Note that there are some explanatory texts on larger screens.

plurals
  1. POPassing a Django Form Class variable to the nested class Meta, how?
    primarykey
    data
    text
    <p>G'day there. I've currently got a bit of an annoyance more than anything. The code below works fully, as expected. Basically it's a ModelForm that dynamically bases it's model on a string received in the url, or based on the class of an instance if that's provided.</p> <p>My question is whether it's possible to abstract this out into another module, forms.py, by passing the model_name variable. I can pass model_name to the form Class no problems, but I can't figure out how to pass it to Meta after that. Is there any easy way to do this? If not this'll do, but it would make my view code heaps neater. </p> <pre><code>@user_passes_test(lambda u: u.is_staff, login_url="%slogin/" % NINJA_ADMIN_URL_PREFIX) def content_form(request, model_name=None, edit=False, call_name=''): if edit: content = Content.objects.get(call_name=call_name) model_name = content.fields.__class__.__name__ class ContentForm(forms.ModelForm): parent = ModelTextField(queryset=Content.objects.all(), widget=JQueryAutocomplete( source_url='%sjson/call_names.json' % NINJA_ADMIN_URL_PREFIX, jquery_opts = {'minLength': 2}, override_label='item.fields.call_name', override_value='item.fields.call_name'), required=False) class Meta(): model = get_ninja_type(model_name) widgets = { 'ninja_type': forms.widgets.HiddenInput(), } def clean_parent(self): call_name = self.cleaned_data['parent'] if call_name: try: parent = Content.objects.get(call_name=call_name) except Content.DoesNotExist: raise forms.ValidationError("The call name '%s' doesn't exist. Choose another parent." % call_name) return parent else: return None if request.method == 'POST': if edit: form = ContentForm(request.POST, instance=content.fields) else: form = ContentForm(request.POST) if form.is_valid(): content = form.save() messages.success(request, "Your new content has been saved.") return HttpResponseRedirect('%scontent/' % NINJA_ADMIN_URL_PREFIX) else: if edit: form = ContentForm(instance=content.fields) else: form = ContentForm(initial={'ninja_type': model_name.lower(), 'author': request.user}) if edit: page_title = 'Edit %s' % model_name else: page_title = 'Create New %s' % model_name return render(request, 'ninja/admin/content_form.html', { 'form': form, 'ninja_type': model_name, 'page_title': page_title, 'edit': edit, 'meta_field_names': NINJA_META_FIELD_NAMES, }) </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload