一种Django形式的多个实例,用于编辑配置文件模型对象

时间:2019-06-09 08:32:13

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

我使用了profile方法来定制用户模型。我还使用this网站 创建注册 可以同时创建用户和个人资料的表单

现在,我要编写edite_user视图。在此question中,我还发现必须使用modelformset_factory 为此目标创建edit_view

这是我的文件:

#models.py 
class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=500)
    degree = models.CharField()

#forms 
class SignUpAdminForm(UserCreationForm):
    bio = forms.CharField(widget=forms.Textarea)
    degree = forms.CharField()
    #Also_their_is_another_fields_here
    class Meta:
        model = User
        fields = (
            'username',
            'email',
            'password1',
            'password2',
            'bio',
            'degree',
        )
#Views.py
def add_user(request):
    if request.method == 'POST':
        form = SignUpAdminForm(request.POST)
        if form.is_valid():
            user = form.save()
            user.refresh_from_db()
            user.profile.bio = form.cleaned_data['bio']
            user.profile.bio = form.cleaned_data['degree']
            user.save()
            return redirect('view_user')
    else:
        form = SignUpAdminForm()
    template = 'add_user.html'
    context = {'form': form}
    return render(request, template, context)

def edit_user(request, id):
    user = get_object_or_404(User, id=id)
    if request.method == "POST":
        UserFormSet = modelformset_factory(user, form=SignUpAdminForm)
        if UserFormSet.is_valid():
            edit_user = UserFormSet.save(commit=False)
            edit_user.save()
            return redirect('view_user')
    else:
        UserFormSet = modelformset_factory(User, form=SignUpAdminForm)
    template = 'edit_user.html'
    context = {'UserFormSet': UserFormSet}
    return render(request, template, context)

但是此视图不起作用。我还看到以下链接:1234;但他们无法帮助我,我也不明白 该怎么办。 您能帮我写编辑视图吗?

1 个答案:

答案 0 :(得分:1)

我认为您需要设置初始用户

怎么样?

def edit_user(request, id):
    user = get_object_or_404(User, id=id)
    if request.method == "POST":
        UserFormSet = SignUpAdminForm(request.POST, instance = user)
        if UserFormSet.is_valid():
            edit_user = UserFormSet.save(commit=False)
            edit_user.profile.bio = form.cleaned_data['bio']
            edit_user.profile.degree = form.cleaned_data['degree']
            edit_user.save()
            return redirect('view_user')
    else:
        UserFormSet = SignUpAdminForm(instance = user,initial={
            'bio':profile.bio,
            'degree': profile.degree})
    template = 'edit_user.html'
    context = {'UserFormSet': UserFormSet}
    return render(request, template, context)