无法以编辑形式获取数据

时间:2016-12-04 20:07:39

标签: django

我正在尝试为现有用户创建一个编辑表单,我有User模型,并且我将它与一个配置文件相关联。 问题是在渲染的html中配置文件的字段是空的,但是当我创建一个新用户时,我填写了这些字段,当我进入管理时,我发现字段已填满。
enter image description here models.py

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


class Profile(models.Model):
    DEPARTMENT_CHOICES = (('MI', 'Math et info'),
                          ('ST', 'Science et Tech'),
                          ('SM', 'Science de la matiere'))

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    teacher = models.BooleanField(default=False)
    description = models.TextField(blank=True)
    department = models.CharField(max_length=35, choices=DEPARTMENT_CHOICES, blank=True)
    picture = models.ImageField(upload_to='profile-images', blank=True)

    def __str__(self):
        return self.user.username


views.py

def profile_view(request):
    if request.method == 'POST':
        user_form = EditUserForm(request.POST, instance=request.user)
        ins = Profile.objects.get(pk=5)
        profile_form = EditProfileForm(request.POST, request.FILES, instance=ins)

        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            user.save()

            profile = profile_form.save(commit=False)
            profile.user = user

            if 'picture' in request.FILES:
                profile.picture = request.FILES['picture']

            profile.save()
            return redirect(home)
    else:
        user_form = EditUserForm(instance=request.user)
        profile_form = EditProfileForm(request.FILES, instance=request.user)

    return render(request, 'account/profile.html', {'user_form': user_form,
                                                    'profile_form': profile_form})


forms.py

class EditProfileForm(forms.ModelForm):

    class Meta:
        model = Profile
        fields = ('description', 'department', 'picture', )


class EditUserForm(forms.ModelForm):

    class Meta:
        model = User
        fields = ('username', 'email', )


profile.html

{% extends 'manhal/base.html' %}
{% load staticfiles %}
{% load crispy_forms_tags %}

{% block content %}

    <div class="col-md-6">

            <form method="post" enctype="multipart/form-data" action="{% url 'profile' %}" class="form-horizontal">{% csrf_token %}

                <fieldset>
                    <legend>User Profile</legend>

                    {{ user_form|crispy }}
                    {{ profile_form|crispy}}
                    <input type="submit" value="Save" class="btn btn-primary">
                </fieldset>
            </form>

    </div>
{% endblock %}

1 个答案:

答案 0 :(得分:1)

首先,您的if / else块正在检查请求是否为POST。由于else阻止不是POST,因此您不希望将任何POST数据传递到表单中。这将使表单认为它没有数据绑定。

此外,您似乎将request.user作为实例传递给ProfileForm,但ProfileForm元类上的模型期待Profile个对象。

你能解决这两件事,看看它是否有效?如果它不起作用,请发布更多代码(如模板)。