Django UpdateView Profile-Save-Data-No-Work

时间:2018-02-14 20:01:48

标签: django django-class-based-views

Holla ppl。我是django的新手并尽力而为,但此时我陷入困境并需要一些帮助。 问题是:我无法通过模板更新我的用户配置文件。当我做一些改变---在控制台我可以看到POST,然后我通过" success_url"重定向。没有显示错误。但是没有保存新数据。 django 1.11.4

这里是我的代码:

  

型号:

class Profile(models.Model):
user       = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.ImageField(blank=True)
location = models.CharField(max_length=30, blank=True)
bio        = models.TextField(max_length=500, blank=True)
active     = models.BooleanField(default=True)
timestamp  = models.DateTimeField(auto_now_add=True)

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

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

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

查看:

class RegisterView(CreateView):
    template_name = "registration/register.html"
    form_class = RegisterForm
    success_url = '/'

    def dispatch(self, *args, **kwargs):
        # if self.request.user.is_authenticated():
        #     return redirect("/logout")
        return super(RegisterView, self).dispatch(*args, **kwargs)


class ProfileUpdateView(UpdateView):
    model = Profile
    form_class = ProfileForm
    template_name = 'profiles/profile-detail-update.html'
    success_url = '/'

    def get_object(self, **kwargs):
        username = self.kwargs.get("username")
        if username is None:
            raise Http404
        return get_object_or_404(User, username__iexact=username)
  

表单

class RegisterForm(forms.ModelForm):
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)

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

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2

    def save(self, commit=True):
        user = super(RegisterForm, self).save(commit=True)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user

class ProfileForm(forms.ModelForm):

    class Meta:
        model = Profile
        fields = ('avatar', 'location', 'bio', 'active',)
  

URL

url(r'^(?P<username>[\w-]+)/$', ProfileUpdateView.as_view(), name='update'),
  

模板:

{% extends 'base.html' %}

{% block content %}
    <p>name: {{ user.username }}</p>
    <p>location: {{ user.profile.location }}</p>
    {% if user.profile.avatar %}
        <img style="width: 200px" src="{{ user.profile.avatar.url }}"/>
    {% endif %}
<hr/>
    {% include 'snippets/form.html' %}
{% endblock %}
  

包含的摘录:

<div class="form pt-2">
{% if form.errors.non_field_errors %}
    {{ form.errors.non_field_errors }}
{% endif %}
    <form method='POST' action='' enctype='multipart/form-data'> {% csrf_token %}
                {{ form.as_p }}
    <button class='btn btn-success' type='submit'>Save</button>
    <button onclick="window.history.back();" class="btn btn-danger" type="button">Go back</button>
    </form>
</div>

SOS。

1 个答案:

答案 0 :(得分:1)

ProfileUpdateView中,您将User实例传递给表单,而不是Profile实例:

class ProfileUpdateView(UpdateView):
    # ...

    def get_object(self, **kwargs):
        username = self.kwargs.get("username")
        if username is None:
            raise Http404
        return get_object_or_404(Profile, user__username__iexact=username)