关于在建筑形式中使用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导入表单 从模型进口膳食,配料,食谱
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')
答案 0 :(得分:0)
您是否导入了mealForm
:
有些事情:from app.forms import mealForm
表单是一个函数。所以试试:
args['form'] = mealForm()
注意:请勿使用render_to_response
。它是旧用render
而不是(所以甚至不需要csrf)::
from django.shortcuts import render
def...(request):
....
return render(request,'newMeal.html', {'form': mealForm()})