Django (Python) : Django form is not Displaying - python

I am making my way into Python and Django programming. However, I struggle with displaying a simple form.
The only element displayed based on the code below is the button, but not (as intended) the entire form. I have already checked the indentation of my code, but have not been able to display the form.
models.py
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class Story (models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
audio = models.FileField(default='SOME STRING', upload_to='audio_stories')
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('story-detail', kwargs={'pk': self.pk})
forms.py
from django import forms
from .models import Story
class Story_Creation(forms.ModelForm):
class Meta:
model = Story
fields = ['title','content','audio']
views.py
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.models import User
from .models import Story
from .forms import Story_Creation
from django.contrib.auth.mixins import (
LoginRequiredMixin,
UserPassesTestMixin
)
from django.views.generic import (
ListView,
DetailView,
CreateView,
UpdateView,
DeleteView
)
def Create_Audio_Story(request):
if request.method == 'POST':
s_form = Story_Creation(request.POST, request.FILES)
if s_form.is_valid():
s_form.save()
return redirect('suyuh-home')
else:
s_form = Story_Creation()
context = {
's_form': s_form,
}
return render (request, 'story/story_form.html', context)
story urls.py
from django.urls import path
from .views import (
StoryListView,
StoryDetailView,
StoryCreateView,
StoryUpdateView,
StoryDeleteView,
UserStoryListView
)
from .import views
urlpatterns = [
path('', StoryListView.as_view(), name='suyuh-home'),
path('user/<str:username>', UserStoryListView.as_view(), name='user-stories'),
path('story/<int:pk>/', StoryDetailView.as_view(), name='story-detail'), #pk pimarykey for stories
path('story/new/', StoryCreateView.as_view(), name='story-create'),
path('story/<int:pk>/update/', StoryUpdateView.as_view(), name='story-update'),
path('story/<int:pk>/delete/', StoryDeleteView.as_view(), name='story-delete'),
path('about/', views.about, name='suyuh-about'),
]
main urls.py
from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views as auth_views
from users import views as user_views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('story.url')),
path('register/', user_views.register, name='register'),
path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'),
path('password-reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'), name='password-reset'),
path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'), name='password_reset_complete'),
path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'),name='password_reset_done'),
path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'), name='password_reset_confirm'),
path('profile/', user_views.profile, name='profile'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
story_form.html
{% extends "story/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">New Story</legend>
{{ s_form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Create Story</button>
</div>
</form>
</div>
{% endblock content %}
I do not see my mistake at the moment and therefore do not know how to continue. Thanks a lot for your support. I really appreciate every hint!
Greetings!

A couple of things to be updated in your code:
In main/urls.py change the parameter passed to the include method, since as I see it, you file in the app story is called urls.py and not url.py
path('', include('story.urls'))
In story/urls.py you are not associating the view called Create_Audio_Story() with any path. If you want to have this view shown at /story/new, then you should update the file as follows:
from . import views
urlpatterns = [
path('story/new/', views.Create_Audio_Story, name='story-create'),
]

return render (request, 'story_form.html', context)
Try that code instead

Related

Django: error trying to access detail view with re_path

To elaborate, I went down a bit of a rabbit hole just trying to make a trailing "/" optional in the URL. got it to sorta work with the project directory, but when on the blog app, I tried to use re_path in order to use regex to allow for an optional trailing "/" in the url, but I seem to get an error in the template
website urls.py (directory with settings.py)
from django.contrib import admin
from django.urls import path, include, re_path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('main.urls')),
path('blog/', include('blog.urls')),
path('blog', include('blog.urls'))
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
blog urls.py
from django.urls import path, include, re_path
from .views import BlogView, ArticleView
urlpatterns = [
path('', BlogView.as_view(), name="blog"),
re_path(r'titles/(?P<slug_url>\d+)/?$', ArticleView, name="article")
]
blog.html template error appears at the href
{% extends 'base.html' %}
{% block content %}
<h1>Articles</h1>
{% for post in object_list %}
<h2>{{ post.title }}</h2>
{% endfor %}
{% endblock %}
blog views.py
from django.shortcuts import render, get_object_or_404, redirect
from .models import Post
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy, reverse
from django.http import HttpResponseRedirect
# Create your views here.
class BlogView(ListView):
model = Post
template_name = 'blog.html'
def ArticleView(request, url_slug):
post = get_object_or_404(Post, url_slug = url_slug)
return render(request, 'article.html', {'post':post})
Any help would be greatly appreciated, I just find the 404 I get without a trailing / to be very annoying

Django : Problem with Django-allauth urls

I just started with a Django project using django-allauth, I configured the basic settings, without using any 3rd party provider. I have set up the urls.py of my project and urls.py of my app.
But on going to http://localhost:8000, I am getting to 'home.html' but how do I remove the navigation of allauth
The following is the urls.py of my project :
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('allauth.urls')),
path('ckeditor/',include('ckeditor_uploader.urls')),
path('',include('blog.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
And this my urls.py of app :
from django.urls import path, include
from . import views
urlpatterns = [
path("", views.PostListView.as_view(), name = 'post_list'),
path("post/add", views.CreatePostView.as_view(), name = "create_new_post"),
]
views.py
from django.shortcuts import render
from django.views.generic import ListView, View
# Create your views here.
from .forms import PostForm, CommentForm
from .models import Post, Comment
class PostListView(ListView):
queryset = Post.objects.filter(is_published=True)
template_name = 'home.html'
class CreatePostView(View):
form_class = PostForm()
template_name = 'create_post.html'
model = Post
home.html
{% extends 'base.html' %}
{% block content %}
<h1>Hello World</h1>
{% for post in post_list %}
<h1>{{post.post_title}}</h1>
<p>{{post.post_body|safe}}</p>
{% endfor %}
{% endblock %}
path("post/add/", views.CreatePostView.as_view(), name = "create_new_post"),
add trailing slash to your url
your global urls.py:
path('',include('blog.urls')),
add something in your app urls.py:
path('test/',views.PostListView.as_view()),
after adding this to your urls.py, run your app again
the extended base.html file may contain the navigation. make changes there to remove or simply remove it
{% extends 'base.html' %}

Unable to render form in Django

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.

Django-CMS - Django Model Form not rendering

I'm building a new site in Django with Django-CMS that needs a form to filter JSON results and return the filtered set.
My issue is that, initially, I can't even get the Django Model Form to render yet I can get the CSRF token to work so the form is technically rendering, but the inputs/fields aren't showing up at all.
models.py:
from django.db import models
from .jobs.jobs import *
roles = get_filters()
loc = roles[0]
j_type = roles[1]
industry = roles[2]
class Filter(models.Model):
country = models.CharField(max_length=255)
job_type = models.CharField(max_length=255)
industry = models.CharField(max_length=255)
search = models.CharField(max_length=255)
jobs/jobs.py
try:
from BeautifulSoup import BeautifulSoup
except ImportError:
from bs4 import BeautifulSoup
import urllib3
import json
http = urllib3.PoolManager()
def get_filters():
response = http.request('GET', 'http://206.189.27.188/eo/api/v1.0/jobs')
jobs = json.loads(response.data.decode('UTF-8'))
job_list = []
for job, values in jobs.items():
job_list.append(values)
roles_data = []
for job in job_list[0]:
roles_data.append(job)
roles_data = sorted(roles_data, key=lambda role : role["id"], reverse=True)
loc = []
j_type = []
industry = []
for role in roles_data:
loc.append(role['location'])
j_type.append(role['type'])
industry.append(role['industry'])
return loc, j_type, industry
views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import FilterForm
def index(request):
form = FilterForm()
context = {
'form': form,
}
return render(request, 'blog.html', context)
forms.py
from django.forms import ModelForm
from .models import Filter
class FilterForm(ModelForm):
class Meta:
model = Filter
fields = ['country', 'job_type', 'industry', 'search']
urls.py
from __future__ import absolute_import, print_function, unicode_literals
from cms.sitemaps import CMSSitemap
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.i18n import i18n_patterns
from django.contrib import admin
from django.contrib.sitemaps.views import sitemap
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.static import serve
from . import views
admin.autodiscover()
urlpatterns = [
url(r'^sitemap\.xml$', sitemap,
{'sitemaps': {'cmspages': CMSSitemap}}),
url(r'^accounts/', admin.site.urls),
url(r'^services/latest-roles/', views.filter_form, name="filter_form" )
]
urlpatterns += i18n_patterns(
url(r'^admin/', include(admin.site.urls)), # NOQA
url(r'^', include('cms.urls')),
)
# This is only needed when using runserver.
if settings.DEBUG:
urlpatterns = [
url(r'^media/(?P<path>.*)$', serve,
{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
] + staticfiles_urlpatterns() + urlpatterns
blog.html
{% extends 'includes/templates/layout.html' %}
{% load cms_tags i18n sekizai_tags zinnia %}
{% block main_content %}
{% include 'components-header-image.html' %}
<section class="module">
<div class="container">
<div class="row">
<div class="col-md-12 m-auto text-center">
<form action="POST" class="col-md-12">
{% csrf_token %}
{{ form.as_p }}
<button name="submit" class="btn btn-brand">Search</button>
</form>
{% get_all_roles%}
</div>
<div class="col-md-12">
<div class="space" data-MY="120px"></div>
</div>
<div class="col-md-12 flex-center text-center">
{% placeholder 'jobs-bottom-statement' %}
</div>
</div>
</div>
</section>
<!-- Image-->
{% include 'components-contact.html' %}
<!-- Image end-->
{% endblock %}
Sorry for the masses of information, just wanted to include anything anyone might need.
As I said, the CSRF token is displaying, nothing is throwing an error anywhere but it's just not displaying the fields at all.
Really appreciate any help or advice.
I'm 95% sure your view isn't being called.
You need to integrate your application as a CMS apphook or hard code your URLs into your root urls.py which is the easier integration test as it doesn't depend on CMS integration.
So Add your view to your URLs like this;
urlpatterns += i18n_patterns(
url(r'^admin/', include(admin.site.urls)), # NOQA
url(r'^blog/$', views.index, name='blog'),
url(r'^', include('cms.urls')),
)
Then go to localhost:8000/blog/ in your browser & you should hit your view.
To confirm you're hitting it you could make a simple amendment to your view;
def index(request):
form = FilterForm()
context = {
'form': form,
}
print "index hit"
return render(request, 'blog.html', context)
Then you'll see "index hit" in your console if your view is called.

DetailView template not displaying it's data

within an app I have two models, named Course and Step. Every Step belongs to a Course and each Course has many steps. However, I'm having problem creating a detailview for Steps. For example when i go to the url 'http://127.0.0.1:8000/courses/1' it should display steps for course.objects.get(pk=1). However what i get back is just the page for course, i.e, http://127.0.0.1:8000/courses'.
Model
from django.db import models
# Create your models here.
class Course(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length= 255)
description = models.TextField()
def __str__(self):
return self.title
class Step(models.Model):
title = models.CharField(max_length = 255)
description = models.TextField()
order = models.IntegerField()
course = models.ForeignKey(Course)
def __str__(self):
return self.title
Url
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.course_list),
url(r'(?P<pk>\d+)/$', views.course_detail)
]
View
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
from .models import Course, Step
def course_list(request):
courses = Course.objects.all()
return render(request, 'courses/course_list.html', {'courses': courses})
def course_detail(request, pk):
course = Course.objects.get(pk=pk)
return render(request, 'courses/course_detail.html', {'course': course})
course_detail.html
{% extends 'layout.html' %}
{% block title %}{{course.title}}{% endblock %}
{% block content %}
<article>
<h2>{{ course.title }} %</h2>
{{course.description}}
<section>
{% for step in course.step_set.all %}
<h3>{{ step.title }}</h3>
{{step.description}}
{% endfor %}
</section>
</article>
{% endblock %}
Main Urls
from django.conf.urls import url, include
from django.contrib import admin
from courses.views import course_list
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
url(r'^courses/', course_list),
url(r'^admin/', admin.site.urls),
url(r'^$', views.hello_world),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
I just can't seem to recognize where i went wrong
I think the you need these url mappings..! This should do the trick.
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^applicationName/$', views.ListView.as_view(), name='courses'),
url(r'^applicationName/(?P<pk>\d+)$', views.CourseDetailView.as_view(), name='course-detail'),
]
The problem is in your main urls.py file - this line makes any URL path starting with 'courses/' resolve to the course_list view:
url(r'^courses/', course_list),
So Django will never reach the course_detail view. Instead, you must "include" the application-specific URLs:
url(r'^courses/', include('myproject.myapp.urls'),
Where myproject is your main project name, and myapp is your app name (make sure you also registered your application under INSTALLED_APPS at your settings.py file).

Categories

Resources