How I can use correctly django ModelChoiceField - python

I'm a newbie and right now I'm using Django forms to show some fields. One of these fields is a ModelChoiceField this show correctly model data, but I donĀ“t know how I can fill a CharField later of select a option in the ModelChoiceField.
How I can make send the value of option selected for obtain the data that i need for later show this in a CharField, this is possible make directly from a djangoForm or do I need a new view to return the value?

There are two ways to achieve what you want I think:
Provide an initial value for your form value.
Bind your form to some data.
See this related stack overflow to provide initial values.
See Django's documentation on forms for binding data. There are two kinds of form states: bound and unbound. To create a bound form, you just need to create an instance of your form with some data: MyForm({'data-key1': 'data-value1', ...}).

Related

Django - Custom Form Field Example

I have a project in which I need to add a custom form field to a form (or formset) in which depending on the choice in the custom field selected, an integer in a database field is changed.
I can't seem to find any examples or prior questions which imply how to modify a database field via a custom field. I suspect it is done by overwriting the save() function in a ModelForm but cannot work out how.
Any advice on solving this problem would be greatly appreciated.
An Example:
My class has an integer field which is the field that needs updating.
class Employee(Model):
years = models.IntegerField()
However this field cannot be updated as it is, instead what is needed is a ChoiceField (I think) with different options that, depending on the selection, changes the field with a +1, -1, or reset to zero.
As previously mentioned this is where I imagine some work with the save() function needs to be done but am unsure.
As a side note in case this affects what can be done, eventually this ModelForm will need to be used in a formset so I can edit multiple objects on one page.

Django ForeignKey form field widget

First of all I have tried to research my problem but have not been able to find what I need. My problem might be related to the design of my project (any help would be appreciated).
The problem I am facing is as follows:
I have a few models
I have a model that would be used specifically to create a ModelForm
In this model I have ForeignKey field that is represented by default as a select/option input widget in the ModelForm (for each the value attribute is the ForeignKey and text between the tags is the __str__() of the model the ForeignKey points to. The user sees the __str__() and value attribute of the option tag is submitted which is great).
So far so good but I want to replace the widget with an input text field so I can implement it as a search field.
Now when the user submits the form the string entered in the text input field is submitted and of course django doesn't like that since it expects a foreign key
I already can think of a few solutions to the problem and I am sure I can make it work but each of them feels like I would be violating some best practices. So my question is what should I do?
Do I exclude this particular field from the ModelForm and implement it as an input text field then after form submission make a query with it's value and then store the ForeignKey to the DB
Do I manipulate the data with JavaScript upon submission so that Django receives correct information
Can I clean this fields data with Django and transform it from string to FK?
Am I going the wrong way with this or there is a Django feature for this type of situation?
If anyone has the same problem here is the solution (to my problem at least):
I tried to use the clean_<fieldname> method to change the user entered string to database id. The method wasn't executing because the validation process was stopping earlier because of the difference between the form field and the widget. I redefined the form field to CharField so that step of the validation was working and then the clean_<fieldname> method executes without a problem.

Create a dynamic admin site

I want to create a dynamic admin site, that based on if the field is blank or not will show that field. So I have a model that has a set number of fields, but for each individual entry will not contain all of the fields in my model and I want to exclude based on if that field is blank.
I have a unique bridge identifier, that correlates to each bridge, and then all of the various different variables that describe the bridge.
I have it set up now that the user will go to a url with the unique bridgekey and then this will create an entry of that bridge. So (as i am testing on my local machine) it would be like localhost/home/brkey and that code in my views.py that corresponds to that url is
However, not every bridge is the same and I have a lot more variables that I would like to include in my model but for now I am just testing on two : prestressed_concrete_deck and reinforced_concrete_coated_bars. What I want is to dynamically create the admin site to not display the prestressed_concrete_deck variable if that field is blank. So instead of displaying all of the variables on the admin site, I want to only display those variables if that bridge has that part, and to not display anything if the field is blank.
Another possible solution to the problem would be to get that unique identifier over to my admins.py. I cant figure out either how to get that individual key over as then I could query in the admins.py. If i knew how to access the bridgekey, I could just query in my admins.py dynamically. So how would I access the brkey for that entry in my admins.py (Something like BridgeModel.brkey ?)
I have tried several different things in my admin.py and have tried the comments suggestion of overwriting the get_fields() method in my admin class, but I am probably syntactically wrong and I am kind of confused what the object it takes exactly is. Is that the actual entry? Or is that the individual field?
Just override the get_fields method in your ModelAdmin class.
You can check the obj is passed as function argument so you can check which fields are empty. The function needs to return a tuple so, you would check if field1 is None and then return (field1, field2, field3) or (field2, field3) depending on the value of field1.
I was using Django 1.6 which did not support overriding the get_fields method. Updated to 1.7 and this method worked perfectly.

Django: make field editable depending on the value of other field

I'm new to Django, and I haven't found the answer yet in the extensive documentation. I'm asking for pointers to research, not for working code. That being said, here's my problem:
In one of my models theres a BooleanField (it gets rendered in the admin form as a checkBox). Let's call it 'A'. It only makes sense to edit other field (say, CharField 'B') if A is checked.
So, is there a way to make B read only, or even changing its content to an empty string, dinamically, if A is checked? Thank you.
(Django 1.5.2, Python 2.7.5)
You're going to need several things to make this work. You may be able to skip some of them depending if you mainly care abut the UI, or the data integrity in the db.
Since the user can (presumably) check/uncheck Field A on the client-side you need some Javascript to enable/disable the appearance of Field B. These docs show how to load custom JS in your ModelAdmin class:
https://docs.djangoproject.com/en/dev/ref/contrib/admin/#modeladmin-asset-definitions
In your ModelForm you may want to do some check in the __init__ method against the value of self.instance.field_a and substitute some kind of ReadOnlyWidget for Field B for the initial display of the form. These docs show how to give your ModelAdmin a custom form class:
https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form
If you are writing some Javascript to do that dynamically it make be easier to skip this step and just do it client-side.
Finally you can use Django model validation to ensure that Field B is saved with a null value if Field A is checked:
https://docs.djangoproject.com/en/dev/ref/models/instances/#validating-objects

Add Derived Field to Django Admin Change Form

I'd like to add a derived field to a default ModelAdmin.fieldsets like I would by specifying a method and adding it to the ModelAdmin.list_display property, but there doesn't seem to be an easy way to do that (if there is ANY way to do that).
The default Django Admin list view seems to have a lot more options than the change form view does.
Let's say I have two fields for a location: latitude and longitude, and instead of displaying them on a change form I want to display a Google Maps Static Map image instead - I already have a method that will return the src url for the image - I just need a way to add that image to the model change form instead of showing those two fields.
If you write a method and add it to ModelAdmin.readonly_fields, it will appear on the change view.
customize admin view http://docs.djangoproject.com/en/dev/ref/contrib/admin/#ref-contrib-admin

Categories