from django.shortcuts import render
from Insertemp.models import EmpInsert
from django.contrib import messages
#from django.http import HttpResponse
def Insertrecord(request):
if request.method=='POST':
if request.POST.get('epname')and request.POST.get('email')and request.POST.get('country'):
saverecord=EmpInsert()
saverecord.empname=request.POST.get('empname')
saverecord.email=request.POST.get('email')
saverecord.country=request.POST.get('country')
saverecord.save()
message.success(request,'Record Saved Successfully...!')
return render(request,'Index.html')
else:
return render(request,'Index.html')
[views.py file][1]
when binding HTML form with MySQL database by django
after submiting submit button from html form I get error ValueError at /
The view Insertemp.views.Insertrecord didn't return an HttpResponse object. It returned None instead.
Request Method: POST
You do not return anything if you are in a POST request but that one parameter is missing.
def Insertrecord(request):
if request.method=='POST':
if request.POST.get('epname')and request.POST.get('email')and request.POST.get('country'):
saverecord=EmpInsert()
saverecord.empname=request.POST.get('empname')
saverecord.email=request.POST.get('email')
saverecord.country=request.POST.get('country')
saverecord.save()
message.success(request,'Record Saved Successfully...!')
return render(request,'Index.html')
else: # HERE IS THE MISSING ELSE
return render(request,'Index.html') # OR RETURN SOMETHING ELSE
else:
return render(request,'Index.html')
[views.py file][1]
Edit - About the message:
You have to import messages: from django.contrib import messages
And you made a typo, writing message instead of messages.
Related
I am new at django
I was designing my own website to store value of form in the database
please help
I can't able to overcome the error
the error is multivaluedicterror
from django.shortcuts import render
from django.http import HttpResponse
from main.models import recieve_content
# Create your views here.
def index(request):
return render(request,'index.html')
def about(request):
return render(request,'about.html')
def contact(request):
return render(request,'contact.html')
def donation(request):
return render(request,'donation.html')
def form(request):
if request.method=="POST":
name1=request.POST["name1"]
name2=request.POST["name2"]
address=request.POST["address"]
content=request.POST["content"]
data=recieve_content(fname=name1,lname=name2,address=address,content=content)
data.save()
return HttpResponse("your data saved successfully")
return render(request,'form.html')
This is a medical inventory system.
Can't seem to get around this Type error. I am new to python and django.
I have looked at other similar errors but have not found a solution. here is my views.py file inside the home directory.
Kindly assist...thank you.
from django.shortcuts import render, redirect, Http404, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect, JsonResponse
from accounts.models import Registration, YearEnding
from home.backup import BackupDatabase
#login_required(login_url='/account/login/')
def HomePage(request):
if not request.user.is_authenticated():
raise Http404
try:
** current_session_id = request.session['session'] **
except:
** currentSession = YearEnding.objects.order_by("-id").first() **
** request.session['session'] = currentSession.id **
current_session_id = currentSession.id
current_session = get_object_or_404(YearEnding, id = current_session_id)
return render(request, 'home/index.html', {"current_session":current_session})
#login_required(login_url='/account/login/')
def takeBackup(request):
if request.method == "GET" and request.is_ajax():
forcefully = request.GET.get("forcefully")
backup = BackupDatabase()
response = backup.run(forcefully = int(forcefully))
if response["code"] == 200:
return JsonResponse(response, status=200)
else:
return JsonResponse(response, status=400)
else:
return JsonResponse({}, status=400)
As per documentation:
Returns the first object matched by the queryset, or None if there is no matching object.
Means if there is not YearEnding instance has been created, then YearEnding.objects.order_by("-id").first() will return None. So you need create one. You can do that from admin site, or shell. For example:
>> python manage.py shell
>> [python] from my_app.models import YearEnding
>> [python] YearEnding.objects.create(field1=value1,field2=value2)
One more suggestion, you can remove this code:
if not request.user.is_authenticated():
raise Http404
Because you are using #login_required decorator, it will automatically prevent non-logged in users from entering this view.
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..
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.
I am trying to pass the id through reverse. But it's not working. I'm getting this error
Reverse for 'reg.views.thanks' with arguments '(20,)' and keyword arguments '{}' not found.
Here is my views.py:
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.core.urlresolvers import reverse
from reg.models import registration, registrationform
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
def registration(request):
if request.method == 'POST':
form = registrationform(request.POST)
if form.is_valid():
data = form.save()
id = data.id
return thanks(request,id)
else:
form = registrationform()
return render_to_response('registration.html', {'form' : form}, context_instance=RequestContext(request))
def thanks(request, id):
p = get_object_or_404(registration, pk=id)
return render_to_response('thanks.html', {'reg' : p})
Here is my urls.py:
from django.conf.urls import patterns, include, url
url(r'^registration/$', 'reg.views.registration'),
url(r'^thanks/$', 'reg.views.thanks'),
url(r'^$','django.views.generic.simple.direct_to_template', {'template' : 'index.html'}),
)
Here is thanks.html:
<html>
<body>
<p>Thank you for registration mr.{{reg.username}}</p>
</body>
</html>
and I'm also showing my models.py:
from django.db import models
from django.forms import ModelForm
class registration(models.Model):
username = models.CharField(max_length=100)
password = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class registrationform(ModelForm):
class Meta:
model = registration
Thanks.
from this links (django tutorial):
https://docs.djangoproject.com/en/dev/topics/http/urls/#django.core.urlresolvers.reverse
example:
def myview(request):
return HttpResponseRedirect(reverse('arch-summary', args=[1945]))
so your code goes to:
in urls.py:
url(r'^thanks/(?P<id>\d+)$', 'reg.views.thanks', name='my_thanks_url')
in your function:
return HttpResponseRedirect(reverse('my_thanks_url', args=[id]))
This line
return HttpResponseRedirect(reverse('reg.views.thanks', args=(id,)))
Is trying to construct a url to your view reg.views.thanks, with the id variable used as a parameter.
This line in urls.py
url(r'^thanks/$', 'reg.views.thanks'),
Does not have anywhere for that parameter to go.
The first thing that you need to figure out is whether you actually want to send an HTTP redirect to the browser to tell it to go to the 'thanks' page. If you really do, then you need a way to send that id in the URL. You can do it as part of the URL path itself, as #moguzalp suggests, or you can put it in the query string, like
/thanks/?id=12345
Or you can do other things, like stashing the id in the user's session, and pulling it out when they request the thanks page. That's a bit more complicated, though.
If you don't actually need to issue an HTTP redirect, then there's nothing stopping you from just calling the thanks() function from inside your view function, like this:
def registration(request):
if request.method == 'POST':
form = registrationform(request.POST)
if form.is_valid():
data = form.save()
id = data.id
return thanks(request, id)
else:
form = registrationform()
return render_to_response('registration.html', {'form' : form}, context_instance=RequestContext(request))
The URL won't change in the browser, but the correct ID will be used, and doesn't need to appear anywhere else, in the URL, the query parameters, or the session