Trouble getting a html file to show in Django App - python

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.

Related

Routing for FormView Class

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.

Class views in Django, Html not showing

I'm confused with why my HTML template is not showing up.
I'm trying to learn Class base views instead of functions on Django.
I know the URL is working because {% extend base.html %} is showing, but anything else like the h1 tags aren't showing up in the render?
Can anyone help please.
views.py
from django.shortcuts import render
from django.views import View
from django.views.generic import (
CreateView,
DetailView,
ListView,
UpdateView,
ListView,
DeleteView
)
from .models import Article
class ArticleListView(ListView):
template_name = 'article/article_list.html'
queryset = Article.objects.all()
url.py
from django.contrib import admin
from django.urls import path
from .views import (
ArticleListView
)
app_name = 'article'
urlpatterns = [
path('', ArticleListView.as_view(), name = 'article_list'),
article_list.html
{%extends 'base.html'%}
<h1> Test </h1>
<h1> Test </h1>
{%block content%}
{% for instance in object_list %}
<p>{{instance.id}} - <a href = '{{instance.get_absolute_url}}'> {{instance.title}} </a></p>
{%endfor%}
{%endblock%}
[This is the outcome when i request get html, The current html is coming from base.html][1]
[1]: https://i.stack.imgur.com/W09EE.png
Use this code in the view:
context_object_name = 'article'
model = models. Article
And use this is in the template:
article. Id
{{article.get_absolute_url}}

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/

NoReverseMatch at Reverse for ... with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []

I am trying understand why I get the NoReverseMatch error when I use the User register form that I've created:
According to my situation, I reference the relevant files/information:
I have the main urls.py file named neurorehab/urls.py
from django.conf.urls import include, url, patterns
from django.conf import settings
from django.contrib import admin
from .views import home, home_files
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', home, name='home'),
url(r'^', include('userprofiles.urls')),
#Call the userprofiles/urls.py
url(r'^(?P<filename>(robots.txt)|(humans.txt))$', home_files, name='home-files'),
]
# Response the media files only in development environment
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$','django.views.static.serve',{'document_root': settings.MEDIA_ROOT,}),
)
I have the module/application named userprofiles, in which I have the userprofiles/urls.py file of this way:
from django.conf.urls import include, url, patterns
from .views import (ProfileView, LogoutView,
AccountRegistrationView, PasswordRecoveryView,
SettingsView)
from userprofiles.forms import CustomAuthenticationForm
urlpatterns = [
url(r'^accounts/profile/$', ProfileView.as_view(), name='profile/'),
# Url that I am using for this case
url(r'^register/$', AccountRegistrationView.as_view(), name='register'),
url(r'^login/$','django.contrib.auth.views.login', {
'authentication_form': CustomAuthenticationForm,
}, name='login',
),
url(r'^logout/$', LogoutView.as_view(), name='logout'),
]
The url register call to the CBV AccountRegistrationView located in the userprofiles/urls.py which is so:
from django.shortcuts import render
from django.contrib.auth import login, logout, get_user, authenticate
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext, loader
# Importing classes for LoginView form
from django.views.generic import FormView, TemplateView, RedirectView
from django.contrib.auth.forms import AuthenticationForm
from django.core.urlresolvers import reverse, reverse_lazy
from .mixins import LoginRequiredMixin
from .forms import UserCreateForm
class AccountRegistrationView(FormView):
template_name = 'signup.html'
form_class = UserCreateForm
# Is here in the success_url in where I use reverse_lazy and I get
# the NoReverseMatch
success_url = reverse_lazy('accounts/profile')
#success_url = '/accounts/profile'
# Override the form_valid method
def form_valid(self, form):
# get our saved user with form.save()
saved_user = form.save()
user = authenticate(username = saved_user.username,
password = form.cleaned_data['password1'])
# Login the user, then we authenticate it
login(self.request,user)
# redirect the user to the url home or profile
# Is here in the self.get_success_url in where I get
# the NoReverseMatch
return HttpResponseRedirect(self.get_success_url())
My form class UserCreateForm in which I made the registration form is located in userprofiles/forms.py file and it's so:
from django import forms
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.models import User
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
class UserCreateForm(UserCreationForm):
def __init__(self, *args, **kwargs):
super(UserCreateForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.add_input(Submit('submit', u'Save'))
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ('username','email','password1','password2',)
def save(self, commit=True):
user = super(UserCreateForm, self).save(commit=False)
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
And my template is the userprofiles/templates/signup.html file:
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block title %}Register{% endblock %}
{% block content %}
<div>
{% crispy form %}
{% csrf_token %}
</div>
{% endblock %}
When I go to my register user form, and I pressed submit this save my user and I have it for that try redirect to profile of the user recent created, but I get this error
What may be happening to me in this case. Seem that the reverse_lazy does not work?
Any help will be appreciated :)
The reverse_lazy() function either takes view function or url name to resolve it not the url path. So you need to call it as
success_url = reverse_lazy('profile/')
#---------------------------^ use url name
However, I'm not sure if '/' character works in url name.
If you have to use path to resolve to an url, use resolve() function.

Reverse for 'detail' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried:

A Django/Python newbie here. I am using python 3.4 and Django 1.7 version.
I am trying to get get my index page with hyperlinks to load and I see this issue.
My index.html (removed unwanted lines)
<form action="{% url 'testapp:search' %}" method="get">
{% csrf_token %}
Morphological
</form>
urls.py
from django.conf.urls import patterns, url
from testapp import views
urlpatterns = patterns('',
#url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^$', 'testapp.views.index', name='index'),
#url(r'^search-form/$', views.IndexView.as_view(), name='index'),
url(r'^search-form/$', 'testapp.views.index', name='index'),
#url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
#url(r'^option=(?P<option>\d+)/$', views.DetailView.as_view(), name='detail'),
url(r'^detail/(?P<val>\w+)/?$', 'testapp.views.detail', name='detail'),
#url(r'^search/$', views.search, name='search'),
url(r'^search/$', views.search, name='search'),
)
views.py
from django.shortcuts import render, get_object_or_404
from django.shortcuts import render_to_response
# Create your views here.
from django.http import HttpResponse, HttpResponseRedirect
#from polls.models import Question, Choice
from testapp.models import Molecular, Morphological
#from django.template import RequestContext, loader
from django.http import Http404
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.views import generic
def index(request):
return render_to_response('testapp/index.html', context_instance=RequestContext(request))
def search(request):
if 'q' in request.GET:
message = 'You searched for: %r' % request.GET['q']
else:
message = 'You submitted an empty form.'
return HttpResponse(message)
def detail(request, val):
message = 'hello form.'
return HttpResponse(message)
#class DetailView(generic.DetailView):
# model = Morphological
# template_name = 'testapp/detail.html'
I am trying to pass a parameter if the link is clicked and use that parameter to query the DB. I tried various things, & at this point I am stuck. I want a string and not the primary key, which I used in the standard polls application. Is it just my regular expression wrong?
Any help in fixing this would be of great help. Thanks.
Put single-quotes around the argument in the URL:
Morphological

Categories