Home > Mobile >  How to automatically get user in django admin through form
How to automatically get user in django admin through form

Time:11-20

I have a form in my django website where the user requests coins and the information is sent to the admin for me to process. I want to automatically get the user who filled the form without them doing it themselves.

Here's the model.py file:

class Requestpayment (models.Model):
  username= models.ForeignKey(User, on_delete= models.CASCADE, null=True)
  useremail= models.CharField(max_length=100)
  accountmail= models.CharField(max_length=100)
  accountphonenumber=models.CharField(max_length=15)
  coinsrequested=models.ForeignKey(Requestamount, on_delete= models.SET_NULL, null=True)
  created= models.DateTimeField(auto_now_add=True)

  def __str__(self):
    return self.accountmail

the forms.py:

class Requestpaymentform (ModelForm):
    class Meta:
        model = Requestpayment
        fields = '__all__'

and the views.py:

@login_required(login_url='login')   
def redeemcoins (request):
    form = Requestpaymentform
    if request.method =='POST':
        form = Requestpaymentform(request.POST)
        if form.is_valid():
             form = form.save(commit=False)
             username = request.user
             form.save()
             return redirect ('home')


I am pretty sure something is wrong but i don't know what it is (I'm very new at django) anyway the form always shows all the users in the website for the current user to pick who they are.

redeem coins page

I also tried excluding that part of the form but it didn't work it just shows up empty in the admin.

thank you.

CodePudding user response:

You need to assign it to the instance wrapped in the form, so:

@login_required(login_url='login')
def redeemcoins(request):
    form = Requestpaymentform()
    if request.method == 'POST':
        form = Requestpaymentform(request.POST)
        if form.is_valid():
            form.instance.username = request.user
            form.save()
            return redirect('home')
    # …

It makes more sense however to name this field user than username. In the model you can also make the username field non-editable, such that it does not appear in the form:

from django.conf import settings


class Requestpayment(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL, editable=False, on_delete=models.CASCADE
    )
    # …

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

CodePudding user response:

When you use username= models.ForeignKey(User, on_delete= models.CASCADE, null=True), Django add a field named user_id in your database which allow django to find User object for Requestpayment.

You can use user_id field to add a User object in Requestpayment.

  1. You don't need to pass username field in your fields list if you want to get user in view.

    class Requestpaymentform (ModelForm):
        class Meta:
        model = Requestpayment
    
        #fields = '__all__'
        fields = ['useremail',
                  'accountmail',
                  'accountphonenumber',
                  'coinsrequested',
                  'created']
    
  2. Now do this to get user in your view.

    @login_required(login_url='login')
    def redeemcoins(request):
        form = Requestpaymentform()
        if request.method == 'POST':
            form = Requestpaymentform(request.POST)
            if form.is_valid():
                requestpayment = form.save(commit=False)
                requestpayment.user_id = request.user.id 
                requestpayment.save()
                return redirect('home')
    

And it's great to use user instead username because it's a User object and not a simple field.

Please for my English !!!

  • Related