Django ModelForm的字段返回id而不是value

时间:2013-01-05 22:11:04

标签: django django-forms

以下是我的相关模型:

class Post(models.Model):
    subtitle = models.ForeignKey('Subtitle')

class Subtitle(models.Model):
      name = models.CharField(max_length=30)
      def __unicode__(self):
          return self.name

和modelform:

class AddLink(ModelForm):
      subtitle = forms.CharField(label='Subreddit')
      class Meta:
          model = Post
          fields = ('subtitle')

相关观点:

@login_required(login_url='/login/')
123 def edit_link(request, post_id):
124     get_post = Post.objects.get(id=post_id)
125     if request.method == 'POST':
126         form = AddLink(request.POST, instance=get_post)
127         if form.is_valid():
128             form.save()
129             return HttpResponseRedirect('/')
130     else:
131         form = AddLink(instance=get_post)
132 
133     context = { 'form': form, 'post': get_post, }
134     template_name = 'edit_post.html'
135     return render_to_response(template_name, context,
136             context_instance=RequestContext(request))

和模板页面:

  1 <form action="" method="post">
  2     {% csrf_token %}
  3     {{ form.as_p }}
  4     <input type="submit" value="save" />
  5 </form>

这样;在模板中,它返回字幕字段的id。不是它的名字。

我想在文本框中提供字幕名称。 ModelChoiceField 无法提供我想要的内容。

1 个答案:

答案 0 :(得分:2)

首先,删除您需要从fields定义中删除ModelForm。因为它不是你想要的数据。

class AddLink(ModelForm):
  subtitle = forms.CharField(label='Subreddit')
  class Meta:
      model = Post

然后,您需要填充初始表单数据。

@login_required(login_url='/login/')
def edit_link(request, post_id):
    get_post = Post.objects.get(id=post_id)
    if request.method == 'POST':
         form = AddLink(request.POST, instance=get_post)
         if form.is_valid():
             form.save()
             return HttpResponseRedirect('/')
     else:
         # this line changed
         form = AddLink(instance=get_post, initial={ 'subtitle': get_post.subtitle.name })     
     context = { 'form': form, 'post': get_post, }
     template_name = 'edit_post.html'
     return render_to_response(template_name, context,
             context_instance=RequestContext(request))

此外,您可能应该在模型中添加save()方法。

def save(self, commit=True):
    post = super(AddLink, self).save(commit=False)
    subtitle_name = self.cleaned_data['subtitle']
    if post.subtitle:
        post.subtitle.name = subtitle_name
    else:
        post.subtitle = new Subtitle(name=subtitle_name)
    post.subtitle.save()
    post.save()
    return post

编辑:根据评论更改了代码库。