Django admin – inline inlines (or, three model editing at once)

You need to create a custom form and template for the LinkSectionInline. Something like this should work for the form: LinkFormset = forms.modelformset_factory(Link) class LinkSectionForm(forms.ModelForm): def __init__(self, **kwargs): super(LinkSectionForm, self).__init__(**kwargs) self.link_formset = LinkFormset(instance=self.instance, data=self.data or None, prefix=self.prefix) def is_valid(self): return (super(LinkSectionForm, self).is_valid() and self.link_formset.is_valid()) def save(self, commit=True): # Supporting commit=False is another can of worms. … Read more

update django database to reflect changes in existing models

As of Django 1.7+, built-in migrations support, allows for database schema migrations that preserve data. That’s probably a better approach than the solution below. Another option, not requiring additional apps, is to use the built in manage.py functions to export your data, clear the database and restore the exported data. The methods below will update … Read more

Django Rest framework, how to include ‘__all__’ fields and a related field in ModelSerializer ?

Like @DanEEStart said, DjangoRestFramework don’t have a simple way to extend the ‘all‘ value for fields, because the get_field_names methods seems to be designed to work that way. But fortunately you can override this method to allow a simple way to include all fields and relations without enumerate a tons of fields. I override this … Read more

How to properly use the “choices” field option in Django

I think no one actually has answered to the first question: Why did they create those variables? Those variables aren’t strictly necessary. It’s true. You can perfectly do something like this: MONTH_CHOICES = ( (“JANUARY”, “January”), (“FEBRUARY”, “February”), (“MARCH”, “March”), # …. (“DECEMBER”, “December”), ) month = models.CharField(max_length=9, choices=MONTH_CHOICES, default=”JANUARY”) Why using variables is better? … Read more

Add custom form fields that are not part of the model (Django)

Either in your admin.py or in a separate forms.py you can add a ModelForm class and then declare your extra fields inside that as you normally would. I’ve also given an example of how you might use these values in form.save(): from django import forms from yourapp.models import YourModel class YourModelForm(forms.ModelForm): extra_field = forms.CharField() def … Read more

Django: How to create a model dynamically just for testing

You can put your tests in a tests/ subdirectory of the app (rather than a tests.py file), and include a tests/models.py with the test-only models. Then provide a test-running script (example) that includes your tests/ “app” in INSTALLED_APPS. (This doesn’t work when running app tests from a real project, which won’t have the tests app … Read more