You can only get request.user.username
if your user is authenticated. To check it use request.user.is_authenticated()
.
So I think it would look somewhat like this:
def new_rate(request):
if request.method == 'POST':
form = RateForm(request.POST)
current_user = request.user
if form.is_valid() and current_user.is_authenticated():
instance = form.save(commit=False)
try:
instance.rater = current_user
instance.user = current_user
instance.validate_unique()
instance.save()
form.save_m2m()
return HttpResponseRedirect('/user/' + current_user.username)
But to me, your design sounds flawed. If you already use request.POST, you should POST the current profile's ID.
If for example you're viewing URL /users/500
and you have a form. Send the ID 500 and then in the view it should get the current profile user like:
from django.contrib.auth import get_user_model
User = get_user_model()
def new_rate(request):
if request.method == 'POST':
form = RateForm(request.POST)
current_user = request.user
profile_id = request.POST['profile_id']
if form.is_valid() and current_user.is_authenticated():
instance = form.save(commit=False)
profile_user = User.objects.get(pk=profile_id)
try:
instance.rater = current_user
instance.user = profile_user
instance.validate_unique()
instance.save()
form.save_m2m()
# it should return us back to that profile, not the request.user's
return HttpResponseRedirect('/user/' + profile_user.username)