There is a good opportunity in the Django admin interface to dynamically add new elements to foreign key fields, and I want to do the same using the upload method for the popup and Ajax to submit and validate the form.
This is my use case:
This is the main form for adding an Item. The item has a link and a category.

And this is the second form to add a new category.

I have no problem showing the modality and submitting the form to add a new category. Instead, the problem is to validate the form (in case the user submits an empty form), and updating the selected content to add a new added category.
This is my code:
forms.py
class ItemForm(forms.ModelForm): ref = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}),max_length=255) category = forms.ModelChoiceField(queryset=ItemCategory.objects.all(), empty_label="(choose from the list)") class ItemCategoryForm(forms.ModelForm): category = forms.CharField( max_length=255, required=True, help_text='Add a new category')
views.py
def add(request): if request.method == 'POST': form = ItemForm(request.POST) if form.is_valid(): item= Item() item.ref = form.cleaned_data.get('ref') item.save() return redirect('/item_list/') else: form = ItemForm() form1 = ItemCategoryForm() return render(request, 'item/add.html', {'form': form, 'form1':form1}) def add_category(request): if request.method == 'POST': form1 = ItemCategoryForm(request.POST) if form1.is_valid(): vulnCategory = ItemCategory() ItemCategory.category = form1.cleaned_data.get('category') ItemCategory.save() if request.is_ajax():
urls.py
url(r'^add/$', 'add', name='add'), url(r'^add_category/$', 'add_category', name='add_category'),
And I also added this jQuery function to load the result
$(".add").click(function () { $.ajax({ url: '/items/add_category/', data: $("form").serialize(), cache: false, type: 'post', beforeSend: function () { $("#add_category .modal-body").html("<div style='text-align: center; padding-top: 1em'><img src='/static/img/loading.gif'></div>"); }, success: function (data) { $("#add_category .modal-body").html(data); } }); });
PS: I know that this can be duplicated, but not the answers give me meaning.
jquery python ajax django forms
imanis_tn
source share