在 Django 中发布预填充表单

Issue Pre-populating form in Django

我试图从 AgendaForm 获取用户配置文件名称以填充表单字段 'user',但我得到的是“'user':None”。 并且,在视图中,在以下打印中:

            print(form.cleaned_data)
            print(initial_data)

我得到:

{'user': None, 'date': datetime.date(2021, 9, 24), 'time': datetime.time(4, 0), 'comment': 'some comment', 'mode': 'ONLINE'}
{'user': <Profile: Jhon Doe>}

views.py

@login_required(login_url='login')
@allowed_users(allowed_roles=['user'])
def agenda(request):
    user = request.user.profile
    initial_data = {
        'user': user
    }
 
    form = AgendaForm(initial=initial_data)

    if request.method == 'POST':
        form = AgendaForm(request.POST, initial=initial_data)
        if form.is_valid():

            form.save()

            print(form.cleaned_data)
            print(initial_data)

    context = {'form': form}
    return render(request, 'agenda.html', context)

agenda.models.py

class Agenda(models.Model):
    user = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.CASCADE)
    date = models.DateField(null=True, blank=True, default="1900-01-11")
      ...

    def __str__(self):
        return '%s' % (self.user)

main.models.py

#(The OneToOneField 'User' comes from the UserCreationForm Django function)
class Profile(models.Model):
    user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    id = models.AutoField(primary_key=True, null=False, blank=True)
    first_name = models.CharField(max_length=50, null=True, blank=True)
       ...

    def __str__(self):
        return '%s %s' % (self.first_name, self.last_name)

您在 initial 中传递的对象仅用于显示目的以显示一些初始值,而不是作为 fallback/default 值。所以如果在request.POST中没有找到user数据,就会默认为None.

来自docs

These values are only displayed for unbound forms, and they’re not used as fallback values if a particular value isn’t provided. This means if the post data does not have user, it will default to None.

如果你想将agenda的用户FK设置为​​当前用户的个人资料,你可以这样做:

    if request.method == 'POST':
        form = AgendaForm(request.POST, initial=initial_data)
        if form.is_valid():
            agenda = form.save(commit=False)
            agenda.user = request.user.profile
            agenda.save()