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
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'):
....
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 }'
as the questions states i receive two errors in my template. Here is the code
def create(request):
full_content = forms.InputForm()
if request.method == "POST":
full_content = forms.InputForm(request.POST)
if full_content.is_valid():
title = full_content.cleaned_data["title"]
content = full_content.cleaned_data["content"]
if full_content.clean_title():#Works
full_content.create(title, content)
context= {
'title' : util.get_page_name(title),
'entry' : util.get_entry(title),
}
return render(request, "encyclopedia/entry.html",context)
#From here on its not valid:
context = {
'form':full_content
}
return render(request, "encyclopedia/create.html", context)
return render(request, "encyclopedia/create.html", {
'form':full_content
})
And the forms.clean_title():
def clean_title(self):
title_name = self.cleaned_data.get("title")
filename = f'entries/{title_name}.md'
if default_storage.exists(filename):
raise ValidationError("This title is already taken")
return title_name
Ofcourse the create.html aswell:
<h3>Create new entry</h3>
<form action="{% url 'create'%}" method="POST">
{{ form.title.errors }}
{% csrf_token %}
<table>
{{form.as_p}}
</table>
<button type="submit" value="save">Save</button>
</form>
Any ideas why i get two bullets?:
This title is already taken
This title is already taken
No need {{ form.title.errors }}. {{form.as_p}} is also show errors. So remove it.
<h3>Create new entry</h3>
<form action="{% url 'create'%}" method="POST">
{% csrf_token %}
<table>
{{form.as_p}}
</table>
<button type="submit" value="save">Save</button>
</form>
views.py:
def sub_comment(request):
if request.method == 'POST':
form = CommentCreateForm(request.POST, request.FILES)
content=request.POST.get('content')
print ',==>', content
topic_id=request.POST.get('topic_id')
print ',--->', topic_id
if form.is_valid():
new_comment = Comment(content=content,
topic_id=topic_id,
created_by=request.user,
)
new_comment.save()
return HttpResponseRedirect('/topic/topic_detail/%s' % topic_id)
else:
form = CommentCreateForm()
variables = RequestContext(request, {'form':form})
return render_to_response('topic/topic_detail.html', variables)
forms.py:
class CommentCreateForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['content', 'created_by',]
templates:
<form action="/topic/sub_comment/" method="post" enctype="multipart/form-data" name="comment">
{% csrf_token %}
<textarea name="content" rows="8" cols="50"></textarea>
<input type="hidden" name="topic_id" value="{{ topics.id }}">
<input type="submit" value="Add comments" />
</form>
There is no error, but comment's data can't save to my database, and it turn into http://127.0.0.1:8000/topic/sub_comment website.
urls.py:
url(r'^sub_comment/$', views.sub_comment, name="sub_comment"),