表单注册为有效但不更新



这是一个非常奇怪的现象。为什么即使表单是有效的,值也没有更新?它的工作原理,如果我做它在django管理虽然。我甚至没有收到任何错误。表单是有效的,但没有更新。就好像他们用旧的值来更新…

html:

<form action="{% url 'account:displayinfo' request.user.id %}" method="POST" enctype="multipart/form-data">{% csrf_token %}
{{ form.as_p }}
<div class="d-flex justify-content-center">
<button type="submit" class="btn btn-primary btn-sm col-lg-5">Update</button>
</div>
</form>

views.py

def display_information_view(request, *args, **kwargs):
user_id = kwargs.get("user_id")
account = Account.objects.get(pk=user_id)
context = {}
displayinfo = AccountDisplayInfo.objects.get(account=account)
if request.method == "POST":
form = DisplayInformationForm(request.POST, request.FILES, instance=request.user)
if form.is_valid():
info = form.save(commit=False)
info.account = request.user
info.save()
messages.success(request, 'Your profile display information have been updated', extra_tags='editdisplayinfo')
return redirect("account:view", user_id=account.pk)
else:
form = DisplayInformationForm(request.POST, instance=request.user,   
initial={
"instagram": displayinfo.instagram,
}
)
context['form'] = form
else:
form = DisplayInformationForm(
initial={
"instagram": displayinfo.instagram,
}
)
context['form'] = form
return render(request, "account/displayinfo.html", context)

forms.py

class DisplayInformationForm(forms.ModelForm):
class Meta:
model = AccountDisplayInfo
fields = ('instagram',)

models.py

class Account(AbstractBaseUser):
email                  = models.EmailField(verbose_name="email", max_length=60, unique=True)
username               = models.CharField(max_length=30, unique=True)
class AccountDisplayInfo(models.Model):
account = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
instagram = models.CharField(max_length=50, unique=True, blank=True, null=True) #instagram

@receiver(post_save, sender=Account)
def create_AccountDisplayInfo(sender, instance, created, **kwargs):
if created:
AccountDisplayInfo.objects.create(account=instance)

您将表单的实例设置为错误的模型实例。看看你的形式,它是AccountDisplayInfoModelForm,但你通过实例作为instance=request.user。将所有这些代码更改为instance=displayinfo

相关内容

  • 没有找到相关文章

最新更新