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.
Related
This question already has answers here:
The view didn't return an HttpResponse object. It returned None instead
(7 answers)
Closed last month.
ValueError at /update_department/14
The view management.views.update_department didn't return an HttpResponse object. It returned None instead.Also when added with return statement data is not updating.
Request information
USER
admin
GET
No GET data
POST
Variable Value
csrfmiddlewaretoken
'XLqZBPhMKImvlfgWsNLeN1Ei8nz5u1HJ15IvAQV4JNwVMeG31rhDOD1q9PJuwXmz'
department_code
'15'
department_name_e
'Finance'
department_name_l
'Finance'
parent_code
''
submit
''
These are the details.I don't know why is there error here while all the posted data is right.also the form is not updating.
Models:
class Departments(models.Model):
department_code = models.CharField(db_column='Department_Code', primary_key= True, max_length=20, db_collation='SQL_Latin1_General_CP1_CI_AS') # Field name made lowercase.
department_name_e = models.CharField(db_column='Department_Name_E', max_length=50, db_collation='SQL_Latin1_General_CP1_CI_AS') # Field name made lowercase.
department_name_l = models.CharField(db_column='Department_Name_L', max_length=50, db_collation='SQL_Latin1_General_CP1_CI_AS') # Field name made lowercase.
parent_code = models.CharField(db_column='Parent_Code', max_length=20, db_collation='SQL_Latin1_General_CP1_CI_AS') # Field name made lowercase.
is_active = models.BooleanField(db_column='Is_Active') # Field name made lowercase.
created_by = models.IntegerField(db_column='Created_By') # Field name made lowercase.
created_date = models.DateTimeField(db_column='Created_date') # Field name made lowercase.
modified_by = models.IntegerField(db_column='Modified_By') # Field name made lowercase.
modified_date = models.DateTimeField(db_column='Modified_date') # Field name made lowercase.
class Meta:
db_table = 'Departments'
unique_together = (('department_code'),)
def __str__(self):
return str("self.department_name_e") or ''
View:
#login_required
def update_department(request, department_code):
dep_up = Departments.objects.get(department_code=department_code)
if request.method == "POST":
form = DepartmentsForm(request.POST, instance = dep_up)
if form.is_valid():
department_code = form.cleaned_data['department_code']
department_name_e = form.cleaned_data['department_name_e']
department_name_l = form.cleaned_data['department_name_l']
parent_code = form.cleaned_data['parent_code']
obj = form.save(commit = False)
obj.is_active = True
obj.created_by = request.user.id
obj.created_date = datetime.today()
obj.modified_by = request.user.id
obj.modified_date = datetime.today()
obj.save()
return HttpResponseRedirect('department_list')
forms:
class DepartmentsForm(forms.ModelForm):
class Meta:
model = Departments
fields = ['department_code','department_name_e','department_name_l','parent_code']
HTML:
{% extends 'base.html' %}
{% block title %}Update Company{% endblock title %}
{% block body %}
<div style="margin-left:22%" class=" top-marg">
<h2 ><strong>Company:</strong></h2><br><br>
<form class="" action="{%url 'update_company' comp_up.company_code %}" method="post">
{% csrf_token %}
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<input type="text" value="{{comp_up.company_code}}" class="form-control" id="company_code" name="company_code" placeholder="Company Code" required>
<label style="margin-left:15px" for="company_code">Company Code</label>
</div>
<br>
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<input type="text" value="{{comp_up.company_name_e}}" class="form-control" id = "company_name_e" name="company_name_e" placeholder="Enter Company" required>
<label style="margin-left:15px" for="company_name_e">Company Name English</label>
</div>
<br>
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<input type="text" value="{{comp_up.company_name_l}}" class="form-control" id = "company_name_l" name="company_name_l" placeholder="Enter Company" required>
<label style="margin-left:15px" for="company_name_e">Company Name Local</label>
</div>
<br>
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<input type="tel" value="{{comp_up.tel}}" class="form-control" id = "tel" name="tel" placeholder="Telephone Number" required>
<label style="margin-left:15px" for="tel">Telephone Number</label>
</div>
<br>
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<input type="tel" value="{{comp_up.fax}}" class="form-control" id = "fax" name="fax" placeholder="Enter Fax"required>
<label style="margin-left:15px" for="fax"> Fax Number</label>
</div>
<br>
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<textarea name="address" class="form-control" rows="4" cols="100" placeholder="Address" required>{{comp_up.address}}</textarea>
<label style="margin-left:15px" for="address">Address</label>
</div>
<br>
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<select class="form-control" name="country_id" required>
<option value="{{comp_up.country_id.id}}" >{{comp_up.country_id.country_name_e}}</option>
{% for con in country %}
<option value="{{con.id}}" >{{con.country_name_e}}</option>
{% endfor %}
</select>
</div>
<br>
<label style = "margin-left:21%; " for="logo">Logo</label>
<div class="form-floating" >
<input value="{{comp_up.}}" style = "margin-left:21%;" accept="image/*" type="file" name="logo" onchange="loadFile(event)" required> <br>
<img style = "margin-left:21%;" id="output" >
<script>
var loadFile = function(event) {
var output = document.getElementById('output');
output.src = URL.createObjectURL(event.target.files[0]);
output.onload = function() {
URL.revokeObjectURL(output.src) // free memory
}
};
</script>
</div>
<br><br>
<center>
<button type="submit" class="btn btn-success" name="submit">Update</button>
<button type="button" class="btn btn-primary" onclick="window.location.href = '{%url 'company_list'%}'" name="cancel">Cancel</button>
</center>
</form>
</div>
{% endblock body %}
You have provided HttpReponse only for POST and valid form. You should give the standard response (with empty form) for fresh entries or posting with errors. Like this:
#login_required
def update_department(request, department_code):
dep_up = Departments.objects.get(department_code=department_code)
if request.method == "POST":
form = DepartmentsForm(request.POST, instance = dep_up)
if form.is_valid():
...
return HttpResponseRedirect('department_list')
form = DepartmentsForm()
return render(request, 'template.html', context={'form': 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
I have been trying to make the date field in a form to display the current date when it renders. But I have failed to find a proper solution to this problem.
Please find below the code.
HTML File
<form class="form-horizontal" role="form" method = 'POST'>
{% csrf_token%}
<h2>New Manufacturer Details</h2>
<div class="form-group row">
<label for="createddate" class="col-sm-3 control-label">Created Date</label>
<div class="col-sm-9">
<input type="date" id="createddate" name = "createddate" class="form-control" autofocus required="true" value = '{{ createddate }}'>
</div>
</div>
<div class="form-group row">
<label for="manufname" class="col-sm-3 control-label">Name</label>
<div class="col-sm-9">
<input type="text" id="manufname" name = "manufname" placeholder="Manufacturer Name" class="form-control" autofocus required="true" value = '{{ manufname }}'>
</div>
</div>
<div class="form-group row">
<label for="manufaddress" class="col-sm-3 control-label">Address</label>
<div class="col-sm-9">
<textarea class="form-control" id="manufaddress" name = "manufaddress" placeholder="Manufacturer Address" rows="3" required="true" value = '{{ manufaddress }}'></textarea>
</div>
</div>
<div class="form-group row">
<label for="manufcontact" class="col-sm-3 control-label">Contact Name</label>
<div class="col-sm-9">
<input type="text" id="manufcontact" name = "manufcontact" placeholder="Manufacturer POC" class="form-control" autofocus required="true" value = '{{ manufcontact }}'>
</div>
</div>
<div class="form-group row">
<label for="manufcontactnum" class="col-sm-3 control-label">Contact Number</label>
<div class="col-sm-9">
<input type="text" id="manufcontactnum" name = "manufcontactnum" placeholder="Manufacturer Contact Number" class="form-control" autofocus required="true" value = '{{ manufcontactnum }}'>
</div>
</div>
<div class="form-group row">
<label for="manufemailid" class="col-sm-3 control-label">Email Id</label>
<div class="col-sm-9">
<input type="email" id="manufemailid" name = "manufemailid" placeholder="Manufacturer Email Id" class="form-control" autofocus required="true" value = '{{ manufemailid }}'>
</div>
</div>
<div class="form-group row">
<label for="manufgst" class="col-sm-3 control-label">GST No</label>
<div class="col-sm-9">
<input type="text" id="manufgst" name = "manufgst" placeholder="Manufacturer GST Number" class="form-control" autofocus required="true" value = '{{ manufgst }}'>
</div>
</div>
<div class="form-group row">
<label for="manuflicenseno" class="col-sm-3 control-label">License No</label>
<div class="col-sm-9">
<input type="text" id="manuflicenseno" name = "manuflicenseno" placeholder="Manufacturer License Number" class="form-control" autofocus required="true" value = '{{ manuflicenseno }}'>
</div>
</div>
<div class="form-group row">
<label for="manufbank" class="col-sm-3 control-label">Bank Details</label>
<div class="col-sm-9">
<textarea class="form-control" id="manufbank" name = "manufbank" placeholder="Manufacturer Bank Details" rows="3" required="true" value = '{{ manufbank }}'></textarea>
</div>
</div>
<div class="col text-center">
<button type="submit" class="btn btn-primary" id="form-submit">Save</button>
</div>
</form> <!-- /form -->
<script>
$("#form-horizontal").validate();
</script>
Views.Py
def createmanufacturer(request):
if request.method == 'POST':
form = CreateManufacturerForm(request.POST or None)
if form.is_valid():
form.save()
else:
createddate = request.POST['createddate']
manufname = request.POST['manufname']
manufaddress = request.POST['manufaddress']
manufcontact = request.POST['manufcontact']
manufcontactnum = request.POST['manufcontactnum']
manufemailid = request.POST['manufemailid']
manufgst = request.POST['manufgst']
manuflicenseno = request.POST['manuflicenseno']
manufbank = request.POST['manufbank']
messages.success(request, ('There was an error in your form! Please try again...'))
return render(request, 'screens/createmanufacturer.html', {
'createddate' : createddate,
'manufname' : manufname,
'manufaddress' : manufaddress,
'manufcontact' : manufcontact,
'manufcontactnum' : manufcontactnum,
'manufemailid' : manufemailid,
'manufgst' : manufgst,
'manuflicenseno' : manuflicenseno,
'manufbank' : manufbank,
})
messages.success(request, ('Manufacturer Details have been submitted successfully'))
return redirect("screens:testpage")
else:
form = CreateManufacturerForm()
return render(
request = request,
template_name = 'screens/createmanufacturer.html',
context = {'form' : form}
)
forms.py
class CreateManufacturerForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(CreateManufacturerForm, self).__init__(*args, **kwargs)
self.fields['createddate'].initial = date.today
class Meta:
model = Manufacturer
#createddate = forms.DateField(initial=date.today)
fields = ['createddate',
'manufname',
'manufaddress',
'manufcontact',
'manufcontactnum',
'manufemailid',
'manufgst',
'manuflicenseno',
'manufbank']
models.py
class Manufacturer(models.Model):
createddate = models.DateField()
manufname = models.CharField(max_length = 255)
manufaddress = models.TextField()
manufcontact = models.CharField(max_length = 255)
manufcontactnum = models.CharField(max_length = 25)
manufemailid = models.EmailField(max_length = 200)
manufgst = models.CharField(max_length = 255)
manuflicenseno = models.CharField(max_length = 255)
manufbank = models.TextField()
manufcode = models.CharField(max_length = 255, primary_key=True, editable=False)
def __str__(self):
return self.manufname
Right now, nothing happens when the form renders. What I want is the date in the Created Date should be set to today's date. However the user could leave it as is or could select a date of his/her choice. But the requirement is that date field should be pre-populated with the current date.
Please find below the screenshot of the web form.
Web Form
To save the current use auto_now=True
class DateField(auto_now=False, auto_now_add=False, **options)¶
A date, represented in Python by a datetime.date instance. Has a few extra, optional arguments:
DateField.auto_now¶
Automatically set the field to now every time the object is saved. Useful for “last-modified” timestamps. Note that the current date is always used; it’s not just a default value that you can override
To display current date in the form use :
form = CreateManufacturerForm(initial={'createddate': datetime.now()})
So, after a lot of frustrating hours, I was able to finally solve the problem, with help from my friend Houda. This is what I did.
views.py
In the GET portion of the code, I wrote the following.
initial_data = {
'createddate' : date.today().strftime("%Y-%m-%d"),
}
form = CreateManufacturerForm(initial = initial_data)
template.html file
I changed the following
<input type="date" id="createddate" name = "createddate" class="form-control" autofocus required="true" value = '{{ form.createddate.value }}'>
I am not sure if this is the best solution. But at least I got it to work. I believe the issue had something to do with the date format that HTML has for the
input type = 'date'
it only allows 'YYYY-mm-dd'
Thanks everyone.
I am trying to upload pictures from an imageField, but it doesn't upload anything when I try.
models.py
def upload_location(instance, filename):
return "uploads/%s/img/%s/" % (instance.id, filename)
class CustomUser(AbstractBaseUser, PermissionsMixin):
...
width_field = models.IntegerField(default=0)
height_field = models.IntegerField(default=0)
photo = models.ImageField(
upload_to=upload_location,
null=True, blank=True,
width_field="width_field",
height_field="height_field"
)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
objects = UserManager()
forms.py
class UserConfigurationForm(UserChangeForm):
class Meta:
model=CustomUser
fields = ('first_name', 'last_name', 'email', 'phone_number',
'direction', 'password', 'photo',)
views.py
def configuration(request):
categoria = Clasificacion.objects.filter(existencia=True)
templates = Templates.objects.get(isSelected=True)
if request.method == 'GET':
form = UserConfigurationForm(instance=request.user)
else:
form = UserConfigurationForm(request.POST or None, request.FILES or None, instance=request.user)
if form.is_valid():
form.save()
return redirect('myuser:myuser')
return render(request, 'myuser/configuration.html', {'form': form, 'categoria':categoria,'templates':templates})
template
<form method="post" action='' enctype="multipart/form-data">
{%csrf_token%}
<div class="col-sm-8 ">
<strong>{{form.photo}}</strong></div>
<!--FIRST NAME-->
<label for="first_name">Nombre</label>
<div class="form-group">
<input class= "form-control" type="text" name="first_name" maxlength="20" value="{{user.first_name}}" required>
</div>
<label for="last_name">Apellidos</label>
<div class="form-group">
<input class="form-control" type="text" name="last_name" value="{{user.last_name}}">
</div>
<!--Username and email is same in this case-->
<label for="last_name">Correo electrónico</label>
<div class="form-group">
<input class= "form-control" type="email" name="email" value="{{user.email}}" required>
</div>
<!--Phone number-->
<label for="phone_number">Teléfono</label>
<div class="form-group">
<input class= "form-control" type="tel" pattern="[0-9]{4}-[0-9]{3}-[0-9]{4}" name="phone_number" placeholder="Formato ejem: 0414-685-4716" value="{{user.phone_number}}"required>
</div>
<!--Direction-->
<label for="direction">Dirección</label>
<div class="form-group">
<textarea id="direction" class= "form-control" rows="6" name="direction"
value="{{user.direction}}" required>{{user.direction}}</textarea>
</div>
<!--SUBMIT-->
<div class="form-group">
<div class="col-xs-12">
<br>
<button type="submit" class="btn btn-lg btn-success">Guardar cambios</button>
</div>
</form>
I did it before but I don't know what is causing this. The other fields are working fine, I just have the problem with the photo. I put the enctype, and the request.FILES but it doesn't work.
Hope you can help me! Thank you!
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.