模型没有用django中的obj.save()保存

时间:2018-04-21 03:06:20

标签: python django django-2.0

我将此模型作为内置用户模型的扩展:

class userprofile(models.Model):

    phone = models.CharField(max_length=20)
    address = models.CharField(max_length=500)
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    @receiver(post_save, sender=User)
    def create_user_profile(sender, instance, created, **kwargs):
        if created:
            userprofile.objects.create(user=instance)

    @receiver(post_save, sender=User)
    def save_user_profile(sender, instance, **kwargs):
        instance.userprofile.save()

用于创建这些模型的django表单类是:

class UserRegister(forms.Form):

    first_name = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={'placeholder': 'First Name'}))
    last_name = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={'placeholder': 'Last Name'}))
    username = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={'placeholder': 'Username'}))
    email = forms.EmailField( required=True, widget=forms.widgets.EmailInput(attrs={'placeholder': 'Email'}))
    password =forms.CharField(required=True, widget=forms.widgets.PasswordInput())
    confirm_password =forms.CharField(required=True, widget=forms.widgets.PasswordInput())

    class Meta:
        model=User
        fields=['first_name','last_name','username','email','password','confirm_password']




   def clean(self):
        cleaned_data = super(UserRegister, self).clean()
        password = cleaned_data.get("password")
        confirm_password = cleaned_data.get("confirm_password")
        if password != confirm_password:
            raise forms.ValidationError(
                "password and confirm_password does not match"
            )



class UserProfileCreate(forms.Form):
    mobile = forms.CharField(required=True, widget=forms.widgets.NumberInput(attrs={'placeholder': 'Mobile No.'}))
    address = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={'placeholder': 'Delivery address'}))

    class Meta:
        model= userprofile
        fields=['mobile', 'address']

HTML就像:

<form class="form-horizontal" method="POST" action="{% url 'createuser' %}">



                            {% csrf_token %}



                           {% for hidden in form.hidden_fields %}
                              {{ hidden }}
                            {% endfor %}

                            {% for field in form.visible_fields %}
                              <div class="form-group">
                                <label for="{{ field.id_for_label }}">{{ field.label }}</label>
                                {{ field|add_class:'form-control' }}
                                {% for error in field.errors %}
                                  <span class="help-block">{{ error }}</span>
                                {% endfor %}
                              </div>
                            {% endfor %}

                            {% for field in formplus.visible_fields %}
                              <div class="form-group">
                                <label for="{{ field.id_for_label }}">{{ field.label }}</label>
                                {{ field|add_class:'form-control' }}
                                {% for error in field.errors %}
                                  <span class="help-block">{{ error }}</span>
                                {% endfor %}
                              </div>
                            {% endfor %}

                            <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <button type="submit" class="btn btn-primary">
                                    Register
                                </button>
                            </div>
                        </div>
                    </form>

视图如下:

def create(request):
    if request.method == "GET":
        return render(request, 'userextension/usercreate.html', {'form' : UserRegister, 'formplus' : UserProfileCreate , 'message': 'Create your account'})

    else:
        user = UserRegister(request.POST)
        profile= UserProfileCreate(request.POST)
        if user.is_valid():
            if user.save():
                return render(request, 'userextension/usercreate.html', {'form' : UserRegister, 'message': 'Account created successfully'})




        return render(request, 'userextension/usercreate.html', {'form' : UserRegister, 'message': 'Could not create account'})

我按照一些django教程后做了这件事。我在任何地方都没有看到任何不正确的代码,但我无法将这样提交的表单保存为模型。我没有在views.py中进行userprofile.save(),因为它通过OneToOneField连接到用户,并且我已提到在创建用户时自动创建userprofile。

既不会引发任何错误,也不会创建帐户。你们可以给它脱脂吗?

1 个答案:

答案 0 :(得分:1)

这里有几个问题。主要的一点是您的用户表单无效。但是你没有将无效表单传回模板,因此你无法理解为什么它无效。您应该传递已经创建的实例,而不是传递类。

return render(request, 'userextension/usercreate.html', {'form' : user, 'message': 'Could not create account'})

第二个问题是你从不对配置文件表单做任何事情 - 你没有检查它是否有效,你没有保存它。

另请注意,您应该在成功发布后重定向。