简体   繁体   English

以Django形式预填充CharField的正确选择

[英]Pre-populate the correct choice for a CharField in a Django form

I have a model which contains a CharField consisting of choices as in the example below 我有一个包含由选择组成的CharField的模型,如下例所示

class SomeModel(models.Model):
    some_field = models.CharField(choices=(('Name1', 'Name1'),
                                           ('Name2', 'Name2'),
                                           ('Name3', 'Name3')
                                          )
                                 )

Here is my ModelForm 这是我的ModelForm

class SomeModelForm(forms.ModelForm):

    class Meta:
        model = SomeModel

Here is my basic view which attaches an instance to the form: 这是将实例附加到表单的基本视图:

def some_view(request, model_id):
    somemodel = SomeModel.objects.get(id=model_id)
    form = SomeModelForm(instance=somemodel)
    context = {'form': form}
    return render(request, 'page.html', context)

When the form is rendered the dropdown is not pre-populated. 呈现表单时,不会预先填充下拉列表。 It is not a case of something being wrong with my code as all other form fields (omitted from this example) ARE pre-populated. 这不是我的代码有问题的情况,因为所有其他表单字段(此示例中都省略了)都已预先填充。 I know I could make the CharField a ForeignKey and then Django would pre-populate the dropdown correctly but I don't want to do this. 我知道我可以将CharField设置为ForeignKey,然后Django会正确地预先填充下拉列表,但是我不想这样做。 Is there any way to make the form show the correct choice? 有什么方法可以使表格显示正确的选择? Any help would be greatly appreciated! 任何帮助将不胜感激!

EDIT : As @solarissmoke requested here is how I rendered the form. 编辑 :正如@solarissmoke在这里要求的是我如何渲染表格。 There's no submit button because I'm using ajax to submit the form as soon as the value is changed. 没有提交按钮,因为一旦值更改,我就使用ajax提交表单。

<form action="{% url 'some_location' %}" method="post">
    {{ form.some_field }}
</form>

Comment Thanks @solarissmoke for prompting me to dig deeper. 注释感谢@solarissmoke提示我进行更深入的研究。 Django was working just fine. Django工作得很好。 My ajax submission was not set up properly and improper jquery was messing with the choice displayed. 我的ajax提交设置不正确,并且jquery不正确使显示的选项混乱。 Thanks for your response and I apologise for any time you wasted. 感谢您的回复,对于您的任何浪费,我深表歉意。 Phil 菲尔

我刚刚制定了一个jQuery解决方案,但如果可能的话,我想要更像Django的东西。

$("#id_some_field").val("{{ form.some_field.value }}");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM