user13652548
user13652548

Reputation:

Issue Pre-populating form in Django

I'm trying to get the user profile name to populate the form field 'user' from AgendaForm but what I get "'user': None". And, in views, in the following prints:

            print(form.cleaned_data)
            print(initial_data)

I get:

{'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)

Upvotes: 1

Views: 55

Answers (1)

Brian Destura
Brian Destura

Reputation: 12068

The objects you pass in initial is only used for displaying purposes to show some initial values, and not as fallback/default values. So if there is no user data found in request.POST, it will default to None.

From the 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.

If you want to set the agenda's user FK to the profile of the current user, you can do:

    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()

Upvotes: 1

Related Questions