Home > Blockchain >  ModelChoiceField - get request.user.username
ModelChoiceField - get request.user.username

Time:11-30

I need to choose User to form by the request.user.username and save into the database. Here I have a code of forms.py

class Send(forms.ModelForm):
  sender = forms.ModelChoiceField(queryset=User.objects.order_by('username')

Here is the models.py, where I am going to save the data about the user:

class SendM(models.Model):
 sender = models.ForeignKey(User, null=True, blank=False, on_delete=models.CASCADE)

And here is views.py, where I get the data

def form_create(request):
   if not request.user.is_anonymous:
        form = Send(request.POST or None, initial={'sender': request.user.username})

   if request.method == "POST":
      if form.is_valid():
         send = SendM(sender=User.objects.get(username=form.cleaned_data['sender']))
      send.save()
      return redirect("/")

To understand I want to pre-filled the array with the user found in database.

Thank you very much!!

it does only this: [1]: https://i.stack.imgur.com/XY2fl.png

CodePudding user response:

The initial value in the form is the user reference, not the username, because you're using a ModelChoiceField. I don't really remember now if it's the model instance (initial={'sender': request.user}) or the model primary key (initial={'sender': request.user.pk}) .

Then after form.is_valid(), there is no need to get the user from the database again. You just need to call the save method on the form. Django does the rest.


if form.is_valid():
    send = form.save()
  • Related