i tried using class based views for signup but when i try to add images to the form fields, i keep getting this field is required the problem is with the image file
this is the forms.py file
`
from django import forms
from .models import User
class USerForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User
fields = ['username', 'email', 'password', 'company', 'description', 'logo']
`
and the views.py file
from django.shortcuts import render, redirect
from django.views.generic import View, TemplateView
from .forms import USerForm
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.views.generic.edit import UpdateView
# Create your views here.
#login_required(login_url="/jembe/login/")
def index(request):
return render(request, 'base.html')
class SignUp(View):
form_class = USerForm
template_name = 'signup.html'
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
def post(self, request):
form = self.form_class(request.POST, request.FILES)
if form.is_valid():
user = form.save(commit=False)
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user.set_password(password)
user.save()
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('invoice:index')
return render(request, self.template_name, {'form': form})
class LogoutView(View):
def get(self, request):
logout(request)
return HttpResponseRedirect('/jembe/login')
class AboutView(TemplateView):
template_name = "about.html"
models.py file
`from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
company = models.CharField(max_length=300)
description = models.TextField(blank=True)
website = models.URLField()
logo = models.ImageField(upload_to='../media/')
`
register.html
{% load staticfiles %}
{% load i18n widget_tweaks %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="img/favicon_1.ico">
<title>{% block title %} Signup {% endblock %} |Jims</title>
""
<!-- Bootstrap core CSS -->
<link href="{% static 'login/css/bootstrap.min.css' %}" rel="stylesheet">
<link href="{% static 'login/css/bootstrap-reset.css' %}" rel="stylesheet">
<!--Animation css-->
<link href="{% static 'login/css/animate.css' %}" rel="stylesheet">
<!--Icon-fonts css-->
<link href="{% static 'login/assets/font-awesome/css/font-awesome.css' %}" rel="stylesheet" />
<link href="{% static 'login/assets/ionicon/css/ionicons.min.css' %}" rel="stylesheet" />
<!--Morris Chart CSS -->
<link rel="stylesheet" href="{% static 'login/assets/morris/morris.css">
<!-- Custom styles for this template -->
<link href="{% static 'login/css/style.css' %}" rel="stylesheet">
<link href="{% static 'login/css/helper.css' %}" rel="stylesheet">
<link href="{% static 'css/style.css' %}" rel="stylesheet">
<link href="{% static 'css/bootstrap.css' %}" rel="stylesheet">
<link href="{% static 'css/main.css' %}" rel="stylesheet">
<link rel='stylesheet prefetch' href='http://fonts.googleapis.com/css?family=Roboto:400,100,300,500,700,900|RobotoDraft:400,100,300,500,700,900'>
<link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css'>
<!-- HTML5 shim and Respond.js IE8 support of HTML5 tooltipss and media queries -->
<!--[if lt IE 9]>
<script src="js/html5shiv.js"></script>
<script src="js/respond.min.js"></script>
<![endif]-->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','../../../www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-62751496-1', 'auto');
ga('send', 'pageview');
</script>
</head>
<body>
<div class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href=""><div class="logo">
<a href="" class="logo-expanded">
<i class="ion-compose"></i>
<span class="nav-label">Jigs</span>
</a>
</div></a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li><strong>About</strong></li>
<li><strong>Login</strong></li>
<li><strong>Register</strong></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
<div class="wrapper-page animated fadeInDown">
<div class="panel panel-color panel-primary">
<div class="panel-heading">
<h3 class="text-center m-t-10"> Create a new Account </h3>
</div>
{# error logic #}
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ error | escape }}</strong>
</div>
{% endfor %}
{% for error in form.non_field_errors %}
<div class="alert alert-danger">
<strong> {{ error | escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% endif %}
{# end error logic #}
<form class="form-horizontal m-t-40" action="" method="post">
{% csrf_token %}
{% for field in form %}
<div class="form-group">
<div class="col-xs-12">
<label> {{ field.label }} </label>
{{ field|attr:"class:form-control" }}
</div>
</div>
{% endfor %}
<div class="form-group ">
<div class="col-xs-12">
<label class="cr-styled">
<input type="checkbox" checked>
<i class="fa"></i>
I accept <strong>Terms and Conditions</strong>
</label>
</div>
</div>
<div class="form-group text-right">
<div class="col-xs-12">
<button class="btn btn-purple w-md" type="submit">Register</button>
</div>
</div>
<div class="form-group m-t-30">
<div class="col-sm-12 text-center">
Already have account?
</div>
</div>
</form>
</div>
</div>
<!-- js placed at the end of the document so the pages load faster -->
<script src="{% static 'login/js/jquery.js' %}"></script>
<script src="{% static 'login/js/bootstrap.min.js' %}"></script>
<script src="{% static 'login/js/pace.min.js' %}"></script>
<script src="{% static 'login/js/wow.min.js' %}"></script>
<script src="{% static 'login/js/jquery.nicescroll.js' %}" type="text/javascript"></script>
<!--common script for all pages-->
<script src="{% static 'login/js/jquery.app.js' %}"></script>
<hr/>
<center><h3 class="text text-success"> Jembe™ © 2017</h3></center>
</body>
</html>
You have forgotten to set enctype in your form. It should be:
<form class="form-horizontal m-t-40" action="" method="post" enctype="multipart/form-data">
See the Django docs on file uploads for more info.
Related
I am new to Django and am trying to make an online journal, and the server runs fine, but when I press the create button, it does not redirect to the form even though a POST request is being sent. screenshot of the create page. I'm not sure why.
This is the code:
views.py:
from django.shortcuts import render, redirect, get_object_or_404
from ejournal.models import Journal
from ejournal.forms import JournalForm
def make_entry(request):
if request.method == "POST":
entry = JournalForm(request.POST, request.FILES)
if entry.is_valid():
entry.save()
return redirect('list_journals')
else:
entry = JournalForm()
context = {
'entry':entry
}
return render(request, 'ejournal/create.html', context)
def delete_entry(request, id):
entry = get_object_or_404(Journal, id=id)
if request.method == "POST":
entry.delete()
return redirect('list_journals')
context = {
'object':object
}
return render(request, 'journal/delete.html',context)
def list_journals(request):
entries = Journal.objects.all()
context = {
'entries': entries
}
return render(request, 'ejournal/list_journals.html',context)
def journal_detail(request, id):
journal = Journal.objects.get(id=id)
context = {
'journal':journal
}
return render(request, 'journal/journal_detail.html', context)
forms.py
from ejournal.models import Journal
from django.forms import ModelForm
class JournalForm(ModelForm):
class Meta:
model = Journal
fields = ['name','title','text','image']
models.py
from django.db import models
class Journal(models.Model):
name = models.CharField(max_length=20)
title = models.CharField(max_length=50)
text = models.TextField(max_length=1000)
date = models.DateField(auto_now_add=True)
image = models.FileField(upload_to='')
archived = models.BooleanField(default=False)
def __str__(self):
return self.name
base.html
{% load static %}<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>My Online Journal</title>
<!-- Bootstrap core CSS -->
<link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
<link href="{% static 'css/style.css' %}" rel="stylesheet">
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand" href="{% url 'list_journals' %}">Smart Journal</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="btn btn-outline-info btn-md" href="{% url 'list_journals' %}">LIST ALL</a>
</li>
</ul>
</div>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="btn btn-outline-info btn-md" href="{% url 'make_entry' %}">+ New Journal Entry </a>
</li>
</ul>
</div>
</div>
</nav>
<!-- Page Content -->
<div class="container" id="app">
{% block content %}
{% endblock %}
</div>
<!-- /.container -->
<!-- Bootstrap core JavaScript -->
<script src="{% static 'js/jquery.min.js' %}"></script>
<script src="{% static 'js/bootstrap.min.js' %}"></script>
</body>
</html>
create.html
{% extends 'ejournal/base.html' %}
{% block content %}
<div class="center_journal">
<h1> Create Journal Entry </h1>
</div>
<div class="center_journal">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.as_p }}</p>
<button class="btn btn-primary" type="submit">CREATE</button>
</form>
</div>
{% endblock content %}
urls.py
from django.urls import path
from ejournal.views import make_entry, delete_entry, list_journals, journal_detail
urlpatterns = [
path('create', make_entry, name="make_entry"),
path('list_journals', list_journals, name="list_journals"),
path('delete/<int:id>/', delete_entry, name="delete_entry"),
path('journal_detail/<int:id>',journal_detail, name="journal_detail"),
]
You pass the form as the variable entry to your template ejournal/create.html.
Inside this template you use {{ form.as_p }}, but form is undefined. You need to use the variable entry because thats where the form is assigned to.
So your create.html becomes this:
{% extends 'ejournal/base.html' %}
{% block content %}
<div class="center_journal">
<h1> Create Journal Entry </h1>
</div>
<div class="center_journal">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ entry.as_p }}</p>
<button class="btn btn-primary" type="submit">CREATE</button>
</form>
</div>
{% endblock content %}
You're checking if your form is valid by using entry.is_valid(), but your form will always be invalid because you didn't pass the correct form in your template, as described above.
Check with form's action='' attribute like this...
<form method="POST" action="{% url 'make_entry' %}" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.as_p }}</p>
<button class="btn btn-primary" type="submit">CREATE</button>
</form>
I am getting a helper object provided to {% crispy %} tag must be a crispy.helper.FormHelper object error when trying to access a slice of the form. As shown in forms.py below, I would like to access the first Div using a layout slice (https://django-crispy-forms.readthedocs.io/en/latest/dynamic_layouts.html), so that I can display ONLY that Div within a tab in my HTML. In ref_detail.html below, I have tried to accomplish this with {% crispy form form_helper.0 %}. I've also tried {% crispy form form_helper[0] %} but that doesn't work either.
python version 3.8.3
django version 3.1.2
views.py:
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse_lazy
from crispy_forms.utils import render_crispy_form
from .models import reference
from .forms import ReferenceForm
def ref_detail(request, ref_id):
try:
ref = reference.objects.get(pk=ref_id)
except ref.DoesNotExist:
raise Http404("Reference does not exist")
#If this is a POST request, process the form data
if request.method == 'POST':
#create a form instance and populate it with data from the request
form = ReferenceForm(request.POST)
#check whether it's valid
if form.is_valid():
#process the data in form.cleaned_data as required (i.e. save to database, etc.)
#...
print(form.cleaned_data)
new_reference = form.save() #save a new reference object to the database, from the form's data
#redirect to a new URL:
return HttpResponseRedirect('thanks/')
#if a GET (or any other method) we'll create a blank form
else:
form = ReferenceForm()
return render(request, 'test_cedar_app/ref_detail.html', {'ref': ref, 'form': form, 'form_helper': form.helper})
forms.py:
from django.forms import ModelForm
from django import forms
from test_cedar_app.models import factor, reference
from django.utils.translation import gettext_lazy as _
from crispy_forms.bootstrap import Tab, TabHolder, FormActions
from crispy_forms.helper import FormHelper
from crispy_forms.layout_slice import LayoutSlice
from crispy_forms.layout import Submit, Layout, Div
from crispy_forms.utils import render_crispy_form
class ReferenceForm(ModelForm):
class Meta:
model = reference
fields = '__all__'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_tag = False
self.helper.layout = Layout(
Div('study_title',
'name_author',
'publication_year',
'publisher',
'ident_doi',
'ident_pmid',
'exclude_extraction',
'exclude_extraction_reason',
css_id='main-tab-md',
css_class='tab-pane fade show active',
),
Div('study_design',
'study_design_detail',
'study_sample_method',
'ast_method',
'has_breakpoint',
'has_mic_table',
css_id='study-tab-md',
css_class='tab-pane fade',
),
)
ref_detail.html:
{% extends './base.html' %}
<!-- {% load static %} -->
{% load crispy_forms_tags %}
{% load widget_tweaks %}
{% block content %}
<form action="" method="post" id="leadform" enctype="multipart/form-data" role="form">
{% csrf_token %}
<ul class="nav nav-tabs md-tabs" id="myTabMD" role="tablist">
<li class="nav-item">
<a class="nav-link active" id="main-tab-md" data-toggle="tab" href="#main-md" role="tab" aria-controls="main-md"
aria-selected="true">Main</a>
</li>
<li class="nav-item">
<a class="nav-link" id="study-tab-md" data-toggle="tab" href="#study-md" role="tab" aria-controls="study-md"
aria-selected="false">Study Design</a>
</li>
<li class="nav-item">
<a class="nav-link" id="location-tab-md" data-toggle="tab" href="#location-md" role="tab" aria-controls="location-md"
aria-selected="false">Location</a>
</li>
<li class="nav-item">
<a class="nav-link" id="history-tab-md" data-toggle="tab" href="#history-md" role="tab" aria-controls="history-md"
aria-selected="false">History</a>
</li>
<li class="nav-item">
<a class="nav-link" id="notes-tab-md" data-toggle="tab" href="#notes-md" role="tab" aria-controls="notes-md"
aria-selected="false">Notes and Issues</a>
</li>
</ul>
<div class="tab-content card pt-5" id="myTabContentMD">
<div class="tab-pane fade show active" id="main-md" role="tabpanel" aria-labelledby="main-tab-md">
{% crispy form form_helper.0 %}
</div>
<div class="tab-pane fade" id="study-md" role="tabpanel" aria-labelledby="study-tab-md">
<p>Study</p>
</div>
<div class="tab-pane fade" id="location-md" role="tabpanel" aria-labelledby="location-tab-md">
<p>Location</p>
</div>
<div class="tab-pane fade" id="history-md" role="tabpanel" aria-labelledby="history-tab-md">
<p>History</p>
</div>
<div class="tab-pane fade" id="notes-md" role="tabpanel" aria-labelledby="notes-tab-md">
<p>Notes</p>
</div>
</div>
</form>
{% endblock %}
base.html:
{% load static %}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<title>Update a Reference</title>
<script src="http://code.jquery.com/jquery-1.9.1.js">
</script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js">
</script>
<script type="text/javascript" src="{% static 'bootstrap-tab.js' %}"> </script>
<!-- MDB icon -->
<link rel="icon" href="{% static 'img/mdb-favicon.ico' %}" type="image/x-icon">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.11.2/css/all.css">
<!-- Google Fonts Roboto -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap">
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
<!-- Material Design Bootstrap -->
<link rel="stylesheet" href="{% static 'css/mdb.min.css' %}">
<!-- Your custom styles (optional) - -->
</head>
<body>
<div class="container">
<div class="row justify-content-left">
<div class="col-8">
<h1 class="mt-2">{{ref.study_title}}</h1>
<hr class="mt-0 mb-4">
{% block content %}
{% endblock %}
</div>
</div>
</div>
<!-- SCRIPTS -->
<!-- jQuery -->
<script type="text/javascript" src="{% static 'js/jquery.min.js' %}"></script>
<!-- Bootstrap tooltips -->
<script type="text/javascript" src="{% static 'js/popper.min.js' %}"></script>
<!-- Bootstrap core JavaScript -->
<script type="text/javascript" src="{% static 'js/bootstrap.min.js' %}"></script>
<!-- MDB core JavaScript -->
<script type="text/javascript" src="{% static 'js/mdb.min.js' %}"></script>
<!-- MDBootstrap Datatables -->
<!-- <script type="text/javascript" src="{% static 'js/addons/datatables.min.js' %}"></script> -->
<!-- Your custom scripts (optional) -->
</body>
</html>
You could remove the layout object in your view. The last few lines would look like:
form = ReferenceForm()
form.helper.layout.pop(1)
return render(request, 'test_cedar_app/ref_detail.html', {'ref': ref, 'form': form})
And then display your form as you usually do:
{% crispy form %}
Here is my html file of landing page.
{% load static %}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="{% static 'css/base.css' %}">
</head>
<body>
<div class="center-column">
<form method="POST" action="/">
{% csrf_token %}
{{form.title}}
<input class="btn btn-info" type="submit" name="Create Task">
</form>
<div class="todo-list">
{% for task in tasks %}
<div class="item-row">
<a class="btn btn-sm btn-info" href="{% url 'update_task' task.id %}">Update</a>
<a class="btn btn-sm btn-danger" href="{% url 'delete' task.id %}">Delete</a>
{% if task.complete == True %}
<strike>{{task}}</strike>
{% else %}
<span>{{task}}</span>
{% endif %}
</div>
{% endfor %}
</div>
</div>
</body>
</html>
Here is Models.py file where a table is created
class Task(models.Model):
title = models.CharField(max_length=200)
complete = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
Error i am getting
OperationalError at /
no such table: tasks_task
C:\Users\91870\Desktop\Django\todo\tasks\templates\tasks\list.html, error at line 15
line 15 is
{% for task in tasks %}
here is views.py file
def index(request):
tasks = Task.objects.all()
form = TaskForm()
if request.method =='POST':
form = TaskForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
return render(request, 'tasks/list.html', {'tasks':tasks, 'form':form})
It was working when i haven't applied the css but now it isn't.
Can someone please help me with this
I am working on a hotel booking site , in which i give the user a option to upload their hotel in the site, In that i am interested in user to upload multiple images with out any particular limit, i wrote the model , the user successfully uploading the images but i am unable to store it in the database .
I got struck on this issue, i have searched everything on the web from the past one week , still not yet resolved, please help me on this issue .
Here is my model
hotel_rating_choices = (
('1','1'),
('2','2'),
('3','3'),
('4','4'),
('5','5'),
('6','6'),
('7','7'),
)
class Hotel(models.Model):
Hotel_Name = models.CharField(max_length=50)
location = models.CharField(max_length=20)
no_of_rooms = models.IntegerField()
rating = models.CharField(max_length=1, choices=hotel_rating_choices, default=3)
hotel_img = models.FileField(upload_to='hotel_images/')
uploaded_at = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True)
def __str__(self):
return self.Hotel_Name
Here is my form
class add_hotel(forms.ModelForm):
class Meta:
model = Hotel
fields = ('Hotel_Name', 'location', 'rating','no_of_rooms', 'user','hotel_img', )
# exclude = ['id']
widgets = {
'hotel_img' : forms.ClearableFileInput(attrs={'multiple': True})
}
Here is my view
class BasicUploadView(CreateView):
template_name = 'photos/basic_upload/index.html'
model = Hotel
form_class = add_hotel
success_url = reverse_lazy('home')
def get(self, request, *args, **kwargs):
form = add_hotel
return render(
self.request,
template_name = self.template_name,
context={'form' : form}
)
def post(self, request, *args, **kwargs):
import ipdb
ipdb.set_trace()
form = self.form_class(request.POST, request.FILES)
if form.is_valid():
photo = form.save()
data = {'is_valid': True, 'name':photo.hotel_img.name, 'url': photo.hotel_img.url}
return redirect('home')
else:
data = {'is_valid' : False}
return render(request, self.template_name, {'form': form})
Here is my template
{% load static from staticfiles %}
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Euphoria booking</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="author" content="" />
<!-- Icomoon Icon Fonts-->
<link rel="stylesheet" href="{% static 'css/icomoon.css' %}">
<!-- Theme style -->
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<link rel="stylesheet" href="{% static 'css/bootstrap.css' %}">
</head>
<body>
<div style="margin-bottom: 20px;">
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<table id="gallery" class="table table-bordered">
<tbody>
{% csrf_token %}
{% for field in form %}
<tr>
{{ field.errors }}
<td> {{ field.label_tag }}</td>
<td>{{ field }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<b>For uploading of more hotel photos</b>
<div align="center">
<button type="button" class="btn btn-primary js-upload-photos">
Upload photos
</button>
<input id="fileupload" type="file" name="hotel_img" multiple
style="display: none;"
data-url="{% url 'basic_upload' %}"
data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'>
</div>
<input type="submit" value="Submit" style="margin-left: 37%;" />
</form>
</div>
<div class="modal fade" id="modal-progress" data-backdrop="static" data- keyboard="false">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Uploading...</h4>
</div>
<div class="modal-body">
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: 0%;">0% </div>
</div>
</div>
</div>
</div>
</div>
{% block javascript %}
{# JQUERY FILE UPLOAD SCRIPTS #}
<script src="{% static 'js/jquery-file-upload/vendor/jquery.ui.widget.js' %}"></script>
<script src="{% static 'js/jquery-file-upload/jquery.iframe-transport.js' %}"></script>
<script src="{% static 'js/jquery-file-upload/jquery.fileupload.js' %}"></script>
<link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
{# PHOTOS PAGE SCRIPTS #}
<script src="{% static '/js/progress-bar-upload.js' %}"></script>
{% endblock %}
</div>
</body>
</html>
Ignore the progress bar , css stuff, i want to know why i am unable to store multiple images
Reference
I'm fairly new to Django and I'm trying to set up my project so that there's a homepage and then off of the homepage a bunch of different links. The problem is whenever I click one of my other tabs (products, login, contact) etc. it just reloads the homepages block content despite the fact that I told it to load something else. so when I click the links it does show that I'm on a new webpage (ill see whatever my BASE_DIR is with '/courses/products/' for example in the url bar but its always the same website which is displaying views.homepage.
Here's my courses/urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'$', views.homepage, name='homepage'),
url(r'contact/$', views.contact, name='contact'),
url(r'login/$', views.login, name='login'),
url(r'products/$', views.products, name='products'),
url(r'register/$', views.register, name='register'),
]
here's my layout.html which is in the template folder:
{% load static from staticfiles %}
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>HealthSmart</title>
<link href="{% static 'images/photo.jpg' %}" rel='icon' type='image/x-icon' />
<link rel="stylesheet" href="{% static 'css/normalize.css' %}" />
<link href="http://fonts.googleapis.com/css?family=Lora|Open+Sans:400italic,700italic,400,700,300,800" rel='stylesheet' type='text/css' />
<link href='http://fonts.googleapis.com/css?family=Varela+Round|' rel='stylesheet' type='text/css' />
<link rel="stylesheet" href="{% static 'css/pavle.css' %}" />
<link rel="stylesheet" href="{% static 'css/responsive.css' %}" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<header>
<a href="{% url 'courses:homepage' %}" id="logo">
<h1>{% block title %} {% endblock %}</h1>
</a>
<nav>
<ul>
<li>Home</li>
<li>Products</li>
<li>Contact</li>
<li>Login</li>
</ul>
</nav>
</header>
{% block content %} {% endblock %}
<div id="footer">
<footer>
<img src="{% static 'images/briggs.png' %}" alt="BriggsLogo" class="social-icon">
<p>©2015 HealthSmart Prototypes.</p>
</footer>
</div>
</body>
</html>
and finally, here's my views.py:
from django.shortcuts import get_object_or_404
from django.shortcuts import render
from .models import Owner, Device, Page
# Create your views here.
def homepage(request):
home = Page.objects.all()
return render(request, 'courses/homepage.html', {'homepage': homepage})
def contact(request, contact_pk):
contact = get_object_or_404(Page, pk=contact_pk)
return render(request, 'courses/contact.html', {'contact': contact})
def login(request, login_pk):
login = get_object_or_404(Page, pk=login_pk)
return render(request, 'courses/login.html', {'login': login})
def products(request, products_pk):
product = get_object_or_404(Page, pk=products_pk)
return render(request, 'courses/products.html', {'product': product})
def register(request, register_pk):
register = get_object_or_404(Page, pk=register_pk)
return render(request, 'courses/register.html', {'register': register})
Also I'll include the homepage.html and products.html just in case:
homepage.html:
{% extends "layout.html" %}
{% block title %}{{ page.title }}{% endblock %}
{% block content %}
<article>
<div class="main_body">
<div class="hep">
<section class="product">
<h3 id="purify">Purifying your life</h3>
<p id="smartprod">Meet our smart products today.</p>
</section>
</div>
</div>
<div id="information">
<h3>Change your Home Environment with the new Briggs HealthSmart Air Purifier and Humidifier</h3>
<p>Run multiple devices at the same time all on your smartphone!</p>
</div>
<div id="getStarted">
<p>If you have an account Login, or you can get started today and Register!</p>
</div>
</article>
{% endblock %}
products.html:
{% extends "layout.html" %}
{% block title %}{{ page.title }}{% endblock %}
{% block content %}
<article>
<div id="wrapper">
<section>
<ul id="gallery">
<li>
<a href="{% static 'images/air purifier 03272015.png' %}">
<img src="{% static 'images/air purifier 03272015.png' %}" alt="" />
<p>The Briggs Air Purifier.</p>
</a>
</li>
<li>
<a href="{% static 'images/base 03272015.png' %}">
<img src="{% static 'images/base 03272015.png' %}" alt="" />
<p>The Briggs Base.</p>
</a>
</li>
<li>
<a href="{% static 'images/humidifier 03272015.png' %}">
<img src="{% static 'images/humidifier 03272015.png' %}" alt="" />
<p>The Briggs Air Humidifier.</p>
</a>
</li>
<li>
<a href="{% static 'images/water tank 03272015.png' %}">
<img src="{% static 'images/water tank 03272015.png' %}" alt="" />
<p>The Briggs Water Tank.</p>
</a>
</li>
</ul>
</section>
</div>
</article>
{% endblock %}
use
url(r'^$', views.homepage, name='homepage'),
for your homepage, can you also show us how you extends your "layout.html" ?
For your contact problem you can add the pk in your url pattern
url(r'contact/(?P<contact_pk>\d+)/$', views.contact, name='contact'),