Django保存了一些字段

时间:2018-04-11 15:27:01

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

当我按“上传”时,我有错误:UNIQUE约束失败:main_profile.user_id。你需要在哪里插入个人资料ID?

            <form method="post" enctype="multipart/form-data">
                {% csrf_token %}
                <label for="pic">Загрузить фото:</label>
                {{ form.as_p }}
                <button type="submit">Upload</button>
            </form>

views.py

def profile(request, user_name):
user = User.objects.get(username=user_name)
if request.method == 'POST':
    form = ImageForm(
        request.POST,
        request.FILES,
        instance=Profile(user=user)
    )

    if form.is_valid():
        form.save() #When I put commit=False the error disappears, but image don`t save
        return redirect('/')
else:
    form = ImageForm()

return render(request, "profile.html", {"profile_data": user,
                                        'form': form})

models.py 用户类扩展

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    photo = models.ImageField(verbose_name="Фото", upload_to="images/profile", default="images/profile/profile.png",
                          blank=True)

forms.py

from django import forms
from main.models import Profile

class ImageForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ('photo', )

1 个答案:

答案 0 :(得分:0)

您可以将ProfileUser之间的关系定义为一对一,这意味着对于每个用户,他们只能拥有一个配置文件。我想,您尝试创建配置文件的用户已经在数据库中有一个,导致它抛出错误。