简体   繁体   English

使用Django显示用户特定信息

[英]Displaying User Specific Information with Django

So I know this question is a bit broad, but I am working on a web application using Django and I have hit a snag; 所以我知道这个问题有点广泛,但是我正在使用Django开发Web应用程序,但是遇到了麻烦。 So I want to have user specific data (that is imputed by the user) stored in the users model. 所以我想在用户模型中存储特定于用户的数据(由用户估算)。 (I have completed the user model and it works as expected, and I am using a custom user class so that I can have the needed data fields.) (我已经完成了用户模型,并且可以按预期工作,并且我正在使用自定义用户类,以便可以拥有所需的数据字段。)

So the issue is I want to have one url for a page (ie. www.example.com/profile/) but have the information displayed to be specific to the user that is logged in. And have the user be able to change the info and have the database updated with the changes. 因此,问题是我想为页面提供一个网址(即www.example.com/profile/),但要显示的信息是特定于登录用户的,并且使用户能够更改信息,并使用更改更新数据库。 I have read the Django documentation on sessions but I am unsure if it would work for my use case or exactly how I would implement it. 我已经阅读了有关会话的Django文档,但不确定它是否适用于我的用例或我将如何实现它。 Thanks for the help. 谢谢您的帮助。

               Cheers

On django, be sure that if you log a user, if you use request.user , it will send you the user which is logged in. 在django上,请确保如果您登录用户,并且使用request.user ,它将向您发送已登录的用户。

From this you can easily get all the information you want and then displaying them into inputs on your template giving from a ModificationForm for example. 通过此操作,您可以轻松获取所需的所有信息,然后将其显示在模板的输入中(例如,通过ModificationForm提供)。

Then with this form you can request it in your view like you know with form = ModificationForm(request.POST) . 然后,使用此表单,您可以像使用form = ModificationForm(request.POST)一样在视图中请求它。

I don't know if I have answered your question well, tell me if you want more. 我不知道我是否已经很好地回答了您的问题,请告诉我您是否想要更多。 I already did exactly what you want to do so I can help you. 我已经完全按照您的意愿去做,所以我可以为您提供帮助。

I give you an example below 我在下面给你一个例子

forms.py 表格

class ModificationForm(forms.ModelForm):
  name = models.CharField()
  ...

views.py views.py

def ModificationView(request):
  if request.user.is_authenticated():
    if request.method == 'POST':
      form = ModificationForm(request.POST)
      if form.is_valid():
        [ get all informations from inputs ]
    else:
      formModif = ModificationForm()
      profile = request.user
  else:
    HttpRedirect('404/')
  return render(request, 'profil/', locals())

profil.html profil.html

<html>
  ...
    <!-- Example of one input -->
    <input type="text" name="email" value="{{ profile.user.email }}"
  ...
</html>

I am not sure of all the fonction's name or how to get back the email for example because it's been a while I didn't touch Django but I think this can work with the good names. 我不确定所有功能的名称或如何获取电子邮件,例如,因为已经有一段时间我没有接触过Django了,但是我认为这可以使用好名字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM