I have two models, Course and Student. I want to include a file upload field to the Course form in the admin, to accept a CSV file that I will process and store as one or more records in the Students table. My questions are:
How can I add this "transient" field to the Course model, without it being a column or something in the corresponding table?
Where should I do the file processing? I was thinking perhaps overriding the save_model method in the CourseAdmin class will do it, am I right?
1 - You can override a form class in admin. Create you own ModelForm and add necessary field there
2 - After that, override form_save or form's save() method and process your file there
Related
I have some items connected to users.
When every item is added, timestamp is created through inheritance of BaseModel on auto_now field.
By mistake when i added new field and populated i updated timestamps.
I resolved timestamps with some custom migrations and copy data methods in django.
What i wonder - is there possibility to override save method on admin to do only update_fields (so in other words with that i would not update update_at timestamp),
while on user actions i want to retain original django save method which would update timestamp.
So basically is it possible to have two different save methods?
I know that i can override save method - but i don't know if i can have two save methods at the same time.
ModelAdmin.save_model() might deliver that for you. Check out the docs. Within your admin file, override the save_model function
class ObjectAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
obj.save(update_fields = ['fields', 'to', 'save'])
From looking at the django github, the super of save_model doesn't do much more than call obj.save(), so I don't think you need or want to call super() in this case.
I have this class:
class Object(models.Model):
value=models.IntegerFiled(validators=[MaxValueValidator(100)])
I get user input for the value attribute, create an object according to the user input and save it to the database. The problem is that the user can enter e.g. 120 in the form that is used to get the input from the template/html-page to the view's method. Then an invalid object is saved to the database.
How exactly does the MaxValueValidator work? When does it do anything? What purpose do validators serve?( I really couldn't find any answer to my questions in the documentation)
I do check if the input form is valid in the view, but this doesn't seem to prevent saving invalid objects by just changing the HTML attributes in the form via developer tools in the browser
You should use a ModelForm to generate your form from the model if you want your validators to be run automatically. As per docs:
Note that validators will not be run automatically when you save a model, but if you are using a ModelForm, it will run your validators on any fields that are included in your form.
Validators work with Forms
You can make a form, such as
class ObjectForm(forms.Form):
value = forms.IntegerField(validators=[MaxValueValidator(100)])
Then validate the form based on user input
if ObjectForm(request.POST).is_valid():
# save model object here
Hope this helps.
Basically, I have a FileField and, on creation, the other fields are populated by the data extracted from this file.
Some fields of my model have a non-null contraint (a value has to be extracted from the file for those fields).
I'm using a ModelSerializer and drf fields to add allow_null to the fields (null=False in my model) as I am aware of Order of Serializer Validation in Django REST Framework.
The problem is that I want them to be readonly (I just want a form with a file input, remember ?) and according to the drf documentation :
Read-only fields are included in the API output, but should not be included in the input during create or update operations.
Because of that I sometimes have to put random values in those fields just to pass the validation phase even if those fields will be populated by the correct values (extracted from the file) afterwards.
How can I ignore the non-null constraint from my model and make my fields readonly in my serializer (not changing my model) ?
I safely removed my default validation (validators = []) as, in this particular case, I had to write the whole validation process (export all the data from my FileField to fill the others).
This enabled my serializer to do its job, without raising validation error, through the save method where I added the exported data from my file in my non null fields.
def save(self, **kwargs):
...
self.validated_data['my-non-null-field'] = value
It's a question of design here: you are forcing the serializer to perform some of the controller's job. My recommendation would be that you will overwrite the view's create method and inside there you will build your business logic:
receive the file in the request; validate it's type and content
parse the file in a sequential (low memory footprint!) manner
extract your "other fields" data
at this stage you can call your serializer which have all his fields mapped to the model in the dB properly; delegate any validation to him, together with model creation/update;
This approach will enable you to still request only a POST from your clients while not breaking the "chain of responsibilities" and keep your serializer clean and simple.
Makes sense?
Lets say I have a model with 2 fields: user and money. And I want to edit only users money fields.
If i create a modelformset and exclude for example user field from the form, then does it mean that if someone creates a false form, with user field included it will ignore it and save with bounded instance?
Or do i still need to validate something like this? And if, for example, someone still includes new form with new user in it how do I go about it?
In my Django admin i want to add the URLField box dynamically.that means In my model i have one URLField for that model,In future the links will be added more than one.but i have only one URLField.I wannt it should be flexible to add multiple URLFields.
Note: Inline Model will solve this. but,For the single field it should be extended as a Foreignkey also it occupies lot of time for that optional operation.
I am expecting the custom support to add the model fields only in django admin?
The attached file will expect something!
One approach is to limit the inline formset to 0 extra objects if there is already a record present for that foreign key field by setting the "extra" property: https://docs.djangoproject.com/en/1.3/ref/contrib/admin/#inlinemodeladmin-options