如何使用form.ModelForm

时间:2019-01-27 06:53:35

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

我在stackov上尝试了多个链接。但没有任何效果,我无法获得 bio 表单来将数据保存在用户配置文件的数据库中:/

我设法保存了名字和姓氏,但我无法进行个人保存...这是我的代码:

profile.html

<div class="tab-pane active" id="home">
                    <br>
                    <div class="form-group">
                        <div class="col-6">
                            <form method="POST" enctype="multipart/form-data">
                                {% csrf_token %}

                                <label for="first_name">
                                    <h4>First name</h4>
                                </label>
                                {{ user_ProfileForm.first_name |as_crispy_field }}

                                <label for="last_name">
                                    <h4>Last name</h4>
                                </label>
                                {{ user_ProfileForm.last_name |as_crispy_field }}
                                <p>
                                {{ user_BioAndSocialForm.bio |as_crispy_field }}
                                </p>
                                <div class="form-group">
                                    <button class="btn btn-outline-info" type="submit">Update</button>
                                </div>
                            </form>
                        </div>
                    </div>
                    <br>
                    <hr>
                </div>

views.py

@login_required
def profile(request):
    if request.method == 'POST':
        user_ProfileForm = UserProfileForm(request.POST, instance=request.user)
        user_BioAndSocialForm = BioAndSocialForm(request.POST, instance=request.user)

        if user_ProfileForm.is_valid() and user_BioAndSocialForm.is_valid():
            user_ProfileForm.save()
            user_BioAndSocialForm.save()
            messages.success(request, f'Profile updated!')
            return HttpResponseRedirect(request.path_info)
        else:
            messages.error(request, _('Please correct the error below.'))

    else:
        user_ProfileForm = UserProfileForm(instance=request.user)
        user_BioAndSocialForm = BioAndSocialForm(instance=request.user)

    context = {
        'user_ProfileForm': user_ProfileForm,
        'user_BioAndSocialForm': user_BioAndSocialForm
    }

    return render(request, 'users/profile.html', context)

forms.py

class BioAndSocialForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ['bio']

    def __init__(self, *args, **kwargs):
        super(BioAndSocialForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_show_labels = False

models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=500, blank=True)
    birth_date = models.DateField(null=True, blank=True)

    #Image feature upload
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')

    # If we don't have this, it's going to say profile object only
    def __str__(self):
        return f'{self.user.username} Profile'  # it's going to print username Profile

    def save(self, *args, **kwargs):
            super().save(*args, **kwargs)

            img = Image.open(self.image.path)

            if img.height > 300 or img.width > 300:
                output_size = (300, 300)
                img.thumbnail(output_size)
                img.save(self.image.path)

当我点击“更新”时,名字和姓氏保存得很好,但是个人简介却没有保存。

谢谢你的时间

1 个答案:

答案 0 :(得分:0)

我发现了错误!由于个人简介已存在,因此我必须从以下位置获取它:

instance=request.user.profile

感谢Rambarun Komaljeet的提示