如何在我的view.py中使用.save()正确包含表单

时间:2019-01-24 18:51:38

标签: python django django-crispy-forms

我正在尝试在form.py(AddressForm)中创建一个新表单,但是出现一条错误消息:分配前引用了本地变量'user_AddressForm'

有人可以帮我吗?

用户名,密码和图像可以正常工作,但是地址表中没有永久性数据,并且给我错误

in my forms.py file:

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile

class AddressForm(forms.Form):
    address_1 = forms.CharField(
        label='Address',
        widget=forms.TextInput(attrs={'placeholder': '1234 Main St'})
    )
    address_2 = forms.CharField(
        widget=forms.TextInput(attrs={'placeholder': 'Apartment, studio, or floor'})
    )
    city = forms.CharField()
    state = forms.ChoiceField(choices=states)
    zip_code = forms.CharField(label='Zip')
    class Meta:
            model = User
            fields = ['address_1', 'address_2', 'city', 'state', 'zip_code']




in my views.py

from django.shortcuts import render, redirect
from django.contrib import messages # to display alert messages when the form data is valid
from .forms import UserSignUpForm, UserUpdateForm, ProfileUpdateForm, AddressForm
from django.contrib.auth.decorators import login_required
from django.contrib.auth import update_session_auth_hash

@login_required
def profile(request):
    if request.method == 'POST':
        u_Passform = PasswordChangeForm(request.user, request.POST)
        if u_Passform.is_valid():
            u_Passform.save()
            update_session_auth_hash(request, u_Passform)
            messages.success(request, f'Your password was updated successfully. Please log back in')
            return redirect('profile')

        u_form = UserUpdateForm(request.POST, instance=request.user)
        if u_form.is_valid:
            u_form.save()
            messages.success(request, f'Your account has been updated!')
            return redirect('profile')

        p_form = ProfileUpdateForm(request.POST,
                                   request.FILES,
                                   instance=request.user.profile)
        if p_form.is_valid():
            p_form.save()
            messages.success(request, f'Your Image was updated successfully!')
            return redirect('profile')

        user_AddressForm = AddressForm(request.POST, None)
        if user_AddressForm.is_valid:
            u_form.save()
            messages.success(request, f'Your address has been updated!')
            return redirect('profile')

    else:
        u_Passform = PasswordChangeForm(request.user)
        u_form = UserUpdateForm(instance=request.user)
        p_form = ProfileUpdateForm(instance=request.user.profile)

    context = {
        'user_AddressForm': user_AddressForm,
        'u_Passform': u_Passform,
        'u_form': u_form,
        'p_form': p_form
    }

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



In my profile.html:

<form method="POST" enctype="multipart/form-data">
                {% csrf_token %}
                <fieldset class="form-group">
                    <div class="card text-center">
                        <div class="card-header">
                            Profile Info
                        </div>
                    </div>
                    <p></p>
                    {{ u_form|crispy }} <!-- Public profile: Username, email, website url  -->
                    {{ p_form|crispy }}  <!-- Image form -->
                    {{ u_Passform|crispy }} <!-- Password reset form -->
                    {{ user_AddressForm|crispy }} <!-- Password reset form -->
                </fieldset>
                <div class="form-group">
                    <button class="btn btn-outline-info" type="submit">Update</button>
                </div>
            </form>





This is the models.py:


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

# Profle model with data regarding the user
class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    address1 = models.CharField(
        "Address line 1",
        max_length=1024,
    )


    #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)

现在...如果我只是从forms.py文件中获取表单,则可以在屏幕上显示它,但是它不保存数据。

感谢帮助

1 个答案:

答案 0 :(得分:1)

在请求方法不是'POST'的情况下,您尚未定义user_AddressForm。在p_form = ProfileUpdateForm...下,您应该:

user_AddressForm = AddressForm(instance=request.user.user_profile)

这样,它也可以出现在GET请求中。