Django更新已有的用户信息

时间:2013-08-13 03:20:29

标签: django django-forms

好的,我可以在用户输入用户名,电子邮件,姓/名的情况下进行注册。

我的问题是如何让用户能够编辑他们的电子邮件,姓/名?

谢谢!

1 个答案:

答案 0 :(得分:1)

默认的django用户没有什么特别之处。实际上,django auth应用程序是一个普通的django应用程序,它有自己的modelsviewsurlstemplates,就像你要编写的任何其他应用程序一样。

要更新任何模型实例 - 您可以使用通用UpdateView,其工作方式如下:

  1. 您创建的模板将显示将用于更新模型的表单。
  2. 您可以(可选)创建自己的表单类 - 这不是必需的。
  3. 您将要更新的模型与实例一起传递到此视图。
  4. 该视图负责其余的逻辑。
  5. 以下是您在实践中如何实施它。在views.py

    from django.views.generic.edit import UpdateView
    from django.core.urlresolvers import reverse_lazy
    from django.contrib.auth.models import User
    
    class ProfileUpdate(UpdateView):
        model = User
        template_name = 'user_update.html'
        success_url = reverse_lazy('home') # This is where the user will be 
                                           # redirected once the form
                                           # is successfully filled in
    
        def get_object(self, queryset=None):
            '''This method will load the object
               that will be used to load the form
               that will be edited'''
            return self.request.user
    

    user_update.html模板非常简单:

    <form method="post">
      {% csrf_token %}
      {{ form }}
      <input type="submit" />
    </form>
    

    现在剩下的就是在urls.py

    中进行连线
    from .views import ProfileUpdate
    
    urlpatterns = patterns('',
                           # your other url maps
                           url(r'^profile/', ProfileUpdate.as_view(), name='profile'),
    )
    
相关问题