TemplateDoesNotExist at /accounts/upload_save/ error - python

I got an error,TemplateDoesNotExist at /accounts/upload_save/
{'form': } .
I wrote in views.py like
def upload(request, p_id):
form = UserImageForm(request.POST or None)
d = {
'p_id': p_id,
'form':form,
}
return render(request, 'registration/accounts/photo.html', d)
#csrf_exempt
def upload_save(request):
if request.method == "POST":
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
data = Post()
data.image = request.FILES['image']
data.save()
else:
form = UploadForm()
return render('registration/accounts/photo.html', {'form':form})
class UploadForm(forms.Form):
image = forms.FileField()
urls.py is
urlpatterns = [
url(r'^regist/$', views.regist,name='regist' ),
url(r'^regist_save/$', views.regist_save, name='regist_save'),
url(r'^profile/$', views.profile, name='profile'),
url(r'^photo/$', views.photo, name='photo'),
url(r'^upload/(?P<p_id>\d+)/$', views.upload, name='upload'),
url(r'^upload_save/$', views.upload_save, name='upload_save'),
]
profile.html is
<div class="container">
<form action="{% url 'accounts:upload_save' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="input-group">
<label class="input-group-btn">
<span class="btn btn-primary btn-lg">
SELECT FILE
<input type="file" style="display:none" name="files[]" multiple>
</span>
</label>
<input type="text" class="form-control" readonly="">
</div>
<div class="form-group">
<input type="hidden" value="{{ p_id }}" name="p_id" class="form-control">
</div>
<div class="form-group">
<input type="submit" value="SEND" class="form-control">
</div>
</form>
</div>
When I put "SEND" button,I wanna show photo.html in the browser.But now the error happens, although I wrote registration/accounts/photo.html in render.I really cannot understand how to fix this.What should I do?

In render pass request as first argument.
return render(request, 'registration/accounts/photo.html', {'form':form})
It will work fine.

Related

2023 Everybody! We made it. I want to update my form, but my details are not pulling through to the form

I want to Update/Edit my details on my form. I want to pull the existing details from the database and have them populate on the form, without having the user start from the beginning.
Views.py
def Client_Update(request, Client_id):
ClientUpdate = TestModel.objects.get(pk=Client_id)
ClientUpdates = TestForm(request.POST or None, instance=ClientUpdate)
if request.method == 'POST':
if ClientUpdates.is_valid():
ClientUpdates.save()
return redirect('/Client_Details')
return render(request, 'GymApp/ClientUpdate.html',
{'ClientUpdate':ClientUpdate,
'ClientUpdates':ClientUpdates})
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.Home, name='Home'),
path('ClientList/', views.Client_list, name='Client_list'),
path('ClientDetails/<int:Client_id>', views.Client_Details, name='Client_Details'),
path('ClientUpdate/<int:Client_id>', views.Client_Update, name='Client_Update'),
path('ClientDelete/<int:Client_id>', views.Client_Delete, name='Client_Delete'),
path('DownloadingCSV/', views.DownloadingCSV, name='DownloadingCSV'),
path('Search/', views.Search, name='Search'),
]
HTML Page
{% extends 'GymApp/Layout.html' %}
{% block content %}
<h1>Updating status</h1>
<form action="" method="POST">
{% csrf_token %}
<div class="mb-3">
<input type="text" class="form-control"
name="Name" placeholder="Client's Name"><br>
<input type="text" class="form-control"
name="Surname"placeholder="Client's Surname"><br>
<select name="Gender" class="form-control">
<option selected disabled>
Open this select menu
</option>
<option value="Male">Male</option><br>
<option value="Female">Female</option>
</select>
</div>
<div class="mb-3">
<input type="text" class="form-control" name="Weight" id="Weight" placeholder="Client's Weight"><br><br>
<input type="text" class="form-control" name="Height" id="Height" placeholder="Client's Height"><br><br>
<button type="button" onclick="calculation()">Calculation update</button>
<br>
</div>
<br>
<div class="mb-3">
<input type="text" class="form-control" name="Outcome" id="Outcome" placeholder="BMI Outcome"><br>
<select name="Activity_log" class="form-control"><br>
<option selected disabled>Open this select menu</option>
<option value="Not Active">Not Active</option><br>
<option value="Active">Active</option>
</select>
<br>
<button type="submit">Finalising update!</button>
</div>
</form>
<script>
function calculation(){
W = document.getElementById('Weight').value;
H = document.getElementById('Height').value;
O = W * H;
document.getElementById('Outcome').value = O;
}
</script>
{% endblock %}
And the outcome when i press the Update button is the following:
As you can the form is empty
How to i pull the existing details on my form? Please help.
from django.db import models
# Create your models here.
class TestModel(models.Model):
Name = models.CharField(max_length=30, blank=True)
Surname = models.CharField(max_length=30, blank=True)
Weight = models.CharField(max_length=30, blank=True)
Height = models.CharField(max_length=30,blank=True)
Gender = models.CharField(max_length=6, blank=True, null=True)
Outcome = models.CharField(max_length=30,blank=True)
Activity = models.CharField(max_length=30, blank=True)
def __str__(self):
return self.Name
And this is my updated HTML
<form action="" method="POST">
{% csrf_token %}
<div class="mb-3">
<input type="text" class="form-control" name="Name" value={{Name}}><br>
<input type="text" class="form-control" name="Surname" value={{Surname}}><br>
<select name="Gender" class="form-control">
<option selected disabled>
Open this select menu
</option>
<option value="Male" value={{Gender}}>Male</option><br>
<option value="Female" value={{Gender}}>Female</option>
</select>
</div>
<div class="mb-3">
<input type="text" class="form-control" id="Weight" value={{Weight}} ><br><br>
<input type="text" class="form-control" id="Height" value={{Height}} ><br><br>
<button type="button" onclick="calculation()">Calculation update</button>
<br>
</div>
<br>
<div class="mb-3">
<input type="text" class="form-control" name="Outcome" id="Outcome" placeholder="BMI Outcome"><br>
<select name="Activity_log" class="form-control"><br>
<option selected disabled>Open this select menu</option>
<option value="Not Active">Not Active</option><br>
<option value="Active">Active</option>
</select>
<br>
<button type="submit">Finalising update!</button>
</div>
</form>
All my views.py
from django.shortcuts import render, redirect
from . models import TestModel
from . forms import TestForm
from django.http import HttpResponse
import csv
# Create your views here.
def Search(request):
if request.method == "POST":
Searching = request.POST['Searching']
Results_query = TestModel.objects.filter(Name__contains=Searching)
{'Searching':Searching,
'Results_query':Results_query}
return render(request, 'GymApp/Searching.html',
{'Searching':Searching,
'Results_query':Results_query})
def DownloadingCSV(request):
response = HttpResponse(content_type='text/csv')
response['content-disposition'] = 'attachment; filename=Client_list.csv'
writer = csv.writer(response)
Downloading_all = TestModel.objects.all()
writer.writerow(['Name','Surname',
'Weight','Height',
'Outcome','Gender',
'Activity'])
for download in Downloading_all:
writer.writerow([download.Name,
download.Surname,
download.Weight,
download.Height,
download.Outcome,
download.Gender,
download.Activity])
return response
def Client_Delete(request, Client_id):
ClientUpdate = TestModel.objects.get(pk=Client_id)
ClientUpdate.delete()
return redirect('Home')
def Client_Update(request, Client_id):
ClientUpdate = TestModel.objects.get(pk=Client_id)
ClientUpdates = TestForm(request.POST or None, instance=ClientUpdate)
if request.method == 'POST':
if ClientUpdates.is_valid():
ClientUpdates.save()
return redirect('/Client_Details')
return render(request, 'GymApp/ClientUpdate.html',
{'ClientUpdate':ClientUpdate,
'ClientUpdates':ClientUpdates})
def Client_list(request):
Clients = TestModel.objects.all()
return render(request, 'GymApp/ClientList.html',
{'Clients':Clients})
def Client_Details(request, Client_id):
ClientDetails = TestModel.objects.get(pk=Client_id)
return render(request, 'GymApp/ClientDetails.html',
{'ClientDetails':ClientDetails})
def Home(request):
Forms = TestForm
if request.method == 'POST':
Forms = TestForm(request.POST or None)
if Forms.is_valid():
Forms.save()
return redirect('Client_list')
return render(request, 'GymApp/Home.html',{})
### You have not given value
<input type="text" class="form-control"
name="Name" value={{ClientUpdates.Name}} placeholder="Client's Name"><br>
###{{Name}} --> your model field name

Two forms on same template in django. How to collaborate the template with the views.py?

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'):
....

How to make search bar working in django?

I made a search bar and I want it to search the titles which is in the site. Before typing nothing appears but whenever I type one title all the titles appear. How to resolve this issue?
index.html
def index(request):
query = request.GET.get('srh')
if query:
target1 = Destination.objects.filter(title__icontains=query)
target1 = a, b= [Destination() for __ in range(2)]
a.img = 'Article.jpg'
b.img = 'Micro Tasks.jpeg'
a.title = 'Article Writing'
b.title = 'Micro Tasks'
context = {'target1': target1}
return render(request, 'index.html', context)
else:
return render(request, 'index.html')
views.py
<form class="love" method="GET" action="">
{% csrf_token %}
<input type="text" placeholder='Search..' name="srh" value="{{request.GET.srh}}"> <br>
<button type="submit" class="btn btn-danger"> Search </button>
</form>
<div>
{% for dest1 in target1 %}
{% if dest1 %}
<div>
<a href="{{baseUrl}}/{{dest1.img}}">
<img src="{{hiUrl}}/{{dest1.img}}" alt="" />
<h3>{{dest1.title}}</h3>
</a>
</div>
{% endif %}
{%endfor%}
</div>
objects.filter reads from the database, but you have no objects in the database.
This should be enough:
def index(request):
query = request.GET.get('srh')
if query:
destinations = Destination.objects.filter(title__icontains=query)
context = {'target1': destinations}
return render(request, 'index.html', context)
else:
return render(request, 'index.html')
But of course it will not return any objects when the database is empty.
.py codes:
def paylasimlar(request):
keyword = request.GET.get("keyword")
if keyword:
paylasimlar = Makale.objects.filter(Q(baslik__contains=keyword) | Q(icerik__contains=keyword))
return render(request, "feed.html", {"paylasimlar": paylasimlar})
and .html
<form style="text-align: right">
{% csrf_token %}
<button type="submit" class="btn btn-default" style="float: right">
<i class="material-icons">search</i>
</button>
<input type="text" name="keyword" class="form-control" placeholder="Anı Ara..." style="border-radius: 20px;float: right;width: 20%" aria-label="Search" >

ValueError at /accounts/upload_save/

I got an error,ValueError at /accounts/upload_save/
The view accounts.views.upload_save didn't return an HttpResponse object. It returned None instead.
Always image cannot be sent normally. I wrote in views.py
def photo(request):
d = {
'photos': Post.objects.all(),
}
return render(request, 'registration/accounts/profile.html', d)
def upload_save(request):
if request.method == "POST":
print(444)
form = UserImageForm(request.POST, request.FILES)
if form.is_valid():
print(5555)
image1 = form.cleaned_data.get('image1')
image2 = form.cleaned_data.get("image2")
user = request.user
ImageAndUser.objects.create(
User=user,
image=image1,
image2=image2,
image3=image3,
)
return redirect('registration/accounts/photo.html')
else:
print(666)
form = UserImageForm(request.POST or None)
return render(request, 'registration/profile.html',{'form':form})
in profile.html
<main>
<div>
<img class="absolute-fill">
<div class="container" id="photoform">
<form action="/accounts/upload_save/" method="POST" enctype="multipart/form-data" role="form">
{% csrf_token %}
  <div class="input-group">
<label>
<input id="image1" type="file" name="image1" accept="image/*" style="display: none">
</label>
    <input type="text" class="form-control" readonly="">
  </div>
  <div class="input-group">
<label>
<input id="image2" type="file" name="image2" accept="image/*" style="display: none">
</label>
    <input type="text" class="form-control" readonly="">
  </div>
  
  <div class="input-group">
<label>
<input id="image3" type="file" name="image3" accept="image/*" style="display: none">
</label>
    <input type="text" class="form-control" readonly="">
  </div>
<div class="form-group">
<input type="hidden" value="{{ p_id }}" name="p_id" class="form-control">
</div>
<input id="send" type="submit" value="SEND" class="form-control">
</form>
</div>
</div>
</div>
</main>
in forms.py
class UserImageForm(forms.ModelForm):
image = forms.ImageField()
class Meta:
model = ImageAndUser
fields = ('image1','image2','image3')
in urls.py
urlpatterns = [
url(r'^profile/$', views.profile, name='profile'),
url(r'^photo/$', views.photo, name='photo'),
url(r'^upload_save/$', views.upload_save, name='upload_save'),
]
I really cannot understand why this error happens.I surely send images so I think type is not None.What is wrong in my code?How should I fix this?I debuged my views.py code,so 444 is shown in print(444).Traceback is
Traceback:
File "/Users/xxx/anaconda/envs/py35/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/Users/xxx/anaconda/envs/py35/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
198. "returned None instead." % (callback.__module__, view_name)
Exception Type: ValueError at /accounts/upload_save/
Exception Value: The view accounts.views.upload_save didn't return an HttpResponse object. It returned None instead.
couple of thing wrong in your code:
First you model looks like this:
Modle: ImageAndUser contain four fieds: user, image, image2, image3
as you have mentioned in object creation.
ImageAndUser.objects.create(User=user,image=image1,image2=image2,image3=image3
)
and you mentioned field in form:
class UserImageForm(forms.ModelForm):
image = forms.ImageField()
class Meta:
model = ImageAndUser
fields = ('image1','image2','image3')
where image1 is coming from. It's image attribute.
do it like this.
class UserImageForm(forms.ModelForm):
class Meta:
model = ImageAndUser
fields = ('image','image2','image3')
Make Edit in your template side.
<input id="image" type="file" name="image" accept="image/*" style="display: none">
</label>
   
Hope this works.
For one thing, image3 is not being set. Try adding this line
image3 = form.cleaned_data.get("image3")
after the one that does the same thing for image2.
Further to that, the view will return None if the form is invalid, i.e. if form.is_valid() returns False.

How do you fix this: IntegrityError at /restaurants/create? - NOT NULL constraint failed: restaurants_restaurantlocation.name

I'm trying to make a django developed website which is called MuyPicky. It is a website which allows you to find restaurants and other things based on your pickiness. I am currently making a page for forms which adds Restaurants to the database. As I am doing this I get this error:
IntegrityError at /restaurants/create.
NOT NULL constraint failed: restaurants_restaurantlocation.name
Is this why I get the error
Here is the forms.py:
class RestaurantCreateForm(forms.Form):
title = forms.CharField()
location = forms.CharField(required = False)
category = forms.CharField(required = False)
The form.html:
{% extends "base.html" %}
{% block title %}Add Restaurant || {{block.super}} {% endblock %}
{% block content %}
<div class="container-fluid">
<div class="container">
<div class="row">
<div class="col-md-offset-4 col-md-4 col-md-offset-4">
<h1>Add Restaurant</h1>
<form method="POST">{% csrf_token %}
<input title="Title" class="form-control" type="text" name="Title" placeholder="Title">
<br>
<input title="Location" class="form-control" type="text" name="Location" placeholder="Location"><br>
<input title="Category" class="form-control" type="text" name="Category" placeholder="Category"><br>
<!--<input title="Save" class="form-control btn btn-info " type="submit" value="Save" >--><br>
<button class="btn btn-success form-control btn-md center-block" type="submit">Save</button>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
The view from views.py:
def restaurant_createview(request):
#if request.method == "GET":
# print("get data")
if request.method == "POST":
title = request.POST.get("title") #(request.POST["title"])
location = request.POST.get("location")
category = request.POST.get("category")
obj = RestaurantLocation.objects.create(
name = title,
location = location,
category = category
)
return HttpResponseRedirect("/restaurants/")
template_name = "restaurants/form.html"
context = {}
return render(request, template_name, context)
Lastly the urls.py:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^/$', TemplateView.as_view(template_name="home.html")),
url(r'^restaurants/$', RestaurantListView.as_view()),
url(r'^restaurants/create/$', restaurant_createview),
url(r'^restaurants/(?P<slug>[\w-]+)/$', RestaurantDetailView.as_view()),
url(r'^contact/$', TemplateView.as_view(template_name="contact.html")),
url(r'^about/$',TemplateView.as_view(template_name="about.html"))]
Your fields have name Title, Location, Category but your Django code is looking for title, location and category. These need to be the same.

Categories

Resources