[英]How to get username of the user that I am viewing not the current logged in username
I want to get the current profile viewing username and save it in instance.user
.我想获取当前的个人资料查看用户名并将其保存在
instance.user
中。 The problem is that I want to get the username of the user that is going to be rated for other users.问题是我想获取将要为其他用户评级的用户的用户名。
Here is my code:这是我的代码:
def new_rate(request):
if request.method == 'POST':
form = RateForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
try:
instance.rater = request.user
---------> instance.user = !!!!! GET THE CURRENT PROFILE VIEWING USERNAME !!!!!
instance.validate_unique()
instance.save()
form.save_m2m()
return HttpResponseRedirect('/user/' + request.user.username)
You can only get request.user.username
if your user is authenticated.如果您的用户已通过身份验证,您只能获得
request.user.username
。 To check it use request.user.is_authenticated()
.要检查它,请使用
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.
如果你已经使用了 request.POST,你应该 POST 当前配置文件的 ID。
If for example you're viewing URL /users/500
and you have a form.例如,如果您正在查看 URL
/users/500
并且您有一个表单。 Send the ID 500 and then in the view it should get the current profile user like:发送 ID 500,然后在视图中它应该获取当前配置文件用户,例如:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.