用户个人资料的Django模型表格不会预先填充

时间:2015-08-15 19:27:55

标签: django django-models django-forms django-views

我在models.py:

中制作了个人资料模型
class Profile(models.Model):
   user = models.OneToOneField(User)
   title = models.CharField(max_length=20, default='title')
   firstname = models.CharField(max_length=40, default='firstname')
   lastname = models.CharField(max_length=40, default='lastname')
   blurb = models.CharField(max_length=500, default='tell us about yourself')

   #work out how to make filename equal the username
   pic = models.ImageField(default="static/profile/blank.png", upload_to='static/profile/%d%m%y.jpg')  #+ user.pk + '.jpg') 

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

以下是用于编辑已登录用户的个人资料的页面视图:

def editprofile(request):
   u_p = request.user.profile
   template = loader.get_template('registration/editprofile.html')

   if request.method == 'POST':
      form = ProfileForm(request.POST, instance=u_p)
      if form.is_valid():
          form.save()
      else:
          # todo
          None
   else:
      #todo

context = RequestContext(request, {'form': form})
return HttpResponse(template.render(context))

模板片段显示:

<form method="POST" action=".">
  {% csrf_token %}
  <div class="regformout">
    <div class="regform">
        {% for field in form %}
            <div class='cell'> {{ field.label_tag }} </div>
            <div class='nogin'> {{ field.errors }} </div>
            <div class='cell'> {{ field }} </div>
        {% endfor %}
    </div>
  </div>

  <input class="btn btn-large btn-primary" type="submit" value="Save Your Profile" ></input>
</form>

我希望表单字段在相应页面上自动填充当前用户的数据以编辑配置文件。但是,无论我尝试什么,我都无法做到这一点。我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

您的主要问题是,如果用户点击提交按钮,您只填充表单,因此在最初请求视图时,您的表单为空。

from django.shortcuts import render, redirect

def editprofile(request):
    u_p = request.user.profile
    form = ProfileForm(request.POST or None, instance=u_p)
    if request.method == 'POST':
        if form.is_valid():
            form.save()
            return redirect('/')
    return render(request,
                  'registration/editprofile.html', {'form': form})