How can I submit a Django formset within python code? - python

Background. We want our users to check if the metadata we read out of several images is correct.
Therefore, we show the retreived data in a formset to let the user check everything.
In case the metadata has errors (that happens) we would like to display them as form errors here.
Problem. To obtain the error messages we need bound forms. Feeding our various data into a bound ModelFormSet and taking care of the ManagementForm is ... not so simple. With the unbound version everything works fine.
Idea. If we could produce an unbound form and submit it within the python code, that would be a simple way to get the POST data we need to create the bound form.

Related

what's the difference between cleaned_data and normal data? - django

as mentioned in title...what's the difference?
I have seen people keep on saying use cleaned_data and in videos people still say so but only says it cleans the data but when I use print
print form.cleaned_data.get('title')
print request.POST.get('title')
I don't see any difference though. At first I thought it's those character escape and so but tested and doesn't seem so.
which is actually a preferred way since there doesn't seem to have differences?
You can not trust on request data as it is raw data which are not validated. You should never use data from request and store it to your database.
It so important that you store only valid data in database for smooth functioning of application. Django forms cleaned_data ensure you that validation rules defines for that form are satisfied or not. form.is_valid() check all your validations against request.POST data and generate dictionary containing valid data which is form.cleaned_data.
So data retrieved from forms.cleaned_data attribute are go through form validation. It's not only validation but also converted data to relevant python type too.
You can also refer this link to know how Django form perform validation.

Newfies-dialer Call Reports module

I have newfies dialer project, i would like to add a new field in Call Reports section.
I have lot of field that are unused in contact model. One of them can be used for this special id for my purpose.
How can i do that? Please help me anyone who familiar with newfies-dialer.
Newfies-Dialer is based on the Django framework, so it's good to know about Django to hack on the project.
You will notice in Newfies-Dialer that there is a template called: dialer_cdr/templates/dialer_cdr/voipcall_report.html
in which we display the data that is passed from the view.
So then in dialer_cdr/views.py, you have a view function which is in charge of rendering template and pass it some data. There, you can either modify voipcall_list object to add extra data to it, like info from the contact model, or pass an other object to data.
Here a link to the function handling this view: https://github.com/Star2Billing/newfies-dialer/blob/v2.12.2/newfies/dialer_cdr/views.py#L169

Ajax image upload in Django using Django-imagekit

I've been trying to get my head around uploading image files in Django. There are several tutorials that I have followed and they do help a bit, for example this one and the one here.
While they do give a basic idea of what is happening/how to think about it, I am not yet able transfer that to ImageKit implementation of ProcessedImageField.
My problem is the following: I have several ProcessedImageFields. To upload new pictures, I use a form with a slightly modified ClearableFileIput widget, which displays a thumbnail above the standard 'Choose file' button. This works absolutely fine, the user is able to select a couple of files(one for each field), upload them all at once when the form is saved. I use S3 for storing data using django-storages.
I would like to be able to add an ajax upload functionality on those so that image processing could be delegated away from the form saving. When the user chooses the image, it should be uploaded and its updated once the file is processed. Then changes to the model should only be preserved if the user actually saves the form, otherwise new files should be discarded.
Any ideas where to start looking? Perhaps there are projects that use Django-Imagekit that use one of the existing django ajax libraries?
ProcessedImageFields are really just normal Django ImageFields that perform the image processing (synchronously) before saving the image, and Django ImageFields are really just specialized FileFields. So, if you're using ProcessedImageFields, there's nothing different than normal form file handling; any non-Django specific tutorial about AJAX uploads should apply equally.
As far as processing the image asynchronously, there are two approaches you could take.
The first is to do one form submission with the image and return an id for that image which could be sent with a second submission for the rest of the form. In this case, the processing of the image is done synchronously on the server side, but the user can do other thing with your app while it happens. This makes the final submission shorter because the file has already been sent, but the image processing still needs to complete before the form is successfully saved. You might try looking at jQuery-File-Upload's Django examples, though I'm not sure how good or relevant they are.
If, on the other hand, you want to actually do the image processing asynchronously on the server, it's a little more complicated. One approach would be to have two image separate fields on your model—one for the raw image and one for the current, processed image. In the view that handles the form submission, you'd save the raw image in the model and kick off an asynchronous task (using Celery or something similar) that processes the raw image and then saves it to the other field.
As for the discarding of new files, you'll probably have to do that in a cleanup script that runs periodically. (What you're asking is that the image be preserved on the server, but then discarded when it's not saved, but the server can never be reliably notified of the form not being saved.)

Python - Django - How to handle a multiple page form correctly

I have an application that is used to store vehicle information. I created a Vehicle Model which has many foreign keys including a Consumption Model, Capacity Model, Tires Model, Fuel Model etc.
Multiple Page Form:
When a user wants to add a vehicle to the inventory I wanted to use a multiple page form to break up the steps. So, for example, the first step would be the Vehicle modelform and the second step would be the Fuel modelform. The problem I am running into is storing modelforms over multiple pages without using formwizard.
My Thoughts:
There seems to be no information on how to do this, am I the only one who wants to do this or is the solution blatantly obvious? In other languages I would have stored all the forms in a session and saved them at the end of the process. It seems you can't store a modelform in a session because I get a pickling error (unless I serialize it perhaps?) so I assume that is a no-no. I could save the modelform of a given page to the database before going to the next step but that has multiple issues. i.e. what if the user stops halfway through?
Any explanation on the normal way this is done, or if it is ok to serialize modelforms would be greatly appreciated.
You are looking for the form wizard:
Django comes with an optional “form wizard” application that splits forms across multiple Web pages. It maintains state in hashed HTML fields so that the full server-side processing can be delayed until the submission of the final form.
You might want to use this if you have
a lengthy form that would be too
unwieldy for display on a single page.
The first page might ask the user for
core information, the second page
might ask for less important
information, etc.
More details in the docs.

Model and Validation Confusion - Looking for advice

I'm somewhat new to Python, Django, and I'd like some advice on how to layout the code I'd like to write.
I have the model written that allows a file to be uploaded. In the models save method I'm checking if the file has a specific extension. If it has an XML extension I'm opening the file and grabbing some information from the file to save in the database. I have this model working. I've tested it in the built-in administration. It works.
Currently when there's an error (it's not an XML file; the file can't be opened; a specific attribute doesn't exist) I'm throwing an custom "Exception" error. What I would like to do is some how pass these "Exception" error messages to the view (whether that's a custom view or the built-in administration view) and have an error message displayed like if the forms library was being used. Is that possible?
I'm starting to think I'm going to have to write the validation checks again using the forms library. If that's the case, is it possible to still use the built-in administration template, but extend the form it uses to add these custom validations?
Anything to help my confusion would be appreciated.
UPDATE:
Here's my model so far, for those who are asking, "nzb" is the XML file field.
http://dpaste.com/hold/6101/
The admin interface will use the Form you associate with your model; your own views can also use the form.
This is exactly what I'd like to do. However, I don't know how to associate my forms with my models. When ever I've created forms in the past they've always acted as their own entity. I could never get the administration views to use them while using the ModelForm class. Can you shead any light on this?
I've read over the link you gave me and it seams to be what I've done in the past, with no luck.
Getting attributes from the file, should probably be a method.
Sorry, could you please elaborate on this? A method where?
UPDATE:
It seams I've been compleatly missing this step to link a form to the administration view.
http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin
This should now allow me to do the validation in a Form. However, I'm still confused about how to actually handle the validation. S.Lott says it should be a method?
The Form errors are automatically part of the administrative view.
See http://docs.djangoproject.com/en/dev/ref/forms/validation/#ref-forms-validation
You're happiest if you validate in a Form -- that's what Forms are for. The admin interface will use the Form you associate with your model; your own views can also use the form.
Getting attributes from the file, should probably be a separate method of the model class. The separate method of the model class can be used by the save() method of the model class or invoked at other times by view functions.
"I could never get the administration views to use them while using the ModelForm class."
http://docs.djangoproject.com/en/dev/ref/contrib/admin/#form
http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin
"I'm still confused about how to actually handle the validation. S.Lott says it should be a method?"
Validation in a form is done with a clean() method or a clean_somefield() method.
The "Adding custom validation to the admin" link (above) shows how to add the clean_name method to the "MyArticleAdminForm" form.
If you're still confused, trying actually typing the code from the Django web page and see what it does.
I guess the best way would be to implement a special field class that extends FileField with custom validation of the uploaded file.
The validation is implemented in the field's clean method. It should check the XML file and raise ValidationErrors if it encounters errors. The admin system should then treat your custom errors like any other field errors.
The ImageField class is a good example of special validation like this — I recommend just reading through the source.
You can provide a form that will be used by the admin site. You can then perform validations in the form code that will be displayed in the admin area.
See the docs on the admin site, and in particular the form attribute of ModelAdmin.
"I'm throwing an custom "Exception" error " - Where exactly are you throwing the exception ? In your model or in your view ?
I am confused with your question, so I am assuming that you should be asking 'Where should I catch input errors if any ? ' to yourself.
The Model and View as I see are like pieces in a small assembly line.
View/ Form validation is the first action which should be performed. If there is any issue with the input data through the forms. It should be prevented at the form level using form.is_valid() etc.
The models functionality should be to provide meta information about the entity itself apart from performing CRUD. Ideally it should not be bothered about the data it is getting for the CRUD operations.

Categories

Resources