简体   繁体   中英

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

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

Here is my 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. 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. There's no submit button because I'm using ajax to submit the form as soon as the value is changed.

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

Comment Thanks @solarissmoke for prompting me to dig deeper. Django was working just fine. My ajax submission was not set up properly and improper jquery was messing with the choice displayed. Thanks for your response and I apologise for any time you wasted. Phil

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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