Django - 以两种不同的形式编辑自定义用户配置文件字段

时间:2018-04-25 15:47:39

标签: python django django-models django-forms django-users

我真的很头疼。我整整一周都在搜索信息,但我还是卡住了。

我想创建两个具有2种不同形式但仍与同一用户模型相关联的子页面: /account/register.html - 我已经使用Django通用UserCreationForm了 /account/questionnaire.html - 更新用户城市,网站,电话等其他信息的页面。

注册表格正在运作。我有第二个问题。 发送第二个表单时控制台输出: [25/Apr/2018 17:29:11] "POST /accounts/edituserinfo/ HTTP/1.1" 302 0 [25/Apr/2018 17:29:11] "GET /accounts/profile/ HTTP/1.1" 200 1818 302意味着重定向我猜...

models.py

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete='CASCADE')
    description = models.CharField(max_length=100, default='')
    city = models.CharField(max_length=100, default='')
    website = models.URLField(default='')
    phone = models.IntegerField(default=0)
    def __str__(self):
        return self.user.username

def create_profile(sender, **kwargs):
    if kwargs['created']:
        user_profile = UserProfile.objects.create(user=kwargs['instance'])

post_save.connect(create_profile, sender=User)

forms.py

from django import forms
from accounts.models import UserProfile
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, UserChangeForm

class RegistrationForm(UserCreationForm):
    email = forms.EmailField(required=True)
    field_order = ['username', 'email', 'password1','password2',
        'first_name','last_name']

    class Meta():
        model = User
        fields = {
            'username',
            'first_name',
            'last_name',
            'email',
            'password1',
            'password2',
        }

    def save(self,commit=True):
        user = super(RegistrationForm, self).save(commit=False)
        user.first_name = self.cleaned_data['first_name']
        user.first_name = self.cleaned_data['last_name']
        user.first_name = self.cleaned_data['email']

        if commit:
            user.save()
        return user

class EditProfileForm(UserChangeForm):

    class Meta():
        model = User
        fields = {
            'email',
            'first_name',
            'last_name',
            'password',
        }

class EditUserInfo(forms.ModelForm):

    class Meta():
        model = UserProfile
        fields = {
            'description',
            'city',
            'website',
            'phone',
        }

views.py

from django.shortcuts import render, reverse, redirect, HttpResponse
from accounts.forms import RegistrationForm, EditProfileForm, EditUserInfo
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserChangeForm, PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.decorators import login_required

def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect(reverse('accounts:home'))
    else:
        form = RegistrationForm()

    args = {'form': form}
    return render(request, 'accounts/register.html', args)

def edit_user_info(request):
    if request.method == 'POST':
        form = EditUserInfo(data=request.POST, instance=request.user)
        if form.is_valid():
            form.save()
            return redirect(reverse('accounts:view_profile'))
    else:
        form = EditUserInfo(instance=request.user)
    args = {'form':form}
    return render(request, 'accounts/edit_user_info.html', args)

register.html

{% extends 'base.html' %}

{% block head %}
  <title>Register.html</title>
{% endblock %}


{% block body %}
  <div class="container">
    <h1>Register</h1>
    <form method="post">
      {% csrf_token %}
      {{ form.as_p }}
      <button class="btn btn-primary" type="submit">Register</button>
    </form>
  </div>
{% endblock %}

edit_user_info.html

{% extends 'base.html' %}

{% block head %}
  <title>Edit_user_info.html</title>
{% endblock %}


{% block body %}
  <div class="container">
    <h1>Edit user info</h1>
    <form method="post">
      {% csrf_token %}
      {{ form.as_p }}
      <button class="btn btn-primary" type="submit">Edit User Info</button>
    </form>
  </div>
{% endblock %}

1 个答案:

答案 0 :(得分:0)

EditUserInfo表单适用于UserProfile模型。因此,您应该使用UserProfile实例进行实例化,而不是request.userUser实例)。

from django.contrib.auth.decorators import login_required

@login_required
def edit_user_info(request):
    if request.method == 'POST':
        form = EditUserInfo(data=request.POST, instance=request.user.userprofile)
        ...
    else:
        form = EditUserInfo(instance=request.user.userprofile)
    ...

请注意,我添加了login_required装饰器,以便只有已登录的用户才能访问该视图。