[Django]-Django ModelChoiceField allow objects creation

0👍

This seems like it’d be easier without using a ModelForm. You could create a list of all of your Type objects then pass that to the template as a context variable. Then, you could use that list to construct a <select> element. Then use jquery and selectize to add the necessary attributes to the form.

#views.py
...
types = Type.objects.all()
...



#template.html
...
<form action="" method="POST">{% csrf_token %}
    <input type='text' name='title'>
    <select name='type' id='id_type'>
        {% for type in types %}
            <option value="{{type.id}}">{{type.name}}</option>
        {% endfor %}
    </select>
    <input type='submit'>
</form>
<script type='text/javascript'>
$('#id_type').selectize({
    create: true
    });
</script>
...

Then when you get a form submission, you can process it in a simple view function:

if request.method == POST:
        title_post = request.POST.get('title','')
        type_post = request.POST.get('type',None)
        if type_post is not None:
            try:
                #If an existing Type was selected, we'll have an ID to lookup
                type = Type.objects.get(id=type_post)
            except:
                #If that lookup failed, we've got a user-inputted name to use
                type = Type.objects.create(name=type_post)
            new_doc = Document.objects.create(title=title_post, type=type)

Leave a comment