I'm making a web app in django and currently I'm facing this problem. I have a dashboard page and an upload page. There's a button in dashboard page which links to the upload page. but whenever I click the button then the upload page url appends the dashboard page.
below is the code:
views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from .models import Registration
from .forms import UploadForm
from django.urls import reverse
# Create your views here.
def homepage(request):
return render(request, 'index.html', {})
def dashboard(request):
posts = Registration.objects.all()
return render(request, "dashboard.html", {'posts': posts})
def upload(request):
form = UploadForm()
return render(request, "upload.html", {'form': form})
def uploadimage(request):
if request.method == 'POST':
form=UploadForm(request.FILES['image'], request.POST)
if form.is_valid():
pic = request.FILES['image']
desc = request.POST
post = Registration(pic='pic', desc='desc')
post.save()
urls.py
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
path('', views.homepage, name='homepage'),
path('dashboard/', views.dashboard, name='dashboard'),
path('upload/', views.upload, name='upload'),
path('create/', views.uploadimage, name='uploadimage'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
dashboard.html
<div class="profile">
<div class="left-s col s12 m3 l3">
<div class="profile-overview">
<img src="{%static 'images/group.jpg' %}" alt="profile-pic" class="circle responsive-img">
<p>Daljit Singh</p>
<p>Lorem ipsum dolor sit amet.</p>
</div>
<hr>
<div class="container">
<ul>
<li>About</li>
<li>Friends</li>
<li>Photos</li>
<li>Likes</li>
</ul>
</div>
<hr>
<button>Upload post</button>
</div>
error:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/dashboard/upload/
Using the URLconf defined in main.urls, Django tried these URL patterns, in this order:
[name='homepage']
dashboard/ [name='dashboard']
upload/ [name='upload']
create/ [name='uploadimage']
^media\/(?P<path>.*)$
The current path, dashboard/upload/, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
Help would be appreciated.
It should be - Upload post
If you enter '/' (/upload/) before the path it will append to the base URL and if '/' (upload/) doesn't exist then it will append to the existing path.
Or the Different way suggested in the comment -
Upload post
Related
So I am new to Django and I'm trying to create a HTML form (just following the tutorial for the name input) and I can input the name but can't direct to the /thanks.html page.
$ views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import NameForm
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
print(form)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/polls/thanks.html')
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
$ name.html
<html>
<form action="/polls/thanks.html" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
<html>
$ /mysite/urls
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
$ mysite/polls/urls.py
from django.urls import path
from polls import views
urlpatterns = [
path('', views.get_name, name='index'),
]
When I go to to the page, I can enter my name fine but then when I submit i get
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
polls/ [name='index']
admin/
The current path, polls/thanks.html, didn't match any of these.
Even though thanks.html is inside /polls
Sorry if the fix is super easy I just haven't used Django before.
Thanks :)
Create a view called thanks in views.py
def thanks(request):
return render(request, 'thanks.html')
Now, Link the /poll/thanks/ url to the thanks template by adding path('thanks/', views.thanks, name='thanks') to your urls.py of the polls app.
$ mysite/polls/urls.py
from django.urls import path
from polls import views
urlpatterns = [
path('thanks/', views.thanks, name='thanks'),
]
Finally change the following line in your get_name view
return HttpResponseRedirect('/polls/thanks/')
Change your main urls.py:
url(r'^polls/', include('polls.urls')),
And in your app's urls.py:
url(r'^$', views.get_name, name='index'),
And in your views.py change to:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return render(request, 'thanks.html')
Hello, Everyone
I'm a novice programmer trying to follow Antonio Mele tutorial on blog creation using django.
Am stuck with the post/detail.html which is not responding
below are the codes.Kindly help.
Problem: Am unable to view details of the post
404 Error: Page not found
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/blog/2020/3/13/more-post/
Raised by: blog.views.post_detail
No Post matches the given query.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
Error:Page not found
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
1.admin/
2.blog/
The empty path didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.*
urls.py/blog
urls.py/mysite
views.py
urls.py/blog
from django.urls import path
from . import views
app_name = 'blog'
urlspatterns = [
path('', views.post_list, name='post_list'),
path('<int:year>/<int:month>/<int:day>/<slug:post>/',
views.post_detail,
name='post_detail'),
]
urls.py/mysite
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include('blog.urls', namespace='blog')),
]
views.py
from django.shortcuts import render, get_object_or_404
from .models import Post
def post_list(request):
posts = Post.objects.all()
return render(request,
'blog/post/list.html',
{'posts':posts})
def post_detail(request, year, month, day, post):
post = get_object_or_404(Post, slug=post,
status='published',
publish__year=year,
publish__month=month,
publish__day=day)
return render(request,
'blog/post/detail.html',
{'post': post})
Someone had the same problem with the previous version of the book, asked here and published his solution (there must be a much more elegant way), have a look here:
Django get_object_or_404() with DateTimeField
In addition, use the shell to debug items, you should have seen that the date in DB is recorded in UTC:
>>> post = Post.objects.get(title__startswith='who')
>>> post.publish
datetime.datetime(2020, 8, 18, 1, 18, 56, tzinfo=<UTC>)
Take a look at the admin area, where the articles have a 'draft' status. Change them to 'published' status. In the views.py in the function post_list(), change the output of posts on a page with only the status published:
def post_list(request):
posts = Post.objects.filter(status='published')
return render(request, 'blog/post/list.html', {'posts': posts})
In this case, articles with only the status published are displayed on the posts page. By clicking on the article link, you should be transferred to a full post without error.
#FOLLOW THIS PROCEDURE.I HOPE IT HELPS YOU OR ANY ONE ELSE IN THE FUTURE
#blog/models.py
from django.db import models
from django.utils import timezone
class Post(models.Model):
published = models.BooleanField(True)
created_on = models.DateTimeField(auto_now=timezone.now)
# At blog/urls.py
from django.urls import path
from .views import (post_list, post_detail)
urlspatterns = [
path('', post_list, name='post_list'),
path('<str:slug>/', post_detail, name='post_detail'),
#At mysite/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include('blog.urls')),
#At blog/views.py
from django.shortcuts import render, get_object_or_404
from .models import Post
def post_list(request):
posts = Post.objects.filter(published)
template_name = blog/post_list.html
context = {'posts':posts}
return render(request, template_name, context)
def post_detail(request, slug):
posts = get_object_or_404(Post, slug=slug)
template_name = blog/post_detail.html
context = {'posts':posts}
return render(request, template_name, context)
# At the template/blog/post_list.html
{% block content %}
{% for post in posts %}
<article>
<div>
<small>{{ post.created_on|date:"F d, Y" }}</small>
<h2>{{ post.title }}</h2>
<p >{{ post.body }}</p>
</div>
</article>
{% endfor %}
{% endblock content %}
# At template/blog/post_detail.html
<article>
<div>
<small>{{ posts.created_on|date:"F d, Y" }}</small>
<h2>{{ posts.title }}</h2>
<p>{{ posts.body }}</p>
</div>
</article>
#The above code should fix the the issue properly.
I'm trying to import a simple single-field form in Django, and I have gone through plenty of Tutorial Videos on YouTube describing the same. Yet, I'm unable to render the simple form on my web-app. I'm pretty sure I'm doing something really stupid that is still oblivious to me.
I'll also post in the folder structure so you can suggest if I'm defining the class/function in the wrong views.py file.
The appropriate source codes are as follows:
earthquake/views.py File
from django.shortcuts import render
from earthquake.forms import HomeForm
from django.views.generic import TemplateView
class HomeView(TemplateView):
template_name = 'earthquake/home.html'
def get(self, request, *args, **kwargs):
form1 = HomeForm()
argf = {
'myform': form1
}
return render(request, self.template_name, argf)
forms.py
from django import forms
class HomeForm(forms.Form):
post = forms.CharField()
home.html (snippet)
<div class="container">
<div class="jumbotron">
<h1>Query Form</h1>
<p>Please Enter the parameters you want to query against the USGS Earthquake DB</p>
<div class="container">
<form class="" method="post" action="">
{% csrf_token %}
{{ myform }}
<button type="submit" class="btn btn-success">Search</button>
</form>
</div>
</div>
</div>
Django Project urls (interview.py/urls.py)
from django.contrib import admin
from django.urls import path, include
from interview.views import login_redirect
from interview import views
from django.contrib.auth.views import LoginView
from django.contrib.auth.views import LogoutView
urlpatterns = [
path('', login_redirect, name='login_redirect'),
path('admin/', admin.site.urls),
path('home/', include('earthquake.urls')),
path('login/', LoginView.as_view(template_name='earthquake/login.html'), name="login"),
path('logout/', LogoutView.as_view(template_name='earthquake/logout.html'), name="logout"),
path('register/', views.register, name='register'),
]
App URLS (interview/earthquake/urls.py)
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
Folder Structure
https://i.stack.imgur.com/zoehT.jpg
(In case you're unable to see the last entry in the image, it's the main views.py present in the project folder).
The following is the snapshot of the render I currently get:
https://i.stack.imgur.com/kXR7W.jpg
I see that in your home views file your class based view is called
HomeView(TemplateView)
Yet in your app urls you are including the view as view.home when it should be
view.HomeView
to add to that, this is a classed based view so your urls page for that should look like:
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.home.as_view(), name='home'),
]
Since this is a class based view.
Have the following problem; I am following Django by Example, Antonio Mele.The exercise here, is to set up user login and logout.Using the default contrib.auth views. When the code in the book is used. The logout view is that of the admin page logout; seems to be same issue as described here
django logout redirects me to administration page. Have tried all there no success
I have been working on this problem. My code now works, in that the admin template is no longer rendered. However, I am still unable to use my own logout.html. I can redirect to my own login.html... but not the logout.html.The logging out itself is working. User can log in, and out only this issue with the templates. I now only receive one browser error
The page isn't redirecting properly Iceweasel has detected that the >server is redirecting the request for this address in a way that will >never complete.This problem can sometimes be caused by disabling or >refusing to accept cookies.
checked the cookies can see csrf token is accepted
no traceback available no errors :-(
If I use the code below , all works with one exception. I am redirected at logout to the Django Administration logout template, and not my own logout.html....This is when using coede in the book.... My own modified code, with a seperate logout function also did not work generating a maximum recurson error.Editing the URLS.PY stops the rendering of the admin template. but the modified code seems to have an issue in the urls i.e .....
THIS IS NOT WORKING !!!!!
url(r'^logout/$', 'django.contrib.auth.views.logout',{'next_page': '/account/logout'}, name='logout'),
THIS WORKS PERFECTLY !!!!
url(r'^logout/$', 'django.contrib.auth.views.logout',{'next_page': '/account/login'}, name='logout'),
The code from the book is as follows
FROM BOOK SETTINGS.PY
from django.core.urlresolvers import reverse_lazy
LOGIN_REDIRECT_URL = reverse_lazy('dashboard')
LOGIN_URL = reverse_lazy('login')
LOGOUT_URL = reverse_lazy('logout')
FROM BOOK VIEWS.PY
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .forms import LoginForm
#login_required
def dashboard(request):
return render(request, 'account/dashboard.html', {'section': 'dashboard'})
def user_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = authenticate(username=cd['username'], password=cd['password'])
if user is not None:
if user.is_active:
login(request, user)
return HttpResponse('Authenticated successfully')
else:
return HttpResponse('Disabled account')
else:
return HttpResponse('Invalid login')
else:
form = LoginForm()
return render(request, 'account/login.html', {'form': form})
FROM BOOK MAIN URLS.PY
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^account/', include('account.urls')),
]
MYAPP(account) URLS.PY
from django.conf.urls import url
from . import views
urlpatterns = [
# url(r'^login/$', views.user_login, name='login'),
url(r'^$', views.dashboard, name='dashboard'),
# login / logout urls
url(r'^login/$', 'django.contrib.auth.views.login', name='login'),
url(r'^logout/$', 'django.contrib.auth.views.logout', name='logout'),
url(r'^logout-then-login/$', 'django.contrib.auth.views.logout_then_login', name='logout_then_login'),
MY MODIFIFED CODE
I have now include a seperate logout definition in my view's and now also pass a {key:value} pair of {'next_page': '/account/logout'}.
if the logout def is used and mapped in the urls file it generates a maximum recursion error at line logout(request)
def logout(request):
logout(request)
request.session.flush()
request.user = AnonymousUser
# Redirect to a success page.
return HttpResponseRedirect(request,'/account/logout.html',context_instance = RequestContext(request))
without this def the only error generated is
"""
The page isn't redirecting properly
"""Iceweasel has detected that the server is redirecting the request for this address in a way that will never complete.
This problem can sometimes be caused by disabling or refusing to accept cookies.""""
"""
I checked cookies in the browser, and see the csrf_token being accepted
For me the strange thing is that if the code: {'next_page': '/account/logout'} is changed to {'next_page': '/account/login'} everything works perfectly. Have tried all suggestions found, am at a loss any help appreciated ....
MY CODE
VIEWS.PY
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import authenticate, login, logout
from .forms import LoginForm
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from django.contrib.auth.models import User
# Create your views here.
#login_required
def dashboard(request):
return render(request, 'account/dashboard.html',{'section': 'dashboard' })
def user_login(request):
cd = None
if request.method=='POST':
form = LoginForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = authenticate(username=cd['username'],
password=cd['password'])
if user is not None:
if user.is_active:
login(request, user)
return HttpResponse('Authenticated successfully')
else:
return HttpResponse('Disabled Account')
else:
return HttpResponse('Invalid Login')
else:
form = LoginForm()
return render(request, 'account/login.html',{'form': form},context_instance = RequestContext(request))
def logout(request):
logout(request)
request.session.flush()
request.user = AnonymousUser
# Redirect to a success page.
return HttpResponseRedirect(request,'/account/logout.html',context_instance = RequestContext(request))
MY CODE
account/urls.py
from django.conf.urls import url, patterns
from . import views
urlpatterns = [
# post views
#url(r'^login/$', views.user_login, name='login'),
# login/logout urls
url(r'^$', views.dashboard, name='dashboard'),
url(r'^login/$', 'django.contrib.auth.views.login', name='login'),
url(r'^logout/$', 'django.contrib.auth.views.logout',{'next_page': '/account/logout'}, name='logout'),
url(r'^logout-then-login/$','django.contrib.auth.views.logout_then_login', name='logout_then_login'),
]
MY CODE
MAIN URLS.PY
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^account/', include("account.urls")),
]
MYCODE
SETTINGS.PY
LOGIN_REDIRECT_URL = reverse_lazy('dashboard')
LOGIN_URL = reverse_lazy('login')
LOGOUT_URL = reverse_lazy('logout')
INSTALLED_APPS = (
'account',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
# urlpatterns += patterns('django.contrib.auth.views',
# #url(r'^login/$', 'login', { 'template_name': 'registration/login.html'}, name='login' ),
# #url(r'^logout/$', 'logout', { 'template_name': 'registration/logout.html', 'next_page':reverse('index') }, name='logout' ),
# )
MYCODE
logout.html
{% extends "base1.html" %}
{% block title %}Logged Out{% endblock %}
{% block content %}
<h1>
Logged Out
</h1>
<p>
You have been successfully logged out. You can Log-in again
</p>{% endblock %}
MYCODE
base1.html
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" type="text/css" href="{% static 'css/base.css' %}">
</head>
<body>
<div id="header">
<span class="logo">
BookMarks
</span>
{% if user.is_authenticated %}
<ul class="menu">
<li {% if section == "dashboard" %}class="selected"{% endif %}>
My dashboard
</li>
<li {% if section == "images" %}class="selected"{% endif %}>
Images
</li>
<li {% if section == "people" %}class="selected"{% endif %}>
People
</li>
</ul>
{% endif %}
{%if user.is_authenticated %}
<span class="user">
Hello {{ user.first_name }} {{ user.last_name }},
Logout
{% else %}
<a href='{% url "login" %}'>Log-in</a>
{% endif %}
</span>
</div>
<div id="content">
{% block content %}
{% endblock %}
</div>
</body>
</html>
I was having same issue, but then I kept reading
"If you are seeing the log out page of the Django administration site instead of your own log out page, check the INSTALLED_APPS setting of your project and make sure that django.contrib.admin comes after the account application. Both templates are located in the same relative path and the Django template loader will use the first one it finds."
You are using contrib.auth's logout view in your urls.py. This view redirects to the URL specified by 'next_page'. You provide '/account/logout' as next_page -- where again the logout view is called!
That leads to an (infinite) redirect loop: the view redirects to itself.
Try instead: in your own logout view:
# no redirecting here!
return render(request, 'account/logout.html',
context_instance=RequestContext(request))
Add a url for that view in account/urls.py:
url(r'^post-logout/$', logout, name='post-logout'),
# logout being your own view
Then provide that url as 'next_page' to the actual (auth) logout:
url(r'^logout/$', 'django.contrib.auth.views.logout',
{'next_page': '/account/post-logout'}, name='logout'),
The solution to the problem is to map the url as follows
url(r'^logout/$', 'django.contrib.auth.views.logout', { 'template_name': 'account/logout.html',}, name='logout' ),
I am new to Django 1.9 and I am currently coding a website. I am trying to make a contact form to go on the contact page. I have used the following code - which is in the a file called email.html:
{% extends 'blog/base.html' %}
<form method="post">
{% csrf_token %}
{{ form }}
<div class="form-actions">
<button type="submit">Send</button>
</div>
</form>
I've defined it in the view.py file:
from .forms import PostForm, ContactForm
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
def email(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
try:
send_mail(subject, message, from_email, ['nmam.ltd#gmail.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('thanks')
return render(request, "blog/email.html", {'form': form})
def thanks(request):
return HttpResponse('Thank you for your message.')
.....
As well as in the forms.py file:
from django import forms
class ContactForm(forms.Form):
from_email = forms.EmailField(required=True)
subject = forms.CharField(required=True)
message = forms.CharField(widget=forms.Textarea)
Also, in the urls.py file:
from django.conf.urls import patterns, url
from . import views
urlpatterns = [
url(r'^general.html/$', views.general, name='general'),
url(r'^dcmain.html/$', views.dcmain, name='dcmain'),
url(r'^dcmain.html/big_data.html/$', views.big_data, name='big_data'),
url(r'^dcmain.html/Data_Architecture.html/$', views.Data_Architecture, name='Data_Architecture'),
url(r'^dcmain.html/BI_MI.html/$', views.BI_MI, name='BI_MI'),
url(r'^dcmain.html/Master_Data.html/$', views.Master_Data, name='Master_Data'),
url(r'^dcmain.html/Data_Q.html/$', views.Data_Q, name='Data_Q'),
url(r'^dcmain.html/Project_M.html/$', views.Project_M, name='Project_M'),
url(r'^email.html/$', views.email, name='email'),
url(r'^thanks/$', views.thanks, name='thanks'),
]
When I link the email.html file to the main page and click on the link and it just shows the home page even though the url says I am on the email.html page (shown below):
I am totally new to programming in Django. I have tried researching it however, I can't find a solution. Please can someone help me.
Your URLs are most likely the problem. You can read more on Django URLs here.
Note, as the Django docs mention, the first URL pattern which matches the requested URL will be used. As a basic rule of thumb, I recommend putting your more specific URL patterns before your blank url patterns. For instance:
urlpatterns = [
url(r'^email.html/$', views.email, name='email'),
url(r'^thanks/$', views.thanks, name='thanks'),
url(r'^$', views.index, name='some_name'),
]
If this urls.py file is being included from a project urls.py file, you'll want these urls to be included before your root url pattern.
urlpatterns = [
url(r'^blog/', include('blog.urls', namespace='blog'),
url(r'', views.site_home, name='site_home'),
]
Which would then make your url to this page
Email
Which would render as
Email