Routing for FormView Class - python

I have django_test project and defapp application in it.
I want to access form.html which MyView makes,
I am still confused about routing.
I can access localhost/defapp/ and show Hello, World
However how can I access the MyView class and show form.html?
in django_test/urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import include,url
urlpatterns = [
path('defapp/', include('defapp.urls')),
url(r'^s3direct/', include('s3direct.urls')),
path('admin/', admin.site.urls),
]
in defapp/views.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index')
]
in defapp/views.py
from django.shortcuts import render
# Create your views here.
from django.views.generic import FormView
from .forms import S3DirectUploadForm
def index(request):
return HttpResponse("Hello, world.")
class MyView(FormView):
template_name = 'form.html'
form_class = S3DirectUploadForm
in defapp/template/form.html
<html>
<head>
<meta charset="utf-8">
<title>s3direct</title>
{{ form.media }}
</head>
<body>
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
</form>
</body>
</html>

If you're looking to know how to wire up a class based view in the urlconf, please checkout these docs on class based views.
The most direct way to use generic views is to create them directly in your URLconf. If you’re only changing a few attributes on a class-based view, you can pass them into the as_view() method call itself:
from django.urls import path
from django.views.generic import TemplateView
urlpatterns = [
path('about/', TemplateView.as_view(template_name="about.html")),
]
Additionally, the docs on as_view may prove helpful.

Related

Django Create multiple views

I am new to Django. I have to create multiple views and create buttons for them in the main page. I have created different view for different filters of the table. I now have to create buttons in main page to redirect to different views . Can't figure the changes in urls.py and templates.
here is my code :
views.py
from django_tables2 import SingleTableView
from django.db.models import Max
from django.db.models import Min
from .models import airdata
from .tables import AirdataTable
class AirdataListView(SingleTableView):
model = airdata
table_class = AirdataTable
template_name = 'dashboard/data.html'
q = airdata.objects.aggregate(alpha=Min('pol_max'))['alpha']
queryset = airdata.objects.filter(pol_min= q).order_by('-state')
class AirdataListView2(SingleTableView):
model = airdata
table_class = AirdataTable
template_name = 'dashboard/data2.html'
q = airdata.objects.aggregate(alpha=Max('pol_max'))['alpha']
queryset = airdata.objects.filter(pol_min= q).order_by('-state')
app/urls.py
from django.urls import path
from . import views
from .views import AirdataListView,AirdataListView2
urlpatterns = [
path('page1/', AirdataListView2.as_view()),
path('page2/', AirdataListView.as_view()),
]
project/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('dashboard/', include('dashboard.urls')),
path('admin/', admin.site.urls),
]
template
{% load render_table from django_tables2 %}
<!doctype html>
<html>
<head>
<title>Air Data</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
</head>
<body>
{% render_table table %}
</body>
</html>
Django will try to match the given url with one of the paths defined in urls.py.
In your case, you have two views that match the empty pattern, so Django is returning the first match and you wont be able to access your second pattern.
Try this on your urls.py:
urlpatterns = [
path('page1/', AirdataListView2.as_view()),
path('page2/', AirdataListView.as_view()),
]
Chances are you will eventually want to do more complex stuff and pass parameters into your urls so perhaps its a good idea to check the docs for more info about them.
Sure, as Django will run the first view match the url pattern which is the first one in your case. The problem you are handling can be solved by GET parameters. So read about it.

Django Teamplate Error name 'Post_title' is not defined

I'm trying to render index HTML and get post title from database but I'm getting error. I define in views post database but still getting error
name 'Post_title' is not defined
my app/views.py
from django.shortcuts import render, get_object_or_404
from django.shortcuts import reverse
from .models import BlogPost,comments
def index(request):
Post_list = BlogPost.objects.all()
template_name = 'front/index.html'
return render(request, template_name,{Post_title:"Post_title",})
def post_detail(request):
return render(request, 'front/post_detail.html')
my app/urls.py
from django.urls import path
from .import views
urlpatterns = [
path('', views.index, name = 'index'),
path('<int:BlogPost_id>/', views.post_detail, name='Post Detail')
]
my project/urls.py
from django.contrib import admin
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
from froala_editor import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
path('froala_editor/', include('froala_editor.urls'))
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
my index.html template
<div class="col-md-8 mt-3 left">
{% for post in Post_list %}
<div class="card mb-4">
<div class="card-body">
<h2 class="card-title">{{ post.Post_title }}</h2>
</div>
</div>
{% endfor %}
</div>
You are not sending the Post_list to the template through context. Send it like this
return render(request, template_name, {'Post_list':Post_list})

I get page not found (404) error when going to "http://127.0.0.1:8000/restaurant/sign-in/" page

When I go to "http://127.0.0.1:8000/restaurant/sign-in/" I get page not found (404) error. But I can go to "http://127.0.0.1:8000/restaurant/$" to access the home page.
I also tried "http://127.0.0.1:8000/restaurant/sign-in/$" but this also gives me error (init() takes 1 positional argument but 2 were given).
My urls.py is
from django.contrib import admin
from django.urls import path
from foodtaskerapp import views
from django.contrib.auth import views as auth_views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home, name='home'),
path('restaurant/sign-in/$', auth_views.LoginView,
{'template_name': 'restaurant/sign_in.html'},
name='restaurant-sign-in'),
path('restaurant/sign-out', auth_views.LogoutView,
{'next_page': '/'},
name='restaurant-sign-out'),
path('restaurant/$', views.restaurant_home, name='restaurant-
home'),
]
And my views.py is
from django.shortcuts import render, redirect
def home(request):
return redirect(restaurant_home)
def restaurant_home(request):
return render(request, 'restaurant/home.html', {})
here is the screenshot of the error
I also have
<body>
<form method="POST">
{% csrf_token %}
{{ form }}
<button type="submit">Sign In</button>
</form>
</body>
in sign_in.html but the form don't show up, only Sign In is shown.
only sign is shown but not the form
the syntax for the function you are using has changed in the latest version of django, which is why you got that error (the code you are sharing is in a tutorial made by code4startups which uses an older version of django).
You should modify your path command to:
path('restaurant/sign-in/', auth_views.LoginView.as_view(
template_name='restaurant/sign_in.html'),
name='restaurant-sign-in'),
You have no corresponding function in views.py:
auth_views.LoginView
Also, i guess, you neither have 'restaurant/sign_in.html', so it doesn't redirect to the page.
Add this in views.py:
def restaurant_signIn(request):
return render(request, 'restaurant/sign_in.html')
And corresponding HTML page name: 'sign_in.html',in restaurant directory:
<p>SigninWorks</p>
Your urls.py must look like:
from django.contrib import admin
from django.urls import path
from foodtaskerapp import views
from django.contrib.auth import views as auth_views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home, name='home'),
path('restaurant/sign-in/', views.restaurant_signIn,
name='restaurant-sign-in'),
path('restaurant/$', views.restaurant_home, name='restaurant-
home'),
]

NoReverseMatch at /polls/top/ 'polls' is not a registered namespace

Parent app name is mysite,child app name is polls.
I wrote in views.py
from django.shortcuts import render
from .models import Polls
def top(request):
data = Polls.objects.order_by('-created_at')
return render(request,'index.html',{'data':data})
def detail(request):
data = Polls.objects.order_by('-created_at')
return render(request,'detail.html',{'data':data})
in child app's urls.py
from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns=[
url('top/', views.top, name='top'),
url('detail/<int:pk>/', views.top,name='detail'),
]
in parent app's urls.py
from django.contrib import admin
from django.conf.urls import url,include
app_name = 'polls'
urlpatterns = [
url('admin/', admin.site.urls),
url('polls/', include('polls.urls')),
]
in index.html
<main>
{% for item in data %}
<h2>{{ item.title }}</h2>
<a href="{% url 'polls:detail' item.pk %}">SHOW DETAIL
</a>
{% endfor %}
</main>
When I access top method, NoReverseMatch at /polls/top/
'polls' is not a registered namespace error happens.I am using Django 2.0,so I think namespace cannot used.I wrote app_name ,so I really cannot understand why this error happens.How should I fix this?What is wrong in my code?
The var app_name should be inside polls.urls not in the urls.py parent's file. Also if you want to use the new routing that Django provides remember add the path module:
from django.urls import path
path('detail/<int:pk>/', views.top,name='detail'),
If you're using the url module check this and be careful with what version you're using https://docs.djangoproject.com/en/2.0/topics/http/urls/

Trouble getting a html file to show in Django App

In my views.py file I have this currently
from django.contrib import messages
from django.http import HttpResponse
from django.core.urlresolvers import reverse
from django.shortcuts import redirect, get_object_or_404, render
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.views.generic.base import View, TemplateView
from models import *
from forms import *
class test(TemplateView):
def test(request):
return HttpResponse("test")
def get_template_names(self):
return ["myapp/test.html"]
urls.py
from django.conf.urls import patterns, url
from views import test
urlpatterns = patterns('',
url(r'$', test.as_view(), name='test'),
)
test.html
{% extends "index.html" %}
{% block content %}
<P> HELLO </P>
{% endblock %}
Except nothing shows up when the site loads up!
The index.html file loads fine as the html file i am loading up is extending that. But as I click the button that is connected to the url 'test' in urls.py nothing updates. The text.html file just has the text "hello world".
In your urls.py, you need to properly import your view:
from django.conf.urls import patterns, url
from yourapp.views import test
urlpatterns = patterns('',
url(r'$', test.as_view(), name='test'),
)
In your views, you need to fix your class, thus:
class test(TemplateView):
template_name = 'myapp/test.html'
You should not use get_template_names
If this is really all you are trying to do (that is, render a template), then you can import TemplateView directly in your urls.py:
from django.conf.urls import patterns, url
# from yourapp.views import test
from django.views.generic.base import TemplateView
urlpatterns = patterns('',
url(r'$', TemplateView.as_view(template_name='myapp/test.html'), name='test'),
)
Try writing your view like this:
class Test(TemplateView):
template_name = "myapp/test.html"
This is the recommended way to set the template name.

Categories