django forms overwrite data when saved - django

If a have a form, with the data from a user, let's say a CV, and i save the data from the form into a database, but i don't want that a CV from the same user to be stored in the database more than once(when edited form instance)
I want it to be overwritten every time it is saved by one same user.
How can i do it?
thanks a lot

Django's save() should handle this for you automatically.
To give an example, you'll usually submit a form in a way something like this:
...
form = UserCVForm(request.POST, instance=user_cv)
if form.is_valid():
form.save()
...
'instance=user_cv' tells django that you want to update an existing entry - specifically 'user_cv'. Without 'instance=user_cv', Django will insert a new entry into the database.
So in short, see if a user_cv exists already with something like user_cv = UserCV.objects.get(user=user_id). If a user_cv exists, be sure to whack an instance=user_cv in when populating the form.

Related

django: save one field of a formset at a time

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?

Django 1.7 - update a user record using a form

I have created a form to update the existing user profile. But when i save the form it shows the error user already exists.
I used another approach by getting the user profile and then updating each field, but in that case each field has to be validated?
Any clue how to save the form as an update not as a new entry?
I suggest using UpdateView, one of Django's class-based-views for generic editing:
class django.views.generic.edit.UpdateView
A view that displays a
form for editing an existing object, redisplaying the form with
validation errors (if there are any) and saving changes to the object.
This uses a form automatically generated from the object’s model class
(unless a form class is manually specified).
I managed to get the answer, i imported the form to
import the user that i want to edit
u = User.objects.get(username = user_name)
creating the form with values from existing in database and updating with values from POST
user_form = UserEditForm(request.POST,instance=u)
save the form, since it already has existing record it will update
user_form.save()

Accesing information from a POST form in django 1.6

I have a couple of forms, one is created from as a ModelForm and the other is a simple Form. Both of them are used in a request.POST, and to obtain the information from them I am using to different methods:
For the ModelForm form, I do this:
form = ApplicantForm(request.POST)
if form.is_valid():
applicant = form.save(commit=False)
applicant.confirmation_code = '999999'
applicant.save()
For the simple form, I am using:
form = ConfirmationCode(request.POST)
code = request.POST['confirmation_code']
confirmation_id=request.POST['confirmation_id']
As you can see, to access the information in the first form I am using the "form.save.ANYFIELD", and for the second one I am using "request.POST['ANYFIELD']. Is it possible to access the the information in the first form using the request.POST methods even if it hasnt been saved? Which is better?
You can try like this for modelform:
form = ApplicantForm(request.POST)
if form.is_valid():
app_code= form.cleaned_data['confirmation_code'] #assuming confirmation_code is a field in your modelform
.....
You seem a bit confused about what saving is doing in a modelform. When you call form.save(), you're creating a new instance of the model the form is associated with, and (unless you specify commit=False) saving that data to the database. Because you have an instance, you can use any of the normal model instance methods and access patterns.
If you want to use a form without an associated model, you can't call save - because there's nothing to save, and no model to create an instance of - but you should access the data via the form.cleaned_data dictionary after you call form.is_valid(). This is because the data in cleaned_data has been validated according to the rules in the form, and converted into the relevant types where necessary: for instance, if you had an IntegerField in your form called my_number, request.POST['my_number'] will be a string like "3" but form.cleaned_data['my_number'] will be an actual integer, 3.

Saving Formset in a Session - Django

Is here any way to store formset to a session ?
My Scenario is like this . I have a form to fill user data and upload user certificates, and in the next page(form by clicking next) there is a form to enter Professional details .
Is it possible to limit Maximum number of forms generated using a formset?
If I understand your question correctly - how to save a state of the from in a session, then starting with Django 1.4, it actually comes with a way on how to do that out of the box.
https://docs.djangoproject.com/en/dev/ref/contrib/formtools/form-wizard/
It allows you to split a form into multiple section, which then user can fill separately. Once user fills any one section, he/she go to the next page, at which point the state of the form will be saved in a session. Once all the pages are filled, then everything can be saved to a database.
In addition, while going from one page to the other, you add logic of what should be on the next page.
Image that you have a wizard where on the first page it asks what type of content user wants to upload. Then upon going to the second page, then depending on the answer from the first page, appropriate upload fields can be present - field for video, music, or graphics.
I would have answered FormWizard but if you don't want to use it, you can simply create two forms. when the user submit the first one, you pickle it into a session and then you generate the second form. When he clicks on back link, you unPickle saved data and you prefill the form.
def submitFirstForm(request):
data = request.POST['data']
import cPickle
request.session['data'] = cPickle.dumps(data)
...
def backBtn(request):
import cPickle
data = cPickle.loads(request.session['page'])
form = DataForm(data)
...

django forms doubt

Here, I am a bit confused with forms in Django. I have information for the form(a poll i.e the poll question and options) coming from some db_table - table1 or say class1 in models. Now the vote from this poll is to be captured which is another model say class2. So, I am just getting confused with the whole flow of forms, here i think. How will the data be captured into the class2 table?
I was trying something like this.
def blah1()
get_data_from_db_table_1()
x = blah2Form()
render_to_response(blah.html,{...})
Forms have nothing to do with models in Django. They are just class meant to get informations from a dictionary (often request.POST) and check if each data linked to a key match a type and a format (e.g: is this a string of the form "bla#foo.tld").
You can ask django to create a form from a model, and in that case it will do its checking job, then if the data match, it will create a model, fill it and save it.
If a form is not created from a model, it will do nothing but checking. It will save nothing.
If it is created from a model, it will create a new instance of this particular model instance and save it.
If you want something more complicated, like, pre fill a form from various models or according to some conditions, or, say, you need to save several models according to the result of one form, you must do it manually.