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')
Related
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.
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.
I'm am trying to troubleshoot an HTTP response one code works fine but, the other one is returning an ValueError they are the both same code and I looked over them for 1hr side by side but, I can't find what is wrong with the bad code this is really bugging me.
Working code:`
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib import auth
def signup(request):
if request.method == 'POST':
if request.POST['password1'] == request.POST['password2']:
try:
user = User.object.get(username=request.POST['username'])
return render(request, 'accounts/signup.html', {'error':'Username in use'})
except User.DoesNotExist:
User.objects.create_user(request.POST['username'], password=request.POST['password1'])
auth.login(request.user)
return redirect('home')
else:
return render(request, 'accounts/signup.html')
def login(request):
return render(request, 'accounts/login.html')
def logout(request):
return render(request, 'accounts/signup.html')
BAD CODE:
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib import auth
def signup(request):
if request.method =='POST':
if request.POST['password1'] == request.POST['password2']:
try:
user = User.object.get(username=request.POST['username'])
return render(request, 'accounts/signup.html', {'error':'Username in use '})
except User.DoesNotExist:
User.objects.create_user(request.POST['username'], password=request.POST['password1'])
auth.login(request.user)
return redirect('home')
else:
return render(request, 'accounts/signup.html')
def login(request):
return render(request, 'accounts/login.html')
def logout(request):
return render(request, 'accounts/signup.html')
`
else:
return render(request, 'accounts/signup.html')
So this piece of code if it's not a post, but a GET request in the first piece of code it will return the web page signup.html. But in the second the else statement isn't even under an if.
This is throwing me a recursion error.
It first suggested that I put in the argument 'request' in the signup() but then I received a new error.
Here is my code:
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from .forms import signup
from django.utils.html import format_html
from django.contrib import messages
from .models import signup
def index(request):
return render(request, 'myapp/index.html')
def signup(request):
if request.method == 'POST':
register_form = signup(request.POST)
if register_form.is_valid():
post = register_form.save()
message = format_html("Hi {0}, Thank you for signing up with us! See your profile <a href=''>{1}</a>".format(register_form.cleaned_data['name'], "here"))
return render(request, 'myapp/register.html', {'signup':register_form, 'message': message})
else:
message = register_form.errors
form = signup(request)
return render(request, 'myapp/register.html', {'signup':form, 'message': message})
else:
form = signup(request)
return render(request, 'myapp/register.html', {'signup':form})
throws:
if request.method == 'POST': RecursionError: maximum recursion depth
exceeded in comparison
Your problem are these lines
...
from .models import signup
...
def signup(request):
...
if request.method == 'POST':
register_form = signup(request.POST)
...
You're redefining signup() causing it to call itself indefinitely. You'll need to rename one of these methods.
from django.shortcuts import render
from django.http import HttpResponse #http response sends back html/basic webpage
from django.conf.urls import include
from django.template import loader
from .models import Album
# Create your views here.
'''def index(request):
all_objects = Album.objects.all()
html = ''
for album in all_objects:
url = "/music/" + str(album.id) + "/"
html += '' + album.album_title + '<br>'
return HttpResponse(html)
'''
def index(request):
all_albums = Album.objects.all()
#template = loader.get_template('music/index.html')
context = {'all_albums': all_albums}
return render(request, 'music/index.html', context)
#return HttpResponse(template.render(context, request))
def detail(request, album_id):
return HttpResponse("<h2>Details of Album with id:" + str(album_id)+ "</h2>")
yields perfectly right templates.
And when I add the templates for an album that does not exist.
That is I have added 2 albums and synchronized with my database, and when I surf to the third template page, I should get the 404 error.
And the code for this is-
from django.http import Http404
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from .models import Album
def index(request):
all_albums = Album.objects.all()
#template = loader.get_template('music/index.html')
context = {'all_albums': all_albums}
return render(request, 'music/index.html', context)
#return HttpResponse(template.render(context, request))
#render has an inbuilt http return type
def detail(request, album_id):
try:
album = Album.objects.get(pk=album_id)
except Album.DoesNotExist:
raise Http404("Album does not exist")
return render(request, 'music/detail.html', {'album':album})
When i enter http://127.0.0.1:8000/music/3/ it yields a 404 error which i wanted to do but when i type in http://127.0.0.1:8000/music/2/ it starts giving a "TemplateDoesNotExist at /music/2/" error.
Why is this happening...
The problem is that your template file details.html should be detail.html, no s after detail, as in your views.py, it is mentioned as music/detail.html.
or
you can change to music/details.html in your views.py.
The template name should be matched.