I followed the guide at https://docs.djangoproject.com/en/dev/ref/contrib/comments/custom/ to set up a comment form on News entries for my current django app. Now, I need to have a comment form with different fields for another type of Object in another part of the site.
How should this be accomplised considering I've overridden the contact form already?
That's a good question; django does seem pretty insistent that you use the same comment form everywhere. You can probably write a single form that shows different fields based on the object it's instantiated with. Try writing an init method along the lines of this:
class CustomCommentForm(CommentForm):
custom_field = forms.CharField(max_length=100)
def __init__(self, *args, **kwargs):
super(CustomCommentForm, self).__init__(*args, **kwargs)
# check what's in kwargs['initial'], and insert fields if needed like this:
if ...:
self.fields['optional_field'] = forms.CharField(max_length=100)
Related
Very similar to this question, but I tried the accepted answer and it did not work. Here's what's going on.
I have a form for tagging people in photos that looks like this:
forms.py
class TaggingForm(forms.Form):
def __init__(self, *args, **kwargs):
queryset = kwargs.pop('queryset')
super(TaggingForm, self).__init__(*args, **kwargs)
self.fields['people'] = forms.ModelMultipleChoiceField(required=False, queryset=queryset, widget=forms.CheckboxSelectMultiple)
...
models.py
class Photo(models.Model):
user = models.ForeignKey(User)
...
class Person(models.Model):
user = models.ForeignKey(User)
photos = models.ManyToManyField(Photo)
...
I want users to be able to edit the tags on their photos after they initially tag them, so I have a page where they can go to view a single photo and edit its tags. For obvious reasons I want to have the already-tagged individuals' checkboxes pre-selected. I tried to do this by giving the form's initial dictionary a list of people I wanted selected, as in the answer to the question I linked above.
views.py
def photo_detail(request,photo_id):
photo = Photo.objects.get(id=photo_id)
initial = {'photo_id':photo.id, 'people':[p for p in photo.person_set.all()]}
form_queryset = Person.objects.filter(user=request.user)
if request.method == "POST":
form = TaggingForm(request.POST, queryset=form_queryset)
# do stuff
else:
form = TaggingForm(initial=initial, queryset=form_queryset)
...
When I try to initialize people as in the above code, the form doesn't show up, but no errors are thrown either. If I take the 'people' key/value pair out of the initial dictionary the form shows up fine, but without any people checked.
Also I'm using Django 1.5 if that matters. Thanks in advance.
What you could do is simply use django forms to handle all of this for you. Please refer to this question. Ideally it boils down to lettings djnago handle your forms and its validation and initial values.
Now this is actually a really good practice to get used to since, you're dissecting all your logic and your presentation. Its a great DRY principle.
Trying to save a bunch of objects but with a custom form:
class CustomForm(forms.ModelForm):
class Meta:
model = Widget
complexify = models.BooleanField()
When complexify is checked, i need to do some complex operations on the widget object.
I can't do:
for object in formset.save(commit=False):
...
because it won't have the complexify flag.
And going through each form seems to be the wrong way:
for form in formset.forms:
...
because it includes the extra (empty) forms and the deleted forms.
Any ideas on how to get this done?
The best answer i could find to this problem was overriding the save on the form:
class CustomForm(forms.ModelForm):
class Meta:
model = Widget
complexify = models.BooleanField()
def save(self, *args, **kwargs):
obj = super(CustomForm, self).save(*args, **kwargs)
obj.complexify = self.cleaned_data.get("complexify")
return obj
then it will be available for you when you handle them:
for object in formset.save(commit=False):
if object.complexify:
object.do_complicated()
I ran into a similar problem, needing to update a field in my forms before saving them. My solution was to do something like what you suggested above, but then skip over forms that hadn't been changed by using the method has_changed, like so:
for form in formset.forms:
object = form.save(commit=False)
if form.has_changed():
#make additions to object here
object.save()
I've never worked with the complexify flag, but your question seemed to run along the lines of my own problem, so I thought I'd pass the info along. Of course, if anyone sees anything that will lead to problems later with this approach, please let me know, I'm still a Django beginner.
How do I allow fields to be populated by the user at the time of object creation ("add" page) and then made read-only when accessed at "change" page?
The simplest solution I found was to override the get_readonly_fields function of ModelAdmin:
class TestAdmin(admin.ModelAdmin):
def get_readonly_fields(self, request, obj=None):
'''
Override to make certain fields readonly if this is a change request
'''
if obj is not None:
return self.readonly_fields + ('title',)
return self.readonly_fields
admin.site.register(TestModel, TestAdmin)
Object will be none for the add page, and an instance of your model for the change page.
Edit: Please note this was tested on Django==1.2
There's two thing to address in your question.
1. Read-only form fields
Doesn't exist as is in Django, but you can implement it yourself, and this blog post can help.
2. Different form for add/change
I guess you're looking for a solution in the admin site context (otherwise, just use 2 different forms in your views).
You could eventually override add_view or change_view in your ModelAdmin and use a different form in one of the view, but I'm afraid you will end up with an awful load of duplicated code.
Another solution I can think of, is a form that will modify its fields upon instantiation, when passed an instance parameter (ie: an edit case). Assuming you have a ReadOnlyField class, that would give you something like:
class MyModelAdminForm(forms.ModelForm):
class Meta:
model = Stuff
def __init__(self, *args, **kwargs):
super(MyModelAdminForm, self).__init__(*args, **kwargs)
if kwargs.get('instance') is not None:
self.fields['title'] = ReadOnlyField()
In here, the field title in the model Stuff will be read-only on the change page of the admin site, but editable on the creation form.
Hope that helps.
You can edit that model's save method to handle such a requirement. For example, you can check if the field already contains some value, if it does, ignore the new value.
One option is to override or replace the change_form template for that specific model.
When creating a flatpage, I want the user to select a template from a predefined list. In order to keep the Flatpage model untouched, I prefer ChoiceField over ModelChoiceField (the latter provides the PK of the template, but I need the name for the template_name field):
class NewFlatpageForm(FlatpageForm):
template_name = forms.ChoiceField(choices = [])
def __init__(self, *args, **kwargs):
self.base_fields['template_name'].choices = ProjectTemplate.objects.values_list('path', 'name')
super(NewFlatpageForm, self).__init__(*args, **kwargs)
I override __init__ or Django populates choices at server start and does not update the list then.
I don't have any admin experience, but I did similar things using the fields attribute when not using admin. However in this case, I got an exception telling fields is not an attribute of the form. __dict__ showed me there's a base_fields attribute and using it works. So, why use base_fields here, and why is fields not present and finally am I doing something hacky?
fields doesn't exist until after you've called super. So just swap the order of the lines, so that super comes first.
A lesson from my own experience: modifying base_fields means that your modifications stick around "forever" (until python exits). In your case, that's probably not a problem, as you are always using the same field name, and you are replacing its values with the assignment from ProjectTemplate...
In my case, I wanted completely different fields based on parameters in the constructor. Since my field names were usually different, each time I instantiated a form, I added new fields but didn't eliminate the ones from the last time.
By calling super early (as indicated here) and then making my dynamic changes to self.fields instead of self.base_fields, I was able to eliminate the problem of an ever growing list of fields. It makes perfect sense now, but I wasn't familiar with all of the syntax details and was hacking through instead of trying to understand it first.
In addition to Joe Germuska. If you truly need to change the form based on the request, you can use a deepcopy to make sure nothing is changed by reference:
def get_form(self, request, obj=None, **kwargs):
form = super(ResourceAdmin, self).get_form(request, obj, **kwargs)
form = copy.deepcopy(form)
if obj:
form.base_fields['email'] = EmailField(initial=obj.user.email)
if not request.user.is_superuser:
form.base_fields['user'].widget = HiddenInput(attrs={'class': 'hide_form_row'})
return form
Given a model with ForeignKeyField (FKF) or ManyToManyField (MTMF) fields with a foreignkey to 'self' how can I prevent self (recursive) selection within the Django Admin (admin).
In short, it should be possible to prevent self (recursive) selection of a model instance in the admin. This applies when editing existing instances of a model, not creating new instances.
For example, take the following model for an article in a news app;
class Article(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField()
related_articles = models.ManyToManyField('self')
If there are 3 Article instances (title: a1-3), when editing an existing Article instance via the admin the related_articles field is represented by default by a html (multiple)select box which provides a list of ALL articles (Article.objects.all()). The user should only see and be able to select Article instances other than itself, e.g. When editing Article a1, related_articles available to select = a2, a3.
I can currently see 3 potential to ways to do this, in order of decreasing preference;
Provide a way to set the queryset providing available choices in the admin form field for the related_articles (via an exclude query filter, e.g. Article.objects.filter(~Q(id__iexact=self.id)) to exclude the current instance being edited from the list of related_articles a user can see and select from. Creation/setting of the queryset to use could occur within the constructor (__init__) of a custom Article ModelForm, or, via some kind of dynamic limit_choices_to Model option. This would require a way to grab the instance being edited to use for filtering.
Override the save_model function of the Article Model or ModelAdmin class to check for and remove itself from the related_articles before saving the instance. This still means that admin users can see and select all articles including the instance being edited (for existing articles).
Filter out self references when required for use outside the admin, e.g. templates.
The ideal solution (1) is currently possible to do via custom model forms outside of the admin as it's possible to pass in a filtered queryset variable for the instance being edited to the model form constructor. Question is, can you get at the Article instance, i.e. 'self' being edited the admin before the form is created to do the same thing.
It could be I am going about this the wrong way, but if your allowed to define a FKF / MTMF to the same model then there should be a way to have the admin - do the right thing - and prevent a user from selecting itself by excluding it in the list of available choices.
Note: Solution 2 and 3 are possible to do now and are provided to try and avoid getting these as answers, ideally i'd like to get an answer to solution 1.
Carl is correct, here's a cut and paste code sample that would go in admin.py
I find navigating the Django relationships can be tricky if you don't have a solid grasp, and a living example can be worth 1000 time more than a "go read this" (not that you don't need to understand what is happening).
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['myManyToManyField'].queryset = MyModel.objects.exclude(
id__exact=self.instance.id)
You can use a custom ModelForm in the admin (by setting the "form" attribute of your ModelAdmin subclass). So you do it the same way in the admin as you would anywhere else.
You can also override the get_form method of the ModelAdmin like so:
def get_form(self, request, obj=None, **kwargs):
"""
Modify the fields in the form that are self-referential by
removing self instance from queryset
"""
form = super().get_form(request, obj=None, **kwargs)
# obj won't exist yet for create page
if obj:
# Finds fieldnames of related fields whose model is self
rmself_fields = [f.name for f in self.model._meta.get_fields() if (
f.concrete and f.is_relation and f.related_model is self.model)]
for fieldname in rmself_fields:
form.base_fields[fieldname]._queryset =
form.base_fields[fieldname]._queryset.exclude(id=obj.id)
return form
Note that this is a on-size-fits-all solution that automatically finds self-referencing model fields and removes self from all of them :-)
I like the solution of checking at save() time:
def save(self, *args, **kwargs):
# call full_clean() that in turn will call clean()
self.full_clean()
return super().save(*args, **kwargs)
def clean(self):
obj = self
parents = set()
while obj is not None:
if obj in parents:
raise ValidationError('Loop error', code='infinite_loop')
parents.add(obj)
obj = obj.parent