Django - urls.py in project, and url.py in app - python

I'm trying to get a form action redirect to another page, however, I'm not too farmiliar with the Django framework. I went through the polls tutorial.
The current urls.py in my project is:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from WebApp import views
from StripCal import views
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^webapp/', include('WebApp.urls', namespace="WebApp")),
url(r'^stripcal/', include('StripCal.urls', namespace="StripCal")),
)
The url.py in my stripcal app is:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from StripCal import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^run', views.detail, name='detail'),
)
When I type in
http://127.0.0.1:8000/stripcal/
http://127.0.0.1:8000/webapp/
It successfully goes to two different apps. However, I'm not too familiar with {% url 'app_name:view_name' %} syntax. It seems like 'app_name:view_name' becomes /app_name/view_name
This is my current view:
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic
# Create your views here.
def index(request):
context = {'somethingDownByCelery': "heh"}
return render(request, 'StripCal/index.html', context)
def detail(request):
context = {'somethingDownByCelery': "heh"}
return render(request, 'StripCal/detail.html', context)
My Index.html
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'StripCal/index.css' %}"/>
<form action="{% url 'stripcal:detail'%}" method="post">
{% csrf_token %}
<p> StripCal Input </p>
<textarea name="StripCal_Input" cols="30" rows="10"> </textarea>
<br> <br>
<input type="submit" value="Submit">
</form>
My Detail.html
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'StripCal/detail.css' %}"/>
Hello Detail!
When I remove action={% url 'stripcal:detail' %} the webpage loads, however, when I put it in, the page does not even load (HTTP 500).

try to change:
StripCal.url.py
urlpatterns = patterns('StripCal.views',
url(r'^$', 'index', name='index'),
url(r'^run','detail', name='detail'),
)

Related

Django: Page not found , Raised by:django.views.static.serve

I am trying to display a static image in django. When I select image using django admin portal then it's works fine. it is displaying image. But when I select image from my front-end page, I get:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/media/destination-2.jpg
Raised by: django.views.static.server
Here are my codes:
urls.py
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from mainapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('mainapp.urls')),
]
admin.site.site_header = "Login to our web Portal"
admin.site.site_title = "This is Admin Portal"
admin.site.index_title = "Welcome to Amnet"
#urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
settings.py
STATICFILES_DIRS=[os.path.join(BASE_DIR,'static')
]
MEDIA_URL='/media/'
MEDIA_ROOT=os.path.join(BASE_DIR,'media')
models.py
from django.db import models
# Create your models here.
class Amnet(models.Model):
imagee = models.FileField(default='bg_2.jpg')
views.py
from django.shortcuts import render
from mainapp.models import Amnet
# Create your views here.
def index(request):
if(request.method == "POST"):
imagee= request.POST.get('imagee')
am = Amnet(imagee=imagee)
am.save()
return render(request,'image-main.html')
else:
return render(request,'image-main.html')
html page
<form action="" method="POST">
{% csrf_token %}
<td><input type="file" name="imagee" id="file"></td>
<td><img src="" id="profile-img-tag" width="200px" /></td>
</tr>
</table>
<input type="Submit" value="Submit" id="btn"><br>
</form>
Use enctype="multipart/form-data" to handle file uploads. Add this attribute in the form tag in HTML

accounts is not a registered namespace

in this django tutorial, we are creating a blogsite, at this pont we are creating a login form for users, unfortunately im getting and error saying that "accounts" is not a registered namespace, how do i fix this?
my urls.py file for the app "accounts":
from django.conf.urls import url
from.import views
appname= 'accounts'
urlpatterns=[
url(r'^signup/$', views.signup_view, name= "signup"),
url(r'^login/$', views.login_view, name = "login" ),
]
my views.py for the app:
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
def signup_view(request):
if request.method== 'POST':
form= UserCreationForm(request.POST)
if form.is_valid():
form.save()
#log the user in
return redirect('narticle:list')
else:
form=UserCreationForm()
return render (request,'accounts/accounts_signup.html', {'form': form})
def login_view(request):
if request.method == "POST":
form = AuthenticationForm(data= request.POST)
if form.is_valid():
return redirect('narticle:list')
else:
form = AuthenticationForm()
return render(request, 'accounts/login.html',{'form': form})
my base layout is:
{% load static from staticfiles %}
<!DOCTYPE html>
<html>
<head>
<title>Narticle</title>
<link rel="stylesheet" href="{%static 'styles.css'%}">
</head>
<body>
<div class="wrapper">
<h1> narticle </h1>
{% block content %}
{% endblock %}
</div>
</body>
</html>
the template for login is:
{% extends 'base_layout.html'%}
{%block content%}
<h1> log in</h1>
<form class="site-form" action="{% url 'accounts:login' %}" method="post">
{% csrf_token %}
{{form}}
<input type="submit" name="log_in" value="login">
</form>
{% endblock %}
these are my base urls:
from django.conf.urls import url, include
from django.contrib import admin
from. import views
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include ('accounts.urls')),
url(r'^narticle/', include ('narticle.urls')),
url(r'^about/$', views.about),
url(r'^$',views.homepage),
]
urlpatterns+= staticfiles_urlpatterns()
urlpatterns+= static(settings.MEDIA_URL, document_root= settings.
MEDIA_ROOT)
Believe it's because you missed the underscore:
from django.conf.urls import url
from.import views
# app_name not appname
app_name= 'accounts'
urlpatterns = [
url(r'^signup/$', views.signup_view, name= "signup"),
url(r'^login/$', views.login_view, name = "login" ),
]
You missed namespace in project urls.
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include ('accounts.urls', namespace='accounts')),
url(r'^narticle/', include ('narticle.urls')),
url(r'^about/$', views.about),
url(r'^$',views.homepage),
]

NoReverseMatch at /colorsets/new/ Reverse for 'user_logout' not found. 'user_logout' is not a valid view function or pattern name

I'm getting this error when trying to click on the "New Color Set" button:
NoReverseMatch at /colorsets/new/
Reverse for 'user_logout' not found. 'user_logout' is not a valid view function or pattern name.
I've looked extensively through StackOverflow and elsewhere on other sites and can't seem to find what the issue is. As far a I can tell all my code is right but clearly there is an issue.
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Colors</title>
<meta name"viewport" content="width=device-width, initial-scale=1">
<meta charset="uft-8">
<link rel="shortcut icon" href="/images/favicon.ico">
<link rel="stylesheet" href="/style.css">
</head>
<body>
<nav>
<div class="container">
<a class="btn" href="{% url 'index' %}">Home</a>
{% if user.is_authenticated %}
<a class="btn" href="{% url 'colorsets:new_color' %}">New Color Set</a>
<a class="btn" href="{% url 'accounts:user_logout' %}">Logout</a>
{% else %}
<a class="btn" href="{% url 'accounts:user_login' %}">Login</a>
<a class="btn" href="{% url 'accounts:register' %}">Register</a>
{% endif %}
</div>
</nav>
<div class="container">
{% block content %}
{% endblock %}
</div>
</body>
</html>
Views.py
from django.shortcuts import render
from accounts.forms import UserForm
from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
# Create your views here.
def user_login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username,password=password)
if user:
if user.is_active:
login(request,user)
return HttpResponseRedirect(reverse('index'))
else:
return HttpResponse("Account now active")
else:
print("Login Unsuccessful")
return HttpResponse("Your username and/or password are not correct")
else:
return render(request,'accounts/login.html',{})
def register(request):
registered = False
if request.method == 'POST':
user_form = UserForm(data=request.POST)
if user_form.is_valid():
user = user_form.save()
user.set_password(user.password)
registered = True
else:
print(user_form.errors)
else:
user_form = UserForm()
return render(request,'accounts/register.html',{'user_form':user_form,'registered':registered})
#login_required
def user_logout(request):
logout(request)
return HttpResponseRedirect(reverse('index'))
accounts app urls.py
from django.conf.urls import url
from accounts import views
app_name = 'accounts'
urlpatterns = [
url(r'^register/$',views.register,name='register'),
url(r'^login/$',views.user_login,name='user_login'),
url(r'^logout/',views.user_logout,name='user_logout'),
]
project urls.py
"""colors URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
from accounts import views
from colorsets import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$',views.index,name='index'),
url(r'^accounts/',include('accounts.urls',namespace='accounts')),
url(r'^colorsets/',include('colorsets.urls',namespace='colorsets')),
]
Let me know if you need to see anything else.
The problem is in the template under the url named new_color in your colorsets namespace. You definitely used it as {% url 'user_logout' %}, while you should use it like {% url 'accounts:user_logout' %}. Just add the namespace.
Check these two things in your project:
-In settings file you should have these two codes
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
-Must have a path in project's urls.py file (as shown below)
path('users/', include('django.contrib.auth.urls')),

Django urls.py not rendering correct template

This is my urls.py
"""s7h URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^articles/', include('article.urls')),
url(r'^',include('django.contrib.auth.urls')),
url(r'^projects/', include('project.urls')),
#Serve Media Files
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
#subscribe
url(r'^subscribe/$', 'article.views.subscribe'),
url(r'^verify/$', 'article.views.activateSubscriber'),
# user auth urls
url(r'^home/$', 's7h.views.home'),
url(r'^', 's7h.views.home'),
url(r'^accounts/login/$', 's7h.views.login'),
url(r'^accounts/auth/$', 's7h.views.auth_view'),
url(r'^accounts/logout/$', 's7h.views.logout'),
url(r'^accounts/loggedin/$', 's7h.views.loggedin'),
url(r'^accounts/invalid/$', 's7h.views.invalid_login'),
# user registration urls
url(r'^accounts/register/$', 's7h.views.register'),
url(r'^accounts/register_success/$', 's7h.views.register_success'),
url(r'^accounts/register_auth/$', 's7h.views.register_auth'),
url(r'^contact/$', 's7h.views.contact'),
]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
handler400 = 's7h.views.custom_400'
handler403 = 's7h.views.custom_403'
handler404 = 's7h.views.custom_404'
handler500 = 's7h.views.custom_500'
if not settings.DEBUG:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
This is my views.py
from django.shortcuts import render, render_to_response, RequestContext
from django.http import HttpResponseRedirect
from django.contrib import auth,messages
from django.core.context_processors import csrf
from django.template import RequestContext
from django.template.loader import get_template
from forms import MyRegistrationForm
from article.models import Article, ArticleCategory
from project.models import Project, ProjectCategory
def home(request):
args={}
article = Article.objects.earliest("-pub_date")
project = Project.objects.earliest("-pub_date")
article_category = ArticleCategory.objects.all()
project_category = ProjectCategory.objects.all()
args.update(csrf(request))
args['article'] = article
args['project'] = project
args['project_categories'] = project_category
args['article_categories'] = article_category
args['loggedin'] = request.session.get('email', None)
return render_to_response('home.html', args)
def login(request):
c = {}
c.update(csrf(request))
return render_to_response('login.html', c)
def auth_view(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
request.session['email'] = user.email
return render(request, "loggedin.html", locals(),context_instance=RequestContext(request))
else:
return HttpResponseRedirect('/accounts/invalid/')
def loggedin(request):
return render_to_response('loggedin.html', {})
def invalid_login(request):
return render_to_response('invalid_login.html')
def logout(request):
auth.logout(request)
return HttpResponseRedirect('/accounts/login/')
This is my template for login
{% extends "user_forms.html" %}
{% block title %}
S7H - Login
{% endblock %}
{% block main %}
<span class="fa fa-user bigicon"></span>
<h2>Enter Details</h2>
<form action = "/accounts/auth/" method = "POST">{% csrf_token %}
<p><input type="text" name="username" required placeholder="Username" autofocus></p>
<p><input type="password" name="password" required placeholder="Password"></p>
<button class="btn btn-default" type="submit" name="submit" />Sign In</button>
Sign Up
</form>
<small>Forgot your password?</small><br />
{% if messages %}
{% for message in messages %}
<small {% if message.tags %} class="{{message.tags}}" {% endif %}>{{message}}</small>
{% endfor %}
{% endif %}
{% endblock %}
Now when I do http://127.0.0.1:8000/accounts/login/ , Django should render login.html because url accounts/login/ leads me to def login(request): and there in render_to_response() I have mentioned login.html to get rendered but instead of it, Django renders my home.html file. URL of the browser changes to http://127.0.0.1:8000/accounts/login/ when I press the login button on my home page but it keeps on rendering the same home.html template.
This thing is happening with other urls also. Every url is rendering home.html template.
I double checked all my urls, views and templates, I have not been able to figure out my mistake. Django is also not giving any Exceptions and Error messages.
Also in the terminal the HTTP response is 200 OK :/
[08/Jun/2015 01:38:40]"GET /accounts/login/ HTTP/1.1" 200 10201
Help me!
Your s7h.views.home pattern has no terminating $ so it matches every URL.

why isn't this django url redirecting?

After getting post data from the following form, the page should redirect to 'associate:learn' as shown in the action. However, it just stays on the radio button page. I suspect I'm making a beginner's error but after rereading the tutorial, I'm not sure what's going on.
index.html
Choose a dataset
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'associate:learn' %}" method="post">
{% csrf_token %}
{% for dataset in datasets %}
<input type="radio" name="dataset" id="dataset{{ forloop.counter }}" value="{{ dataset.id }}" />
<label for="dataset{{ forloop.counter }}">{{ dataset }}</label><br />
{% endfor %}
<input type="submit" value="learn" />
</form>
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', "associate.views.index", name='index'),
url(r'^$', "associate.views.learn", name='learn'),
)
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^images/', include('images_app.urls', namespace="images_app")),
url(r'^associate/', include('associate.urls', namespace="associate")),
url(r'^admin/', include(admin.site.urls)),
)
views.py
def index(request):
images = Image.objects.all()
datasets = []
for i in images:
if i.rank() >= 3:
datasets.append(i)
return render(request, 'associate/index.html', {'datasets':datasets})
The original HTML should redirect to this page.
learn.html
THIS IS THE LEARN PAGE
Can you go to associate:learn directly?
In your first urls.py
urlpatterns = patterns('',
url(r'^$', "associate.views.index", name='index'),
url(r'^$', "associate.views.learn", name='learn'),
)
The url will always match "associate.views.index" since it appears before "associate.views.learn" and they both have the same url.
You should change it to something like:
urlpatterns = patterns('',
url(r'^$', "associate.views.index", name='index'),
url(r'^learn_or_something$', "associate.views.learn", name='learn'),
)
Hope this helps.
Your associate "index" and "learn" views both have the same URL. You need to have some way of distinguishing between them, otherwise the URL will always be served by the first one, which is index.

Categories

Resources