Hello and thank you in advance. This is a follow up question from the following thread (not sure if I should have posted there or started a new thread...:
CSRF token missing or incorrect even though I have {% csrf_token %}
I am not sure what I need to do with the code to make csrfContext work. I am trying to use ModelForm to collect data to a model and write it to a MYSQL table. I am gettingthe error:
Reason given for failure:
CSRF token missing or incorrect.
Here is the code:
from django.shortcuts import render_to_response
from djengo.template import RequestContext
from django.http import HttpResponse, HttpRequest, HttpResponseRedirect
from acmetest.models import Player
from acmetest.models import PickForm
csrfContext = RequestContext(request)
return render_to_response('makepick.html', csrfContext)
def playerAdd(request, id=None):
form = PickForm(request.POST or None,
instance=id and Player.objects.get(id=id))
# Save new/edited pick
if request.method == 'POST' and form.is_valid():
form.save()
return HttpResponseRedirect('/draft/')
return render_to_response('makepick.html', {'form':form})
Again,
Thank you for your help!
dpbklyn
Update your code thusly:
from django.shortcuts import render
# from djengo.template import RequestContext <- this is not valid.
These two lines, as Yuji pointed out, are not valid python, and in addition they are not necessary if you use the render shortcut.
# csrfContext = RequestContext(request)
# return render_to_response('makepick.html', csrfContext)
Modify your return line:
# return render_to_response('makepick.html', {'form':form})
return render(request,'makepick.html',{'form':form})
I'm assuming we're talking about the playerAdd view - you need to pass RequestContext to the response there.
def playerAdd(request, id=None):
form = PickForm(request.POST or None,
instance=id and Player.objects.get(id=id))
# Save new/edited pick
if request.method == 'POST' and form.is_valid():
form.save()
return HttpResponseRedirect('/draft/')
return render_to_response('makepick.html', RequestContext(request, {'form':form}))
The first lines in your code are hard to understand and doesn't even appear to be valid python. You can't use return from outside a function block.
Related
This is my views function,
def studentcreate(request):
reg = StudentForm()
string = "Give Information"
if request.method == "POST":
reg = StudentForm(request.POST)
string = "Not Currect Information"
if reg.is_valid():
reg.save()
return render('http://localhost:8000/accounts/login/')
context = {
'form':reg,
'string': string,
}
return render(request, 'student.html', context)
Here first we store form in reg variable then also we write reg = StudentForm(request.POST) why?
acutally why we write this?
I can't tell you why you are writing this. Maybe only you know. It does not make much sense. I would recommend reading the Django documentation on this at https://docs.djangoproject.com/en/4.0/topics/forms/#the-view
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import NameForm
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
You read from data if the request is a POST. Otherwise, return an empty form.
You could think of the "request.POST" as a parameter passed onto the form in the view. This tells the view that the form mentioned has POST data from the form in name.html. Otherwise it is just an empty form.
I am working on a web app and I want to use HttpResponse or HttpResponseRedirect instead of render. But I dont know hoe to pass context in response as it does not have context parameter like render. And also how to use the passed context in the url or view ?
Here is my view:
#login_required
def view_task_description(request):
if request.method == 'POST':
task_description = GetTaskDescription(data=request.POST, user=request.user)
if task_description.is_valid():
obj = GetTaskDescription.get_task_description(task_description)
return render(request, 'todoapp/task_desc.html', context={'description': obj[0].description})
return render(request, 'todoapp/select_task_description.html', context={'view_tasks': GetTaskDescription(user=request.user)})
I want to use Redirect or ResponseRedirect with the context instead of the render that I am returning if my form is valid. Basically render still shows the response as a POST method and I want the response to be a GET. How can I do so ? Thanks.
You can simply create a new view for that. Then link it to the existing view using redirect. For example:
# view
from django.shortcuts import get_object_or_404
#login_required
def get_task_description(request, pk):
obj = get_object_or_404(TaskDescriptionModel, pk=pk)
return render(request, 'todoapp/task_desc.html', context={'description': obj.description})
# url
url(r'^some_path/(?P<pk>[0-9]+)/$', get_task_description, name="get_task_description")
# linking to existing view
from django.shortcuts import redirect
...
if task_description.is_valid():
obj = GetTaskDescription.get_task_description(task_description)
return redirect('get_task_description', pk=obj[0].pk) # <-- Pointing the new view
After submit a form, I want to redirect to an specific view passing one flag=True in order to activate a popup like:
def view1(request):
if request.method == 'POST':
form = Form(request.POST)
if form.is_valid():
form.save()
return redirect('new_view') # Here I need to send flag=True
else:
form = Form()
return render(request, 'template.html', {'form': form})
How can I do this?
It's not quite clear on what you mean by arguments if it should be in the query string or arguments to a view.
Either way, below is both solutions;
redirect accepts args and kwargs
redirect('new_view', flag='show') # This is the argument of a view
or
redirect('{}?flag=True'.format(reverse('new_view'))
Then you can access it in the view like so
show_flag = bool(request.GET.get('flag', False))
for a given url pattern such as
url(r'^random/(?P<arg1>[0-9]+)/(?P<arg2>[0-9]+)/$', views.random, name="urlname")
or
url(r'^argfree/', views.random2, name="urlname2
from django.http import HttpResponseRedirect
from django.urls import reverse
def view(request):
# do your thing
if something:
return HttpResponseRedirect(reverse("urlname", args=["this_is_arg1", "this_is_arg2"]))
else:
return HttpResponseRedirect(reverse("urlname"))
There is a django-url-params module to help you in this situation. Just add
request.cparam = {'flag': True}
return param_redirect(request, viewname)
from django.urls import reverse
response = redirect(f"{reverse('search')}?query='How to redirect with arguments'")
Trying to make a form with Django and using a HttpResponseRedirect, I expected this should be fairly easy, however I seem to be doing something wrong.
I keep getting an error:
The view hotel.views.hotel_registration didn't return an HttpResponse object. It returned None instead.
In this case my guess would be that HttpResponseRedirect is not working properly, since, when I remove the if statement with the contents everything is working fine, except I can't submit a form.
I have 2 views:
def hotel_registration(request):
if request.method == 'POST':
form = HotelRegistrationForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('hotel:hotel_registered')
else:
form = HotelRegistrationForm()
return render(request, 'hotel/hotel-registration-form.html', {'form': form})
def hotel_registered(request):
pass
And in urls.py
url(r'hotel-registratie/', hotel.views.hotel_registration, name='registration'),
url(r'hotel-geregistreerd/', hotel.views.hotel_registered, name='registered'),
These are all the parameters I have used in HttpResponseRedirect:
HttpResponseRedirect('hotel:hotel_registered')
HttpResponseRedirect('hotel_registered')
HttpResponseRedirect('/hotel_registered/')
HttpResponseRedirect(hotel_registered)
And then I rust wanted to redirect back to root:
HttpResponseRedirect('/')
And using reverse:
HttpResponseRedirect(reverse(hotel_registration))
HttpResponseRedirect(reverse('hotel_registration'))
What would be the right way to do this?
According to the following urls.py that you posted :
url(r'hotel-registratie/', hotel.views.hotel_registration, name='registration'),
url(r'hotel-geregistreerd/', hotel.views.hotel_registered, name='registered'),
You should make the redirection using one of the following methods :
return HttpResponseRedirect('hotel-geregistreerd/')
or
return HttpResponseRedirect(reverse('registered'))
or simply
return redirect('registered')
When you use HttpResponseRedirect provide the path of the url, if you use reverse or redirect you can use the name that you defined in your urls.py.
This is my views.py file. i am on the way to generate xml file, The data i am getting from mysql. First time its working but i make some changes then i cant remember what i did now it s not working ...
in the views.py
def MessageHeaderModel2(request):
if request.method == "POST":
form = MessageHeaderForm(request.POST)
if form.is_valid():
DDEX_Party_Id = request.POST.get('DDEX_Party_Id',None)
data = serializers.serialize("xml", MessageHeaderModel2.objects.all())
with open("file.xml", "w") as out:
xml_serializer.serialize(MessageHeaderModel2.obj ects.all(), stream=out)
The error now i am gettin is
>Exception Type:ValueError
Exception Value:The view app.views.MessageHeaderModel2 didn't return an HttpResponse object.
Like stated in the error, your view isn't sending any response to the client.
Add at the end of your view a line like :
return render(request, 'template.html')
Or any other response, that you need
You in fact are not returning an HttpResponse object!
Django views must return an instance of HttpResponse so at the end of your view:
from django.http import HttpResponse
def view(request):
...
return HttpResponse("the page content")
You can also return may other subclasses of HttpResponse, see the documentation for a list.
You can also use some of the shortcut functions to render a page using the django templating system, again the documentation is helpful here, but briefly:
from django.shortcuts import render_to_response
def view(request):
...
return render_to_response('my_template.html',
my_data_dictionary,
context_instance=RequestContext(request))
A complete example using your code from above:
def view(request):
if request.method == "POST":
form = MessageHeaderForm(request.POST)
if form.is_valid():
DDEX_Party_Id = request.POST.get('DDEX_Party_Id',None)
data = serializers.serialize("xml", MessageHeaderModel2.objects.all())
with open("file.xml", "w") as out:
out.write(data)
return HttpResponse(data)
else:
# return error response?
return HttpResponseNotAllowed(['POST'])
You are not returning anything so that's why you have such an error...
You can also for example return Success value or redirect to other view..