Is there a way that i can access the values in my form fields before submitting the form.
I need to store the value of one of my fields in request.session[] so as to access it later ( in the same view). I tried doing it using request.GET but it always none.
request.GET.get('name')
where name is the field in a model.
Update
I want to store the value of the form field which is random value generated every time the form is displayed. My models.py contains a random() method which is the default value of the field.
I want to store the field value in sessions, so that i can get the same field value after i return to the page after navigating a few more pages from that page
This is what i was doing:
Django request.session does not resolve
First of all careful when using random in models:
Random/non-constant default value for model field?
Once this is clear I suppose you initialise the form in the view, is there that you need to access the form and get the value for put it in session.
For example
form = MyModelForm();
request.session['your_session_key'] = form.data['field_name']
As far as I understand in some cases you want to set this value in the form from the session instead, for do that you can use the initial data as described here.
https://docs.djangoproject.com/en/dev/ref/forms/api/#dynamic-initial-values
Hope this helps
Related
My django app connects to a sql server database. On my template I have an editable datatable/formset. Whenever a user edits a field and hits enter, I want only the edited field to be saved. As far as I know AJAX is the only approach to do this, especially if you want the value of the edited field to be the only one transfered to the server. Let's put this case aside for now and accept transferring all data of the formset at once.
Also, the formset is based on a sql server view that includes calculated values. Hence, executing formset.save() will raise an error. Instead I have to use the underlying table to save the modified value. What would be best practice to identify the changed field and save only this one?
Let's say the underlying table is costsperdiem that corresponds to a model in my django app and 'costs' is the name of the editable field I want to save then my approach is as follows:
check if the formset is valid
loop through the forms of the formset using changed_data to seek for the modified field
using a model instance to filter for the modified record
pass the modified value to the model
save the model
which looks like this in code:
formset = FormSet_CostsPerDiem(request.POST)
if formset.is_valid():
for f in formset.forms:
if 'costs' in f.changed_data:
val2save=f.cleaned_data['costs']
id=f.cleaned_data['id_costsperdiem']
rec2save=costsperdiem.objects.filter(pk=id)
rec2save.costs=val2save
rec2save.save()
What is best practice to do something like this?
In my django form I have an object_id that is a hidden UUIDField:
class MyForm(forms.Form):
object_id = forms.UUIDField(widget=forms.HiddenInput)
In my view, I populate this id field with an initial value.
form = MyForm(initial={'object_id': pk,})
The idea is that I pass a primary key to the form and then get it back again when the for is submitted. That works. But what if the user tampers with the hidden field?
To prevent this I set disabled=True on my object_id, which according to the documentation means that the initial value should be respected (although perhaps this only means an initial value defined on the field, rather than one defined on the form, through the view?).
Unfortunately the result is that now my object_id returns a None object.
So the question is, should disabling a field mean that it doesn't return a value. If it does, is there any way to ensure that a hidden value does a safe round trip through a submitted form?
In my index view I have a ModelChoiceField which allows me to choose various equipments.
When I have submitted my choice, I keep the selected value in a variable like this:
if form.is_valid():
form.save()
request.session["eq"] = form.cleaned_data['equipment']
Then I am redirected to a new view(reservation) in which I have a form with three fields: "equipment", "date" and "reserved_by". Since I have already chosen the equipment i want in the previous view I want it to be filled in automatically. I managed this by doing the following in my reservation view:
form = ReservationForm(initial={'equipment': request.session.get('eq')})
So when I run my site, the equipment field in the reservation view does get automatically filled in, but now the form suddenly won't validate(form.is_valid is false).
Been struggling with this for a while now so any help would be highly appreciative.
This form from your question is unbound.
form = ReservationForm(initial={'equipment': request.session.get('eq')})
Unbound forms are never valid. To get a valid form, you need to bind it to post or get data.
I'm using some ajax to fill a custom select box dynamically in my form.
However, when I post the data the is_valid method doesn't want to validate the submitted value for this field, although it's a valid value from the db, just not retrieved by Django itself.
Here's my initially empty field populated afterwards with Ajax:
accompanying_partner = forms.ChoiceField(required=False)
It's populated dynamically according to another selected choice field.
Django warns me the value isn't valid.
Any thoughts on a workaround?
You should somehow provide filter dataset to form constructor (if it's contained in data - that's good), then in the constructor compute actual choices and set self.fields['accompanying_partner'].choices = actual_choices to make validation work.
I understand that, by default, Django auto-populates id for each form field upon rendering with the format id_for_%s. One can modify the format by providing the auto_id argument with a different format as its value to the Form constructor.
That's not exactly what I am looking for, however. What I want to accomplish is changing the id of just one of the many fields in my form. Also, the solution should not break the use of form = MyForm(request.POST).
PS. MyForm is a model form, so each id is derived from its corresponding Model field.
Thanks for helping out.
The forms framework appears to generate labels here:
def _id_for_label(self):
"""
Wrapper around the field widget's `id_for_label` class method.
Useful, for example, for focusing on this field regardless of whether
it has a single widget or a MutiWidget.
"""
widget = self.field.widget
id_ = widget.attrs.get('id') or self.auto_id
return widget.id_for_label(id_)
id_for_label = property(_id_for_label)
Which means you can just supply your field widget with an "id" key to set it to whatever you'd like.
foo = forms.CharField(widget=forms.TextInput(attrs={'id': 'foobar'}))
Or override init and set the attrs after form initialization.
I don't see how this could break a form as django's forms framework isn't ever aware of HTML ids (that data is not passed to the server...)