I have a deal model that contains two date field. First one is start_date and the other one is end_date. My aim is when I save a deal I want to update a readonly field which shows the substraction of these two date_field.
I try to write a widget however I can only get one of the fields. Here is my widget:
class DueToWidget(AdminDateWidget):
def render(self,name,value,attrs=None):
from datetime import timedelta
output = []
output.append(super(AdminDateWidget, self).render(name,value,attrs))
if value:
due_to = value + timedelta(days=1)
output.append(u'<p>Diff : %s</p>' % due_to)
return mark_safe(u''.join(output))
I'm adding one day to the selected date, how can I get the other field's value ? Or is there any other way to do this ?
If you don't mind having to refresh to see the diff (that is, you only see it after you save the model), then an easier approach is to add a readonly field in the admin, that points to a function, like this:
class MyModelAdmin(ModelAdmin):
readonly_fields = ('dates_difference',)
#add your other fields, or put it in a fieldset
fields = ('dates_difference',)
def dates_difference(self, model_instance):
return model_instance.end_date - model_instance.start_date
Since your goal is just to display extra information in the model's admin this is the place to put the code, not in a field's widget or the model's class.
As the readonly_fields documentation specifies, its behavior is nearly identical as the list_display, that is you can point it to attributes on both the model and the model's admin, and also to callables and methods.
Override save() in the model to save computed data.
def save( self, *args, **kw ):
self.diff = self.end_date - self.start_date
return super( YourModelClass, self ).save( *args, **kw )
Learn more by reading the Django documentation on the subject.
Related
The context is an inventory app of an e-commerce project.
As expected, there's a Product model. In an attempt to normalize the DB schema, I have created these additional models:
ProductType (ForeignKey relationship in Product)
ProductSpecification (a FK in ProductType)
ProductInventory (with a FK to Product)
ProductSpecificationValue (FK to both ProductSpecification and ProductInventory)
I hope this makes sense - each ProductType has many Products, and also many Specifications.
ProductInventory (suggestions of a better name are welcome), with a FK to Product, is a model with SKU and quantity fields. And the fun part - it has a ManyToMany relationship to ProductSpecification, through ProductSpecificationValue.
Now the part where I am lost is adding this whole thing to Django Admin site.
I can create ProductTypes and Products without any problem, and a ProductTypeAdmin has an inline to add those specs:.
# admin.register(ProductType)
class ProductTypeAdmin(admin.ModelAdmin):
inlines = [
ProductSpecificationInline,
]
The problem starts when I try to add a ProductInventory entity. Because it's associated with a given ProductType, I want to limit the choice of inlines to only those which are related to the same ProductType.
class ProductSpecificationValueInline(admin.TabularInline):
model = ProductSpecificationValue
def get_formset(self, request, obj=None, **kwargs): # obj is always the current Product
print(f">>>>>>>>>>>>>>>>>>>>>> get_formset on PSVI")
print(f"obj: {obj}")
print(f"kwargs: {kwargs}")
fset = super().get_formset(request, obj, **kwargs)
assert fset is not None
print(f"fset dir: {dir(fset)}")
# qs = fset.get_queryset(self)
# print(f"qs: {qs}")
return fset
the print of 'dir(fset)' shows that 'get_queryset' function is available - but whe I try to call it, I get an error:
File "/home/devuser/.pyenv/versions/venv38/lib/python3.8/site-packages/django/forms/models.py", line 744, in get_queryset
'ProductSpecificationValueInline' object has no attribute 'queryset'
I know that I need a queryset attached to ProductSpecifications dropdown, so that I can filter the ProductSpecification objects by the ProductType, which is available on the 'obj'. But I guess I'm not overriding a correct method of the ModelAdmin (or it's subclass admin.TabularInline)? So for now I am stcu with all of Specs for all Types showing up.
Well, thank you for your time y'all; in case you want to see the admin.py/models.py, here they are
PS: this way of getting some queryset (not saying it's a right one), kinda "works":
qs = super().get_queryset(request)
, but that queryset comes empty
In a Django app, I'm having a model Bet which contains a ManyToMany relation with the User model of Django:
class Bet(models.Model):
...
participants = models.ManyToManyField(User)
User should be able to start new bets using a form. Until now, bets have exactly two participants, one of which is the user who creates the bet himself. That means in the form for the new bet you have to chose exactly one participant. The bet creator is added as participant upon saving of the form data.
I'm using a ModelForm for my NewBetForm:
class NewBetForm(forms.ModelForm):
class Meta:
model = Bet
widgets = {
'participants': forms.Select()
}
def save(self, user):
... # save user as participant
Notice the redefined widget for the participants field which makes sure you can only choose one participant.
However, this gives me a validation error:
Enter a list of values.
I'm not really sure where this comes from. If I look at the POST data in the developer tools, it seems to be exactly the same as if I use the default widget and choose only one participant. However, it seems like the to_python() method of the ManyToManyField has its problems with this data. At least there is no User object created if I enable the Select widget.
I know I could work around this problem by excluding the participants field from the form and define it myself but it would be a lot nicer if the ModelForm's capacities could still be used (after all, it's only a widget change). Maybe I could manipulate the passed data in some way if I knew how.
Can anyone tell me what the problem is exactly and if there is a good way to solve it?
Thanks in advance!
Edit
As suggested in the comments: the (relevant) code of the view.
def new_bet(request):
if request.method == 'POST':
form = NewBetForm(request.POST)
if form.is_valid():
form.save(request.user)
... # success message and redirect
else:
form = NewBetForm()
return render(request, 'bets/new.html', {'form': form})
After digging in the Django code, I can answer my own question.
The problem is that Django's ModelForm maps ManyToManyFields in the model to ModelMultipleChoiceFields of the form. This kind of form field expects the widget object to return a sequence from its value_from_datadict() method. The default widget for ModelMultipleChoiceField (which is SelectMultiple) overrides value_from_datadict() to return a list from the user supplied data. But if I use the Select widget, the default value_from_datadict() method of the superclass is used, which simply returns a string. ModelMultipleChoiceField doesn't like that at all, hence the validation error.
To solutions I could think of:
Overriding the value_from_datadict() of Select either via inheritance or some class decorator.
Handling the m2m field manually by creating a new form field and adjusting the save() method of the ModelForm to save its data in the m2m relation.
The seconds solution seems to be less verbose, so that's what I will be going with.
I don't mean to revive a resolved question but I was working a solution like this and thought I would share my code to help others.
In j0ker's answer he lists two methods to get this to work. I used method 1. In which I borrowed the 'value_from_datadict' method from the SelectMultiple widget.
forms.py
from django.utils.datastructures import MultiValueDict, MergeDict
class M2MSelect(forms.Select):
def value_from_datadict(self, data, files, name):
if isinstance(data, (MultiValueDict, MergeDict)):
return data.getlist(name)
return data.get(name, None)
class WindowsSubnetForm(forms.ModelForm):
port_group = forms.ModelMultipleChoiceField(widget=M2MSelect, required=True, queryset=PortGroup.objects.all())
class Meta:
model = Subnet
The problem is that ManyToMany is the wrong data type for this relationship.
In a sense, the bet itself is the many-to-many relationship. It makes no sense to have the participants as a manytomanyfield. What you need is two ForeignKeys, both to User: one for the creator, one for the other user ('acceptor'?)
You can modify the submitted value before (during) validation in Form.clean_field_name. You could use this method to wrap the select's single value in a list.
class NewBetForm(forms.ModelForm):
class Meta:
model = Bet
widgets = {
'participants': forms.Select()
}
def save(self, user):
... # save user as participant
def clean_participants(self):
data = self.cleaned_data['participants']
return [data]
I'm actually just guessing what the value proivded by the select looks like, so this might need a bit of tweaking, but I think it will work.
Here are the docs.
Inspired by #Ryan Currah I found this to be working out of the box:
class M2MSelect(forms.SelectMultiple):
def render(self, name, value, attrs=None, choices=()):
rendered = super(M2MSelect, self).render(name, value=value, attrs=attrs, choices=choices)
return rendered.replace(u'multiple="multiple"', u'')
The first one of the many to many is displayed and when saved only the selected value is left.
I found an easyer way to do this inspired by #Ryan Currah:
You just have to override "allow_multiple_selected" attribut from SelectMultiple class
class M2MSelect(forms.SelectMultiple):
allow_multiple_selected = False
class NewBetForm(forms.ModelForm):
class Meta:
model = Bet
participants = forms.ModelMultipleChoiceField(widget=M2MSelect, required=True, queryset=User.objects.all())
I have a fairly simple Django application (v1.3 on Red Hat) for which I'm using the admin application to create and modify database records. One of the fields in my underlying model is a date field. Each time the corresponding field is displayed in the admin's new or edit form I'd like the initial value of this field to be today's date (and time). The user may choose to modify it thereafter, if she desires.
I know that I can set the default field value within my model definition (i.e. in models.py). Which works fine when a database record is first created. But for subsequent invocations of the change form the callable that I've assigned to the default parameter (datetime.datetime.now) obviously doesn't get invoked.
I've looked at - and tried - pretty well all of the many proposed solutions described elsewhere in stackoverflow, without success. Most of these appear to revolve around inserting initialisation code into the ModelForm subclass, e.g. either something like this...
class ConstantDefAdminForm(ModelForm) :
a_date_field = DateField(initial="datetime.datetime.now") # or now()
class Meta :
model = ConstantDef
widgets = {
...
}
or something like this...
class ConstantDefAdminForm(ModelForm) :
class Meta :
model = ConstantDef
widgets = {
...
}
def __init__(self, ...) :
# some initialisation of a_date_field
super(ConstantDefAdminForm, self).__init__(...)
But neither of these approaches work. The initial field value is always set to the value that is stored in the database. My reading of the Django documentation is that the various ways of imposing initial field values in forms only work for unbound forms, not bound forms. Right?
But this capability (to selectively override currently stored values) would seem to be such a popular requirement that I'm convinced that there must be a way to do it.
Has anyone out there succeeded in doing this?
Thanks in advance,
Phil
In Django 1.4 the default=<callable> in model's declaration works well:
class MyModel(models.Model):
dt = models.TimeField(null=True, blank=True, default=datetime.datetime.now)
every time you add a record the default value of the field is updated.
But the use the field's default parameter cause me some problem with the Admin log history of DateField objects, that are every time recorded as changed also when they are not modified. So I've adopted a solution based on https://stackoverflow.com/a/11145346/1838607:
import datetime
class MyModelAdminForm(forms.ModelForm):
class Meta:
model = MyModel
def __init__(self, *args, **kwargs):
super(MyModelAdminForm, self).__init__(*args, **kwargs)
self.fields['dt'].initial = datetime.datetime.now
class MyModelAdmin(admin.ModelAdmin):
form = MyModelAdminForm
fields = ('dt',)
Here's an approach that might work. In your model admin class, change the value of obj.a_date_field before the form is bound. The 'default' value for the date field should be the new value.
class MyModelAdmin(ModelAdmin):
...
def get_object(self, request, object_id):
obj = super(MyModelAdmin, self).get_object(request, object_id)
if obj is not None:
obj.a_date_field = datetime.now()
return obj
Note that get_object is not documented, so this is a bit hacky.
I had a similar problem, and I found the solution from here
I think what you will want to do is this:
class yourAdminModel(admin.ModelAdmin):
fields = ['your_date_field']
def add_view(self, request, form_url="", extra_context=None):
data = request.GET.copy()
data['your_date_field'] = datetime.date.today() # or whatever u need
request.GET = data
return super(yourAdminModel, self).add_view(request, form_url="", extra_context=extra_context)
You should be able to use auto_now with your DateTime Field which according to the docs will automatically set the value to now() each time the form is saved
Since Django 1.7 there is a function get_changeform_initial_data in ModelAdmin that sets initial form values:
def get_changeform_initial_data(self, request):
return {'dt': datetime.now()}
I want to get rid of the "-------------" choice Django adds in a select input representing a Foreign Key on a ModelForm
It's been answered that you can use the empty_label=none option, but I have a ModelForm, not a regular form and overriding the field is not allowed.
I know that I can override the __init__() method of the ModelForm in order to modify a ModelChoiceField's queryset using
self.fields['my_foreign_key'].queryset = ....
But this would be really ugly, as this happens over +10 foreign_keys on the "Main" model, and there's more than a Modelform based on this model
The whole context :
each one of these foreign_key points to the same kind of models : they are particular lists of choices, many models to ease their modification via the admin.
all these models are related to the Main model via a "to_field=code" relation, based on a Charfield which contains a three-letter code (hey, not my fault, I had to use a legacy MS Access DB), this CharField has the blank=True, unique=True options, so I could, for each list, create a "---No information yet---" record which has, you bet, a blank value instead of a three letter code...
The situation is now : I get a select input field with two "blank value" choices : the django one and mine, one after the other.
I just miss a 'empty_label=none` option here too...
If you want to remove the blank choice for all ModelChoiceField you could do something like..
class Form(forms.ModelForm):
class Meta:
model = MyModel
def __init__(self, *args, **kwargs):
super(Form, self).__init__(*args, **kwargs)
modelchoicefields = [field for field_name, field in self.fields.iteritems() if
isinstance(field, forms.ModelChoiceField)]
for field in modelchoicefield:
field.empty_label = None
But that would replace all ModelChoiceFields, so maybe something more fine grained like:
for fieldname in ('field1','field2','field3','field4','field5','field6'):
self.fields[fieldname].empty_label = None
Certainly easier than the __init__ overwrite you mentioned!
Update from Moritz
You can use 2017+ use:
forms.ModelChoiceField(... empty_label=None
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