Dynamic read-only field in Django Admin - django

In Django Admin for a Model I want all fields to be:
editable on creation
some of them on updating ( based on the instance fields values on creation).
For example:
2-1. If attribute a has a value, the fields corresponding to attributes c and b to be readonly
2-2. If attributes are empty after creation, should not be editable on updating
I know that for normal forms there is the Field disabled attribute.
I know I need to overwrite Admin form, but I don't have an idea, to know is created or update when form is initialized.
Usually I get the value using clean(), but here I need to get them on initialization in case of updates.

So it is like this:
You can create custom FORMS see here https://docs.djangoproject.com/en/1.8/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form
After that you can add your logic of which form to use by overriding the get_form method. see here https://docs.djangoproject.com/en/1.8/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_form
However you need to make sure your DB will accept the partially submitted data. You can DROP NULL on the specific columns.

Related

Where is ID saved in django ModelAdmin autocomplete_fields?

I am rewriting some administration interface to django 2.2, currently using django autocomplete_fields admin feature. Simply said I have ModelAdmin object OrderAdmin, which has nested TabularInline ProductAdmin: variable-length table of products which might be added to order. Each of these ProductAdmin holders just contains ForeignKey to actual product class, with some other attributes.
Now I wonder: where does django store id - ForeignKey - of item selected with autocomplete field? It doesn't mark OPTION in selectbox as selected, and although there is suspicious hidden input field with #cashregisterproduct_set-0-id on page, it doesn't have any value. Or is there some special way how to access it? I was thinking about adding id to __str__ method of model and parsing, but thats just ugly.
Thanks for tip.
EDIT: to make it 100% clear, where from does django get ForeignKey of object selected through autoselect_field, when creating new object from ModelAdmin?
I got misguided thinking that this is managed by django. Selected data might be accessed by using select2 framework:
selected_value = $('.myselectbox').select2().val();
related: https://stackoverflow.com/a/47451658/16268461

How to pre-fill Django dynamically added formset fields on HTML page

I am using Django inline formset with option to add additional forms at runtime. Some of the fields display the default values as already defined in the related models. However, when new rows of formsets are added, most of the fields are "blank" (i.e. the default values do not show up in those fields), except the date field which show the date widget.
As in the image above, a new row containing the blank (red rectangle) field fails to show the default value (as otherwise available in the rows available at page load).
I am currently using jQuery to fill the blank fields capturing the "rowadded" function but find it quite a mess, as managing the code is cumbersome.
Is there a ready to use function/plugin available in Django which can be used to fill the fields on addition of new row/s (at runtime)?
When you render the form, i.e. form = MyForm(), specify the instance of the form like so:
form = MyForm(instance=Model.objects.get(pk=1).
This will populate your form with the object from Model with a primary key of 1.

django generic view update/create: update works but create raises IntegrityError

I'm using CreateView and UpdateView directely into urls.py of my application whose name is dydict. In the file forms.py I'm using ModelForm and I'm exluding a couple of fields from being shown, some of which should be set when either creating or updating. So, as mentioned in the title, update part works but create part doesn't which is obvious because required fields that I have exluded are sent empty which is not allowed in my case. So the question here is, how should I do to fill exluded fields into the file forms.py so that I don't have to override CreateView?
Thanks in advance.
Well, you have to set your required fields somewhere. If you don't want them to be shown or editable in the form, your options are to set them in the view (by using a custom subclass of CreateView) or if appropriate to your design in the save method of the model class. Or declare an appropriate default value on the field in the model.
It would also work to allow the fields into the form, but set them to use HiddenInput widgets. That's not safe against malicious input, so I wouldn't do that for purely automated fields.
You cannot exclude fields, which are set as required in the model definition. You need to define blank=True/null=True for each of these model fields.
If this doesn't solve your issue, then please show us the model and form definitions, so we know exactly what the code looks like.

django model set field default value from admin panel

models.py
class MyModel(models.Model):
maximum_limit = models.PositiveIntegerField(default=5)
Here I set maximum_limit default value is 5.
But I want to set a value which is also editable from admin and use here as a default value. (editable default value for model MyModel)
My initial approach is(not working). I want something like this.
class MySettings(models.Model):
mx_limit = models.PositiveIntegerField(default=5)
class MyModel(models.Model):
maximum_limit = models.PositiveIntegerField(default=MySettings.mx_limit)
Please help me
Your approach is wrong, a maximum for a db value should be set with the proper attribute, namely max_value.
However this would require a schemamigration everytime you want to change it. So what you really should be doing is dynamic form validation where your form checks for a setting (which should probably be saved in your database and not be statically stored in a module like Settings, which would require server restarts).
There are plenty examples how to make a form validation more dynamically on stackoverflow

Django ManyToMany Field in form - unnecessary database calls?

In a django form that has a manyToMany field - is there a database call to retrieve each object in the list when you're adding a new entry? Is this necessary/ wasteful?
For example:
class MyForm(ModelForm):
likes = forms.ModelMultipleChoiceField(queryset=Videos.objects.all())
....
the form is submitted with a list of project id's. within the clean() method likes becomes a list of Video objects. However you can do:
self.instance.likes.add() ...without ever having to get the objects.
...
is it wasteful that the objects are being retrieved first before updating the relationship? if not, why?
I would say that every time you save the form, it would be evaluating the queryset you passed it to check that each ID is within that queryset. if you wish to optimize the behavior, try subclassing ModelMultipleChoiceField and removing the checks/making them more streamlined.