使用database-django填充modelform字段

时间:2013-04-02 05:33:33

标签: django django-models django-forms

我想用数据库数据填充我的模型表字段,并在单选按钮中显示它们。

这是我的模型形式:

class jobpostForm_detail(ModelForm):
    class Meta:

        model = payment_detail
        fields = ('payment_type','country')

    widgets = {

        'payment_type':RadioSelect(),
            'country':RadioSelect(),    




    }

    def __init__(self, *args, **kwargs):
        super(jobpostForm_detail, self).__init__(*args, **kwargs)

        self.fields['country'].queryset = Country.objects.all() // This is not showing data in radio buttons.
        self.helper = FormHelper()
        self.helper.form_class = 'horizontal-form'
        self.helper.form_id = 'id-jobpostform'
        self.helper.form_class = 'blueForms'
        self.helper.form_method = 'post'
             #self.helper.form_action = '/'

        self.helper.add_input(Submit('submit_addcontent', 'Pay'))

        super(jobpostForm_detail, self).__init__(*args, **kwargs)

国家模式:

class Country(models.Model):

    country_id =             models.AutoField(primary_key=True)
    country_name =        models.CharField(max_length=255,null=True, unique=True)

    def __unicode__(self):
        return unicode(self.country_id)
        return unicode(self.country_name)

模板:

   <form method="post" action="/portal/next/post/" class="blueForms" id="id-jobpostform">


    {% csrf_token %}

    {% crispy form %}

    </form>
This is my view:

def payment(request):
    #form = jobpostForm_first()
    country_list = Country.objects.all()
    if request.method == 'POST':
        form = jobpostForm_detail(request.POST)

        #if form.is_valid():
        form.save()
        return HttpResponseRedirect('/thanks/')
    else:
        form = jobpostForm_detail()
        #form.fields['country'].queryset = Country.objects.all()

    c = {}
    c.update(csrf(request))

    return render_to_response('portal/display.html',{
        'form':form,'country_list':country_list
    },context_instance=RequestContext(request))

我的数据也没有进入数据库

我想显示国家/地区名称..它显示的是国家/地区ID

2 个答案:

答案 0 :(得分:0)

在制作对象时,您可以在initial中使用Form

以下是一个例子:

# In views.py
my_form_obj = FormName(request.POST or None, initial = 
                       {
                           'field_name_in_model': Value_from_model, # This field value will be shown in the form when an unbound form is loaded.
                       })

有关详细参考https://docs.djangoproject.com/en/dev/ref/forms/api/#dynamic-initial-values

,请参阅此处

答案 1 :(得分:0)

在models.py中注意 unicode 方法是错误的。你不能两次使用“return”。你应该使用

 def __unicode__(self):
        return self.country_name