How can I reuse django form for searching? - python

I am programming an application in django, and I have a model where I defined some fields that are necessary to be filled. This way, when te user doesn't fill one of these fields, Django authomatically indicates to the user to fill it to create the specific object defined by the model.
But myquestion comes here: I want to reuse the same form to search objects defined by that model. And in this case, all the fields that before were necessary, now are OPTIONAL. But, as I have already defined the model so that the fields are necessary, django doesn´t let me define those fields as optional.
Is there any way to reuse that form where the fields are necessary, but making them OPTIONAL? Or I must create another different model or form in html? I know that creating another form manually in the html code the problem is solver, but I have curiosity to know if it can be reused.
Thank you so much!

You can programmatically change properties of a field within a form using its fields dictionary. So you could create a new form class that is derived from your current form class and in its __init__ set the required property of the fields you desired to be optional to be False like so:
self.fields['title'].required = False

Related

Django - attributes and redefined fields with a ModelForm?

I have been learning about how forms, and now ModelForms, work.
In a video by Max Goodridge, he redefines a field for one of his ModelFields in his ModelForm class. That is, he manually adds a field to his ModelForm class that could have been auto-generated by the ModelForm framework. From what I have read and understood thus far, that may be something to avoid. Though, that is not where my question lies.
I am wondering how redefining fields within a ModelForm class works. In the Django Docs, it is stated (with an example) that a ModelForm instance will have a form field for every model field specified. What happens then, when a form field is explicitly defined in a ModelForm instance? Are two fields generated or does ModelForm recognise that a field is already defined, thus not generating another one?
Furthermore, what exactly does adding an attribute to a ModelForm instance in the views do? For example, I have seen this:
form = ExampleForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.user = request.user # herein lies my confusion
post.save()
What exactly is happening here? I have seen people do this and adding a timestamp as well, but I fail to understand exactly what it does. Presumably, the .save() method recognizes the attribute name 'user' and adds it to the database if the name corresponds with a Model-field name 'user'?
What happens when a form field is explicitly defined in a ModelForm instance?
How does adding an attribute with information for a model-field in a ModelForm instance work?
Thank you!
When you define a field at class level, the form will use that definition rather than create one from the model field. Far from being something to avoid, this is the correct thing to do if you want to completely customise a field.
Your second question is hard to understand. Save is not "recognising" anything. form.save() returns the instance of the model, on which you can set any field values as normal.

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.

How I can use correctly django ModelChoiceField

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', ...}).

how to set name of a field dynamically in openerp?

Hi I am working on an openerp module . I want to make a field dynamically . I want to take a name of a field from user and then create a field to it . How this can be done ? Can I do it with fields.function to return name, char type ? Plz help
Do you mean you want a dynamic field on the form/tree view or in the model?
If it is in the view then you override fields_view_get, call super and then process the returned XML for the form type you want adding in the field or manipulating the XML. ElementTree is your friend here.
If you are talking about having a dynamic database field, I don't think you can and OpenERP creates a registry for each database when that database is first accessed and this process performs database refactoring at that time. The registry contains the singleton model instances you get with self.pool.get...
To achieve this you will need to create some kind of generic field like field1 and then in fields_view_get change the string attribute to give it a dynamic label.
Actually, a plan C occurs to me. You could create a properties type of table, use a functional field to read the value for the current user and override fields_view_get to do the form.
You can create Fields Dynamically by the help of class self.pool.get('ir.model.fields')
Use Create Function.

Categories