Django:表单没有保存到数据库

时间:2016-01-12 23:36:19

标签: python django forms save

我在这里看到过类似的问题,但我仍然无法解决我的问题。当我在视图中保存 PhotographerProfileForm 时,表单会正确呈现,但在点击更新/提交后,实际上并未保存任何内容。

也没有显示任何错误。

我现在所拥有的字段是预填充的,我希望能够在数据库中保存这些字段,但没有任何反应,目前只能从管理面板更新。

models.py

from __future__ import unicode_literals
from django.contrib.auth.models import User

from django.db import models


# Create your models here.
class PhotographerProfile(models.Model):
    user = models.OneToOneField(User)
    location = models.CharField(max_length=200)
    bio = models.TextField(max_length=500)

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

User.profile = property(lambda u: PhotographerProfile.objects.get_or_create(user=u)[0])


from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=User)
def create_profile(sender,instance,created,**kwargs):
    if created:
        profile, new = PhotographerProfile.objects.get_or_create(user=instance)

urls.py

urlpatterns = [
url(r'^profile/$', 'photoprofile.views.photographer_profile', name = 'photographer_profile'),
url(r'^profile/portfolio/$', 'photoprofile.views.photographer_portfolio', name='photographer_portfolio'),

views.py

@login_required


def photographer_profile(request):
    photographerProfile = PhotographerProfile.objects.get(user=request.user)
    form = PhotographerProfileForm(initial={'bio':photographerProfile.bio,     'location':photographerProfile.location})#This means you can prepoulate it
    return render_to_response('photographerprofile.html',{'form':form},  RequestContext(request))

    if request.method == 'POST':
        form = PhotographerProfileForm(request.POST, instance = request.user.profile,)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/accounts/profile')

    else:
        user = request.user
        profile = user.profile
        form = PhotographerProfileForm()

    return render(request, 'photographerprofile.html', {'form':form})

def photographer_portfolio(request):
    photographerProfile = PhotographerProfile.objects.get(user=request.user)
    return render_to_response('photographerportfolio.html', {'photographerProfile':photographerProfile}, RequestContext(request))

forms.py

class PhotographerProfileForm(forms.ModelForm):

class Meta:
    model = PhotographerProfile
    exclude = ('user',)

photographerprofile.html

{% extends 'base.html' %}
{% load crispy_forms_tags %}

{% block content %}

<h2> Profile</h2>

{% for field in form %}
{{ field.error}}

{% endfor %}

<form action='/accounts/profile/' method='post'>
{% csrf_token %}
{{form|crispy}}

    <input type='submit' value='Update'/>

    <p>Click <a href='/accounts/profile/portfolio/'>here</a> to view portfolio.    </p>

</form>

{% endblock %}

1 个答案:

答案 0 :(得分:0)

在表单处理之前,您将在视图的第三行返回。删除该行。