首页 文章

Django ModelChoiceField问题

提问于
浏览
0

关于在我正在构建的形式中使用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进口形式从模型进口膳食,配料,食谱

class 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导入模型导入日期时间

在此处创建模型 .

class recipe(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')

1 回答

  • 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()})
    

相关问题