【问题标题】:Trouble with Django ModelChoiceFieldDjango ModelChoiceField 的问题
【发布时间】:2014-04-29 16:24:21
【问题描述】:

关于在我正在构建的表单中使用 django 的 modelchoicefield 的初学者问题。

我只需要让 django 在表单中显示成分的下拉列表。我已经到了页面呈现但表单没有呈现的地步,我之前遇到过错误,所以我现在有点困惑。我希望得到一些指导。

使用 python 2.7.6 和 django 1.6.2。如果我遗漏了什么,请告诉我。

谢谢!

代码如下:

观看次数:

    args = {}
#add csrf sercurity
args.update(csrf(request))

args['form'] = form
return render_to_response('newMeal.html', args)

表格:

从 django 导入表单 从模型中导入膳食、配料、食谱

类mealForm(forms.ModelForm):

breakfast = forms.ModelChoiceField(queryset=recipe.objects.all())
# Lunch = forms.ModelChoiceField(queryset=recipe.objects.all())
# Dinner = forms.ModelChoiceField(queryset=recipe.objects.all())


class Meta:
    model = meals
    fields = ('Breakfast','Lunch','Dinner','servingDate')

class recipeForm(forms.ModelForm):

class Meta:
    model = recipe
    fields = ('Name', 'Directions')

模板:

    {% extends "base.html" %}

{% block content %}

<p>New Meals go here!</p>

<form action="/meals/newmeal/" method="post">{% csrf_token %}
    <table class="selection">
        {{form.as_table}}


        <tr><td colspan="2"><input type="submit" name="submit" value="Add Meal"></td></tr>
    </table>
</form>

{% endblock %}

型号;

从 django.db 导入模型 导入日期时间

在这里创建您的模型。

类配方(models.Model):

Name = models.CharField(max_length=200)
Directions = models.TextField()
pub_date = models.DateTimeField(auto_now_add = True)

def __unicode__(self):
    return (self.id, self.Name)

类成分(models.Model):

Name = models.CharField(max_length=200)
Quantity = models.IntegerField(default=0)
Units = models.CharField(max_length=10)
Recipe = models.ForeignKey(recipe)

def __unicode__(self):
    return self.Name

上课餐(models.Model):

Breakfast = models.CharField(max_length=200)
Lunch = models.CharField(max_length=200)
Dinner = models.CharField(max_length=200)
servingDate = models.DateTimeField('date published')

【问题讨论】:

  • 你遇到了什么错误?
  • 我收到错误 200
  • 在这种情况下,我没有收到错误消息。这很奇怪,当我检查呈现的页面源时,表单在那里,但只有开始和结束标签,没有内容。认为我只是在滥用 ModelChoiceField。
  • 粘贴你的models.py,因为你有一些基本问题,但我想确保你的模型没有任何问题:)
  • 将模型添加到我的原始帖子中。希望对您有所帮助。

标签: python django forms


【解决方案1】:

你导入了mealForm:

类似:from app.forms import mealForm

form 是一个函数。所以试试:

args['form'] = mealForm()

注意:不要使用render_to_response。它是旧的使用 render 代替(所以甚至不需要 csrf)::

from django.shortcuts import render
def...(request):
....
return render(request,'newMeal.html', {'form': mealForm()})

【讨论】:

  • 感谢 pro-tip re render_to_response。我仔细检查了,我正在导入表单,我得到了同样的结果,页面呈现但没有内容。如果我从表单中删除 ModelChoiceField ,一切都会变得很花哨。我将整个 form.py 代码添加到我的原始帖子中,我确定这是我犯的一些奇怪的菜鸟错误。
猜你喜欢
  • 2012-09-12
  • 2014-11-15
  • 1970-01-01
  • 1970-01-01
  • 2021-01-06
  • 2013-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多