-1

I'm trying to get the current loggedin user's username as a CharField in my model so I can track all the reviews from one user later on. But I'm not understanding how to do it. I don't understand this answer. How does the init function insert the users name into his model?

forms.py:

class ReviewForm(forms.ModelForm):
    user_name = forms.CharField( GET THE CURRENT USERS USERNAME HERE )
    burger = forms.CharField(max_length=150, help_text="What type of burger was it?")

    class Meta:
        model = Review
        fields = ('place', 'burger',)
Community
  • 1
  • 1
user1410712
  • 185
  • 1
  • 2
  • 10

1 Answers1

1

You need to do it the other way around. Remove the field from the form itself (because the user will not be entering it in).

The current logged in user will always be available to your view code, so simply do this:

@login_required
def process_form(request):
    form = ReviewForm(request.POST or None)
    if form.is_valid():
        obj = form.save(commit=False)
        obj.user_name = request.user
        obj.save()
        return redirect('home')
    return render(request, 'form.html', {'form': form})

The login_required decorator will make sure that your view can only be executed when a user is logged in.

Here I am assuming your Review model has a field called user_name which is a ForeignKey to your User model.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284