I have my views file:
from django.shortcuts import render
from .models import Note
# Create your views here.
def index(request):
return render(request, "index.html", {})
def write(request):
notes = Note.objects
return render(request, "write.html", {})
def create(request):
if request.POST:
body = request.POST['note']
title = request.POST['title']
print(f'title = { title }\nbody = { body }'
and my html code:
<h1>CREATE A NOTE</h1>
<form action="{% url 'notes:create' %}" method="post">
{% csrf_token %}
<label for="title">Title</label>
<input type="text" name="title"><br>
<label for="note">Note</label>
<input type="text" name="note"><br>
<input type="submit" value="Submit">
</form>
Whenever I submit this form and try to access either the title or note values I get a MultiValueDictKeyError
A MultiValueDictKeyError comes when you try to access something from request.POST which doesn't exist. It's basically the same the python KeyError. Use request.POST.get('key', 'default_if_key_doesn't exist')
def create(request):
if request.POST:
body = request.POST.get('note', '')
title = request.POST('title', '')
print(f'title = { title }\nbody = { body }'
Related
I'm not sure what is coursing the problem....
The view Insertemp.views.Insertrecord didn't return an HttpResponse object. It returned None instead.
views.py
from django.shortcuts import render
from Insertemp.models import EmpInsert
from django.contrib import messages
def Insertrecord(request):
if request.method == 'POST':
if request.POST.get('empname') 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()
messages.success(request, 'Record saved successfully...!')
return render(request, 'Index.html')
else:
return render(request, 'Index.html'),
I have change the code....
from django.shortcuts import render
from Insertemp.models import EmpInsert
from django.contrib import messages
def Insertrecord(request):
if request.method == 'POST':
if request.POST.get('empname') 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()
messages.success(request, 'Record saved successfully...!')
return render(request, 'templates/Index.html', {})
else:
return render(request, 'templates/Index.html', {})
but still it doesn't display what it should...
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Insert new Record</title>
</head>
<body>
<h1>Create or New record Insert into MySQL(PhpMyAdmin)</h1>
<h2>Python Django web Programming</h2>
<hr>
<form method="POST">
{% cdrf_token %}
Employee Name : <input type="text" placeholder="Enter Name" name="empname" required>
Email : <input type="text" placeholder="Enter Email" name="email" required>
country : <input type="text" placeholder="Enter Country" name="country" required>
<input type="submit" value="Insert record">
{% if messages %}
{% for message in messages %}
<h2 style="color: green;">{{message}}</h2>
{% endfor %}
{% endif %}
</form>
<hr>
</body>
</html>
You need to give default response, in example for GET requests:
def Insertrecord(request):
if request.method == 'POST':
if request.POST.get('empname') and request.POST.get('email') and request.POST.get('country'):
(...)
return render(request, 'templates/Index.html', {})
else:
return render(request, 'templates/Index.html', {})
return render(request, 'templates/Index.html', {}) # new
I have a template with two forms like this and two textareas where the uploaded content will be returned:
<form
class="form-inline"
role="form"
action="/controlepunt140"
method="POST"
enctype="multipart/form-data"
id="form_pdf"
>
<div class="form-group">
{% csrf_token %} {{ form_pdf }}
<button type="submit" name="form_pdf" class="btn btn-warning">Upload!</button>
</div>
</form>
<div class="form-outline">
<div class="form-group">
<textarea class="inline-txtarea form-control" cols="70" rows="25">
{{content}}</textarea
> <form
class="form-inline"
role="form"
action="/controlepunt140"
method="POST"
enctype="multipart/form-data"
id="form_excel"
>
<div class="form-group">
{% csrf_token %} {{ form }}
<button type="submit" name="form_excel" class="btn btn-warning">Upload!</button>
</div>
</form>
<textarea class="inline-txtarea form-control" cols="65" rows="25">
{{content_excel}}</textarea
>
and the views.py:
class ReadingFile(View):
def get(self, request):
form = ProfileForm()
return render(request, "main/controle_punt140.html", {
"form": form
})
def post(self, request):
types_of_encoding = ["utf8", "cp1252"]
submitted_form = ProfileForm(request.POST, request.FILES)
content = ''
if submitted_form.is_valid():
uploadfile = UploadFile(image=request.FILES["upload_file"])
name_of_file = str(request.FILES['upload_file'])
uploadfile.save()
for encoding_type in types_of_encoding:
with open(os.path.join(settings.MEDIA_ROOT,
f"{uploadfile.image}"), 'r', encoding=encoding_type) as f:
if uploadfile.image.path.endswith('.pdf'):
pass
else:
content = f.read()
return render(request, "main/controle_punt140.html", {
'form': ProfileForm(),
"content": content
})
return render(request, "main/controle_punt140.html", {
"form": submitted_form,
})
and forms.py:
class ProfileForm(forms.Form):
upload_file = forms.FileField()
and urls.py:
urlpatterns = [
path('', views.starting_page, name='starting_page'),
path('controlepunt140', views.ReadingFile.as_view(), name='controlepunt140')
]
So this works for the first upload function(pdf). The output is returned to the textarea.
But how to have it also work with the second upload function content_excel?
I.E: how to distinguish the two upload functions?
So this part:
return render(request, "main/controle_punt140.html", {
'form': ProfileForm(),
"content": content
})
return render(request, "main/controle_punt140.html", {
"form": submitted_form,
})
Would be double? one for pdf and one for excel
According to the name of the submit buttons:
#FORM PDF
<button type="submit" name="form_pdf" class="btn btn-warning">Upload!</button>
#FORM EXCEL
<button type="submit" name="form_excel" class="btn btn-warning">Upload!</button>
So, in your views.py you can distinguish them on this way:
if request.POST.get('form_pdf'):
....
elif request.POST.get('form_excel'):
....
Basically, from and to both page have parameters so how can I redirect to page with parameters?
html page:
{% for vr in adduser.adduser.all %}
<form method="POST" action="{% url 'edituser' id=vr.id bid=adduser.id %}">
{% csrf_token %}
<label for="FirstName">First Name<span style="color:#ff0000">*</span></label>
<input type="text" class="form-control" name="firstname" placeholder="Type FirstName here...." value="{{vr.f_name}}">
<label for="LastName">Last Name<span style="color:#ff0000">*</span></label>
<input type="text" class="form-control" name="lastname" placeholder="Type LastName here...." value="{{vr.l_name}}">
{% endfor %}
<button type="submit" class="btn btn-primary">Add</button>
urls.py
path('edituser/<uid>/<bid>', views.edituser, name="edituser"),
views.py
def edituser(request, uid, bid):
if request.method == "POST":
if request.POST.get('firstname') and request.POST.get('lastname'):
saverecord = AddContact()
saverecord.id = uid
saverecord.f_name = request.POST.get('firstname')
saverecord.l_name = request.POST.get('lastname')
saverecord.save()
viewRecords = AddContact.objects.filter(subscribe='subscribe')
return HttpResponseRedirect(reverse('adduser',bid))
else:
viewRecords = AddContact.objects.filter(subscribe='subscribe')
messages.error(request, "Error During Editing of Contact")
return redirect(request, 'broadcastlist.html')
else:
viewRecords = AddContact.objects.filter(subscribe='subscribe')
messages.error(request, "Error During Editing of Contact")
return redirect(request, 'broadcastlist.html')
To clarify more uid is userid which is for edit the user and bid is broadcast id which is to redirect to the broadcast list.
To redirect to another page in Django with parameters use this
return HttpResponseRedirect(reverse(viewname='the view to which it should redirect', args=(parameters to be passed)))
Use redirect, it's easier than invoking reverse and HttpResponseRedirect directly. (Doc)
from django.shortcuts import redirect
...
return redirect( 'myapp:url_name', urlparam=value, ...)
which is the same as
return HttpResponseRedirect(
reverse( 'myapp:url_name',
kwargs={ 'urlparam': value, ... }
)
I want to create a simple wiki page, which is comprised of several entries.
But have an error TypeError at /addentry
__init__() got an unexpected keyword argument 'title'
The main thing here is entry model.
Here is part of my models.py:
class wikies(models.Model):
num = models.CharField(max_length=15)
title = models.CharField(max_length=150)
text = models.TextField()
And here is part of my forms.py:
class entryform(ModelForm):
class Meta:
model = wikies
fields = ['num', 'title', 'text']
Part of my template:
<form action="{% url 'addentry' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p> {{entryform.num}} </p>
<p> {{entryform.title}} </p>
<p> {{entryform.text}}</p>
<p><input type="submit" value="Add Entry" /></p>
This is part of my views.py, where I catch the error:
def addentry(request):
if request.method =='POST':
form = entryform(num = request.POST['num'],
title = request.POST['title'],
text = request.POST['text']
)
I want to bound the form with values I just get, but have the following error:
TypeError at /addentry
init() got an unexpected keyword argument 'title'
Here are POST values:
num
'1.2.3'
text
'Water is very important resource.'
title
'Importance of water'
I've read the docs, I've searched through StackOverflow, but I have no idea what to do. Will appreciate any help.
#views.py
def addentry(request):
if request.method =='POST':
form = entryform(request.POST)
if form.is_valid():
form.save(commit=Fale)
num = form.cleaned_data['num'],
title = form.cleaned_data['title'],
text = form.cleaned_data['text']
form.save(commit=True)
return redirect('/')
else:
form=entryform()
return render(request,....,{'form':form})
#template
<form action="{% url 'addentry' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{form.as_p}}
<input type="submit" name="submit">
</form>
I am trying to get name and surname values and print it to HTML. This is my code:
Views.py
from django.shortcuts import render
from django.http import HttpResponse
from emailai.models import Vartotojas
from renginiai.forms import VartotojasForm
def name(request):
if request.method == 'GET':
form = VartotojasForm(request.GET)
name = form.data['name']
surname = form.data['surname']
return render(request, 'vartotojas-result.html', {'form': form, 'name': names, 'surname': surname })
else:
form = VartotojasForm()
return render(request, 'vartotojas-form.html', {'form': form})
Vartotojas-form.html
<html>
<head>
<title>Name</title>
</head>
<body>
<h1>Name</h1>
<form action="sumbit" method="get">
<table>
{{ form.as_table }}
</table>
{% csrf_token %}
<input type="submit" value="Submit">
</form>
</body>
I am getting KeyError at /name/ . Where is my mistake?
Try this:
def name(request):
if request.method == 'POST':
form = VartotojasForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
surname = form.cleaned_data['surname']
return render(request, 'vartotojas-result.html', {'form': form, 'name': name, 'surname': surname })
else:
form = VartotojasForm()
return render(request, 'vartotojas-form.html', {'form': form})
Also in render parameters , your names variable is undefined:
{'form': form, 'name': names, 'surname': surname }
change it to name:
{'form': form, 'name': name, 'surname': surname }
And change your Vartotojas-form.html form to:
<html>
<head>
<title>Name</title>
</head>
<body>
<h1>Name</h1>
<form action="sumbit" method="post">
<table>
{{ form.as_table }}
</table>
{% csrf_token %}
<input type="submit" value="Submit">
</form>
</body>
Make sure your template uses name parameter in the input tag
<input type="text" name="surname" value="">
<input type="text" name="name" value="">
and that the fields in Django form match the fields in html form