I am struggling with the update of database information with the forms, and simply passing information between views. I could really use some advice because I am fairly new to Django.
The flow goes like this:
1. First form; I transfer the article price and title to the view "event"
2. The view "event" handles title and price and ask for confirmation in the html form
3. Once confirmed, it directs that information to the view "transact_test", I want this view to handle the update of the database via a new form that is build with the Article model. But it provides the error message : "didn't return an HttpResponse object. It returned None instead."
To fix your error: In transact_test you are just calling render in the request.method == 'POST' block:
render(request, ...)
You need to return render:
return render(request, ...)
You should really take a look at some additional django tutorials you are making this harder than you need to. You should almost never manually render a form when using django. And as Tariq said, please don't use images.
Related
I have a Django form that takes filter options for a report. The report page is a separate view that renders the report based on the form data.
My first pass at this, I simply set the action of the form to the report page and method to GET. The form data was then passed directly the report view via the querystring which I would use GET to retrieve. The problem with this was that this bypassed form validation since the the form did not post back to its own view.
My next pass, I removed the form action (so it would post back to itself) and used form_valid (I am using class based views) to encode the form data and redirect to the report view like so:
ReportOptionsView(FormView)
form_class = OptionsForm
template_name = 'my_report_options.html'
report = reverse_lazy('my_report')
def form_valid(self, form):
qstr = urlencode(form.cleaned_data)
return redirect(self.report+"?"+qstr)
The report page works the same -I just retrieve the information from the querystring to filter the models and display the report.
I would prefer the form data not appear on the querystring of the report page. When I tried to redirect to the report page using a POST method is where I starting having trouble. Even going back to my original flow setting the form action to the report page (thus losing validation) and setting the form method to POST, I got 405 errors. I realize that there may be ways to do this using Javascript, but would prefer to stick with Django/Python
My question is, what is the proper method in Django to take cleaned data from a validated form and POST that data to separate view so that the form data is not exposed in the URL?
I have a model named Book that I send to an html to display data from like this:
books = Book.objects.all()
return render(request, 'index.html', {'books':books})
I then show all the information I want of the book in the front-end (which doesn't need to be shown here).
Other than showing the information of the book in the front-end I also want to introduce a small form that will have two buttons let's say "Submit" and "Decline" that will update an attribute of the Book object depending on the button clicked.
I am trying to find a good way to achieve this. My thought is to POST the entire object to a view to process later but I am not sure if is a good practice to submit an entire object from client to server as this may be affected in some way.
This may help you :
If you want to update database with other values related with Book's object then you can achieve it by doing the following:
if request.POST:
book_form = BookForm(request.POST)
if book_form.is_valid():
book = Book.objects.get(pk=book_id)
book_form = BookForm(request.POST, instance = book)
book_form.save()
It will update the existing bookObject in Database by filtering on the basis of book_id.
You don't need to send any form data if it's just an attribute you'll update. You can do something like this (I'm using uuid just as an example you can use id or whatever unique field you want):
# url for your update view. For example: decline
url(r'^decline/book/(?P<book_uuid>[\w\-]+)$',
YourView.as_view(),
name="book-decline"),
# views.py
class YourView(View):
def get(self, request, *args, **kwargs):
book_uuid = kwargs.get('book_uuid', None)
book = get_object_or_404(Book, uuid= book_uuid)
# UPDATE YOUR BOOK HERE
# in your templates for each book's decline button link
<a href={% "book-decline" book.uuid %} ....>
Tiny Instance provided a generic solution. If you want a more specific solution for the case of updating an object of a model by getting a form filled from the user, then Django has something inbuilt which does this for you. FormView is what you are looking for.
See the official documentation here -> https://docs.djangoproject.com/en/1.9/ref/class-based-views/generic-editing/#formview
I am using Boostrap modal fade window which renders Django form to update my database records. And what I fail to do is not to reload the page if the user has opened the Update window and did not change anything. It will be easier to get my idea if you look at the code below:
def updateTask(request, task_id):
#cur_usr_sale_point = PersonUnique.objects.filter(employees__employeeuser__auth_user = request.user.id).values_list('agreementemployees__agreement_unique__sale_point_id',flat=True)
selected_task = Tasks.objects.get(id=task_id)
task_form = TaskForm(instance=selected_task )
taskTable = Tasks.objects.all()
if request.method == 'POST':
task_form = TaskForm(request.POST,instance=selected_task)
if task_form.has_changed():
if task_form.is_valid():
# inside your model instance add each field with the wanted value for it
task_form.save();
return HttpResponseRedirect('/task_list/')
else: # The user did not change any data but I still tell Django to
#reload my page, thus wasting my time.
return HttpResponseRedirect('/task_list/')
return render_to_response('task_management/task_list.html',{'createTask_form':task_form, 'task_id': task_id, 'taskTable': taskTable},context_instance=RequestContext(request))
The question is, is there any way to tell Django to change the url (like it happens after redirecting) but not to load the same page with same data for the second time?
It's not trivial, but the basic steps you need are:
Write some javascript to usurp the form submit button click
Call your ajax function which sends data to "checking" view
Write a "checking" view that will check if form data has changed
If data have changed, submit the form
If not, just stay on page
This blog post is a nice walkthrough of the entire process (though targeted towards a different end result, you'll need to modify the view).
And here are some SO answers that will help with the steps above:
Basically:
$('#your-form-id').on('submit', function(event){
event.preventDefault();
your_ajax_function();
});
Call ajax function on form submit
Gotta do yourself!
Submit form after checking
I have a template that creates a text entry field and a checkbox. When the checkbox is unchecked, the text field is disabled and cleared, when it's checked, it's enabled, and the user may or may not have typed in it. In my controller I need to distinguish between the 2
cases when the checkbox is unchecked, and the checkbox is checked but the text field is blank. I can get the value of the text field, but not of the checkbox. Is there some way to do this? I've googled this, and I see it's been asked a few times here, but noneof the solutions seem to work for me.
request.POST.get('my_checkbox_field')
P.S. In Django, they're called "views" not controllers.
UPDATE (based on comment)
I'm taking "controller" to mean "view" since Django doesn't have a concept of controllers and they're closest to views. If that's not the case, by all means correct me. Given that, all function-based views at the very least require a request parameter. If you're using class-based views, then request is simply stored on the view object, so you just need to modify it to self.request. I suggest you take some more time to thoroughly read the docs, as this is pretty much bare minimal understanding stuff that is well documented.
Are you looking for this?
def myview(request):
form = MyForm()
if request.method == 'POST':
form = MyForm(request.POST)
if form.is_valid():
checkbox = request.POST.get('my_checkbox', False) # will be True if checked
if checkbox:
# check textfield content
else:
# do something else
return render_to_response(template, kwvars, context_instance=RequestContext(request))
Hi Stackoverflow people,
In my Django project I created a form to register users. This forms can be called through a specific url -> view method. Once the user has filled in the form, presses submit, the same view method will be called and if form.is_valid() is true, then ... simply a standard form, nothing special.
Now, I would like to integrate this little form on every page, and therefore I would like to add it to the base template. I have read that I could populate the form variable through a context_processor, but could I define the process after the submission of the form?
I have created the context_processor.py (as below), added the context_processor to the TEMPLATE_CONTEXT_PROCESSOR dir in the settings (as described here):
from app.forms import Form
def registration_form(request):
return {
registration_form : Form()
}
First of all, the form variable won't be displayed.
And secondly, how do I manipulate the form submission?
I think I misunderstanding the context_processor of Django and would be more than happy about comments on the overall process.
Thank you!
how are you trying to access to form in your template? you probably don't want to use a function name as your dictionary key, maybe you want
return {
'registration_form': Form(),
}
not sure what you mean by manipulate the form submission, but i guess you'd need all the form processing logic in your context processor
if request.POST:
form = Form(request.POST)
# validate etc
instead of creating context processor, create template tag for the purpose and place the tag in base.html
for form submission and displaying errors use ajax, and front-end validations.