Reputation: 145
I'm trying to customize the Django admin edit page for a model representing a scholarly paper such that there is a text box that can fill in as a 'shortcut' to the actual information in the model (based on a BibTeX bibliography of it). That is, rather than tediously fill out each field in the "Publication" model, the user can simply copy/paste a BibTeX entry, click on a button, and have the relevant fields filled in automatically.
I've managed to create a text box and button that don't represent part of the model by editing the template, but I can't figure out how to make the button do anything without leaving the page, since I can't override the view. I want it to populate the fields of the form but stay on the same page so a user can look over and edit what's parsed.
How would I go about making a button that fills out a form in the Django admin dynamically?
Sorry if there is a super easy solution to this--my team and I are new to Django!
Upvotes: 1
Views: 1265
Reputation: 37319
You can't do it directly in Django without leaving the page, or at least submitting and redisplaying it. You could use Javascript to parse the contexts of the text box and assign them to your admin input fields, if you're being strict about not submitting the form.
That said, I would do this by defining the form for my admin class, then specializing the save_model
method. Something like this:
class PublicationAdminForm(forms.ModelForm):
class Meta:
model = Publication
bibtex_entry = forms.CharField(widget=forms.Textarea)
class PublicationAdmin(admin.ModelAdmin):
form = PublicationAdminForm
def save_model(self, request, obj, form, change):
bibtex = form.cleaned_data['bibtex_entry']
values = parse_bibtex(bibtex)
obj.author = values['author']
# etc etc, or whatever format you want to use to represent the values you're pulling from the BibTeX entry
super(PublicationAdmin, self).save_model(request, obj, form, change)
Obviously the exactly code inside save_model will depend on how you're pulling information out of the BibTeX entry - I wanted to demonstrate assigning attribute values on the object based on form content prior to saving it.
If the fields that are to be derived from BibTeX are required, it gets a little harder - you'd have to specify a clean
method on the form that can tell whether or not all the values that will be needed from BibTeX can be derived from what got submitted. Which is probably a good idea anyway, although if the fields aren't required you might want to limit that parsing to the form's clean_bibtex
method. Or create a custom field type that knows how to parse the BibTeX into something like a dictionary in its to_python
method, but that's a bit more advanced.
And of course there are other settings you might want on your admin.
Upvotes: 1