I am trying to create a simple to-do list app using Django. But face this error will running the server ValueError: Field 'id' expected a number but got 'index.html'.
models.py
from django.db import models
class List(models.Model):
item = models.CharField(max_length=200)
completed = models.BooleanField(default=False)
def __str__(self):
return self.item + '|' + str(self.completed)
urls.py
from . import views
urlpatterns = [
path("index",views.index, name="home"),
path("delete/<list_id>/", views.delete , name="delete"),
]
views.py
from django.http import HttpResponse
from django.shortcuts import render, redirect
from .models import List
from .forms import ListForm
from django.contrib import messages
# Create your views here.
def index(request):
if request.method == 'POST':
form = ListForm(request.POST or None)
if form.is_valid():
form.save()
all_items = List.objects.all
messages.success(request,('Items has been Added to List !!'))
return render(request,'home.html', {'all_items': all_items})
else:
all_items = List.objects.all
return render(request,'index.html',{'all_items': all_items})
def delete(request, list_id):
item = List.objects.get(pk=list_id)
item.delete()
messages.success(request,('Item has been deleted'))
return redirect('index')
index.html
{% extends 'home.html' %}
{% block content %}
{% if messages %}
{% for message in messages %}
<div class="alert alert-warning alert-dismissable" role="alert">
<button class="close" data-dismiss="alert">
<small><sup>x</sup></small>
</button>
{{ message }}
</div>
{% endfor %}
{% endif %}
{% if all_items %}
<table class="table table-bordered">
{% for things in all_items %}
<tr>
<td>{{ things.item }}</td>
<td><center>{{ things.completed }}</center></td>
<td><center>Delete</center></td>
</tr>
{% endfor %}
</table>
{% endif %}
{% endblock content %}
home.html
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<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">
<title>Home</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="{% url 'home' %}">To-Do Lists</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
</ul>
<form class="form-inline my-2 my-lg-0" method="POST">
{% csrf_token %}
<input class="form-control mr-sm-2" type="search" placeholder="Add Items" aria-label="Search" name="item">
<button class="btn btn-outline-secondary my-2 my-sm-0" type="submit">Add To List</button>
</form>
</div>
</nav>
<br/>
<div class="container">
{% block content %}
{% endblock content %}
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
migration file 0001_intial.py
# Generated by Django 3.1.1 on 2020-09-27 05:07
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='List',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('item', models.CharField(max_length=200)),
('completed', models.BooleanField(default=False)),
],
),
]
here is my note app page
Error that I getting
can anybody tell me where I made the mistake?
thanks in advance
Try replacing "{% url 'delete' things.id %}" with "{% url '<appname>:delete' things.id %}" the appname should be replaced by your app name. The same format works for me in Django 2.x.
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>
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 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.
So, I've been trying to create a user login. When I click submit on my login form, I get this error:
Exception Type: TypeError
Exception Value: 'function' object is not iterable
Here's the full Traceback: http://dpaste.com/3D1B7MG
So, If I'm reading the Traceback correctly, the problem is in the {% extends "base.html" %} line of all_poss.html. So would that would mean the problem is actually inside base.html? or in the view that controls all_posts?
My all_posts.html
{% extends "base.html" %}
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style></style>
<title></title>
</head>
<body>
</body>
</html>
base.html
{% load staticfiles %}
{% load crispy_forms_tags %}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="{% static 'css/base.css' %}">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<TITLE>{% block title %}{% endblock %}</TITLE>
</HEAD>
<BODY>
{% block content %}
<div class="navbar-wrapper">
<div class="post_button" style="width:58px; margin:0 auto;">
Submit a Post
</div> <!-- /.post_button-->
<div class="log_bar">
<ul>
{% if user.is_authenticated %}
<li>Welcome,</li>
<li>{{ user.username }}</li>
<li>|</li>
<li>Log Out</li>
{% else %}
<li>Please</li>
<li><a data-toggle="modal" data-target="#modal-login" href="">log in</a></li>
<li>or</li>
<li><a data-toggle="modal" data-target="#modal-register" href="">sign up</a></li>
{% endif %}
</ul>
</div><!-- /.log_bar -->
<nav class="navbar navbar-fixed-left navbar-static-top">
<div class="container-fluid">
<!-- Collect the nav links, forms, and other content for toggling -->
<ul class="nav navbar-nav ">
<li class="active">Home <span class="sr-only">(current)</span></li>
<li>All</li>
<li>New</li
<li class="dropdown">
Top<span class="caret"></span>
<ul class="dropdown-menu">
<li>hour</li>
<li>24 hrs</li>
<li>week</li>
<li>month</li>
<li>year</li>
<li>beginning of time</li>
<li role="separator" class="divider"></li>
<li>Custom Search</li>
</ul>
</li>
</ul>
</div><!-- /.container-fluid -->
</nav>
<div id="side_bar">
<form class="navbar-form navbar-static-top navbar-right" role="search" id="navBarSearchForm">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search">
<span class="input-group-btn">
<button type="submit" class="btn btn-default" id="search_btn">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</form>
</div><!-- /.side-bar -->
<button class="btn-block" id='hideshow' value='hide/show' style="display: block; height: 100%;"></button>
{% include 'register.html' %}
{% include 'login.html' %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"> </script>
<script type="text/javascript" src="{{ STATIC_URL }} /static/jquery.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }} /static/jquery.leanModal.js"></script>
{% endblock %}
</BODY>
</HTML>
views.py
def login(request):
"""
Log in view
"""
if request.method == 'POST':
form = AuthenticationForm(data=request.POST)
if form.is_valid():
user = authenticate(username=request.POST['username'], password=request.POST['password'])
if user is not None:
if user.is_active:
django_login(request, user)
return render(request, 'all_posts.html', {'user': request.user})
else:
form = AuthenticationForm()
return render_to_response('login.html', {
'authenticationform': form,
}, context_instance=RequestContext(request))
def all_posts(request):
post_list = TextPost.objects.all().order_by('-score'))
paginator = Paginator(post_list, 100) # Show 100 contacts per page
registrationform = RegistrationForm(request.POST or None)
authenticationform = AuthenticationForm(request.POST or None)
page = request.GET.get('page')
try:
posts = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
posts = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
posts = paginator.page(paginator.num_pages)
return render(request, 'all_posts.html', {'posts': posts, 'registrationform': registrationform, 'authenticationform': authenticationform, 'user': request.user})
Edit 1: login.html login.html and register.html are identical modals, one with a login form and the other with the registration one.
{% load staticfiles %}
{% load crispy_forms_tags %}
<div class="modal" id="modal-login">
<div class="modal-dialog">
<div class="modal-content">
<form enctype="multipart/form-data" method="post" action="login/">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">Log In</h3>
</div>
<div class="modal-body">
{% csrf_token %}
{{ authenticationform|crispy }}
</div>
<div class="modal-footer">
<input type='submit' class="btn btn-primary" value="Log In" />
</div>
</form>
</div>
</div>
</div>
Edit 2: register.html
{% load staticfiles %}
{% load crispy_forms_tags %}
<div class="modal" id="modal-register">
<div class="modal-dialog">
<div class="modal-content">
<form enctype="multipart/form-data" method="post" action="register/">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">Register</h3>
</div>
<div class="modal-body">
{% csrf_token %}
{{ registrationform|crispy }}
</div>
<div class="modal-footer">
<input type='submit' class="btn btn-primary" value="Register" />
</div>
</form>
</div>
</div>
</div>
Alright, I was able to solve it.
The problem was apparently in my base.html where I had:
<li>{{ user.username }}</li>
and
<li>Log Out</li>
and I just changed the href="{% %}" tags to "profile/" and "logout/"
respectively.
I ran into this error while doing the Django tutorial.
The core problem was in my app's urls.py, in urlpatterns, with the second argument here:
path('', views.index, views.IndexView.as_view(), name='index'),
It should have been:
path('', views.IndexView.as_view(), name='index'),
Not sure how the extra views.index snuck in there but it was causing the problem. (as to why that exact error occurs - not going to dig too deep)
I believe this is preferable to deleting the {% url '...' id %} call and hard-coding its result as advised in the solution above.