Unable to render form in Django - python

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.

Related

django objects method is not responding in views.py [duplicate]

I am currently doing Django project with sqlite3 with ORM method.
I am unable to debug as print() is not working in the terminal even if I put print() function in views.py.
I checked in python shell, the queryset is working.
In views.py
from django.shortcuts import render,redirect
from .models import BookBoardModel
def index(request):
all_books = BookBoardModel.objects.all()
print(all_books)
for item in all_books:
print(item.title)
context = {'all_books': all_books}
return render(request, 'category_books_page/index.html', context)
The terminal shown with warning sign and not giving print():
Due to this, the variable all_books are not properly rendered in the index.html which will not generate any objects in index.html
In index.html
{{all_books}} It is not showing at all :(
In category_books_page.urls.py
from django.urls import path
from django.contrib import admin
from . import views
urlpatterns = [
path('', views.index, name='bookHome'),
]
In config.urls.py
from django.contrib import admin
from django.urls import path, include
from signup_page import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('default_page.urls')),
path('category_books_page/', include('category_books_page.urls')),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
You can try in template:
{% for book in all_books %}
{{ book.title }}
{% endfor %}
Try to restart runserver project

AttributeError: module 'users.views' has no attribute 'register'

I am new to Python and Django. Getting this error when running the server. The problem seems to be in 'urls.py' of the project.
File "C:\Users\Desktop\myproject\django_project\django_project\urls.py", line 22, in <module>
path('register/', user_views.register , name = 'register'),
AttributeError: module 'users.views' has no attribute 'register'
This is my urls.py
from django.contrib import admin
from django.urls import path, include
from users import views as user_views
urlpatterns = [
path('admin/', admin.site.urls),
path('register/', user_views.register , name = 'register'),
path('', include('blog.urls')),
]
This is register.html under users/templates/users/register.html (users is the name of the app)
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Join Today</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Sign Up</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Already Have An Account? <a class="ml-2" href="#">Sign In</a>
</small>
</div>
</div>
{% endblock content %}
This is my views.py
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
def register(request):
form = UserCreationForm()
return render(request, 'users/register.html', {'form':form})
I have also tried creating a separate urls.py for my 'users' app and adding the path there but I am getting the same error.
I am very new to programming so please excuse my inexperience.
Make sure you have a space after register>>> def register (request):
If it is not the issue please check the "views.py" for correct register function under the users folder.
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
# Create your views here.
def register (request):
form = UserCreationForm()
return render(request, 'users/register.html', {'form': form})
Your urls.py should be like this:
from django.contrib import admin
from django.urls import path, include
from .view.py import register
urlpatterns = [
path('admin/', admin.site.urls),
path('register/',register , name = 'register'),
path('', include('blog.urls')),
]
Note: if your views name is views.py
consider this arrange:
you have a users application in your base directory, this app has a users-views.py file that your register function is there.
then your urls.py must be like this:
from django.contrib import admin
from django.urls import path, include
from users import users-views as user_views
urlpatterns = [
path('admin/', admin.site.urls),
path('register/', user_views.register , name = 'register'),
path('', include('blog.urls')),
]
as you can see your users application has no views.py I recommend rename users-views.py to views.py and use your original urls.py.
Is your users/views.py file saved and up to date? Try stopping the server completely, ctrl+c on windows if it's started and double check all your files are up to date then try running the server again.

How to fix Page Not Found (404) error in django

How to fix this error in django 3.0, when im trying to reach a page using form post method, I getting this error
Hi, Im new to Django programming language, Now im developing a college project in django, When Im using forms to create login in POST method. If I put it on main page, It's working well. But when I put the forms into inside of another page (about.html) I got this error. I can't fix it. So guys Please help me..
> Page not found (404) Request Method: POST Request
> URL: http://127.0.0.1:8000/about/login Using the URLconf defined in
> mysite.urls, Django tried these URL patterns, in this order:
>
> [name='home'] login/ about/ admin/ The current path, about/login,
> 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.
app/ Urls.py
from django.urls import path
from . import views
urlpatterns = [
path('',views.home,name='home'),
path('', views.about, name="about"),
path('', views.login, name="login")
path('admin/', admin.site.urls),
]
project/ urls.py
from django.contrib import admin
from django.urls import path,include
from pages.views import home, about, login
urlpatterns = [
path('',home,name='home'),
path('login/',login),
path('about/',about),
path('admin/', admin.site.urls),
]
views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
# Create your views here.
def home(request, *args, **kwargs):
return render(request, "test.html")
def about(request,*args, **kwargs):
return render(request,"inner.html")
def login(request, *args, **kwargs):
return render(request, "result.html")
HTML FORM
<form action="login" method="POST">
{% csrf_token %}
<label> username</label>
<input type="text" name="uname"><br>
<label> Password</label>
<input type="Password" name="upwd"><br>
<input type="submit" name="submit" value="submit">
</form>
You main problem in action="login"
First write action="/login" for resolve you problem, because now you add login to current opened url

Django (Python) : Django form is not Displaying

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

How to fix 'str' object is not callable in django

Hi Everyone I made A Blog but when i delete post i get this error i'm using django latest version:
TypeError at /post/(?P3\d+)/remove/
'str' object is not callable'
Here Is My Views.py
class PostDeleteView(LoginRequiredMixin,DeleteView):
success_url = reverse_lazy('post_list')
model = Post
Here is my app Urls.py
from django.urls import path
from blog import views
urlpatterns = [
path('',views.PostListView.as_view(),name='post_list'),
path('about/',views.AboutView.as_view(),name='about'),
path('register/',views.user_register,name='user_register'),
path('post/(?P<pk>\d+)',views.PostDetailView.as_view(),name='post_detail'),
path('post/new/',views.CreatePostView.as_view(),name='post_new'),
path('post/(?P<pk>\d+)/edit/',views.PostUpdateView.as_view(),name='post_edit'),
path('post/<int:pk>/remove/',views.PostDeleteView.as_view(),name='post_remove'),
path('drafts/',views.PostDraftListView.as_view(),name='post_draft_list'),
path('post/(?P<pk>\d+)/comment/',views.add_comment_to_post,name='add_comment_to_post'),
path('comment/(?P<pk>\d+)/approve/',views.comment_approve,name='comment_approve'),
path('comment/(?P<pk>\d+)/remove/',views.comment_remove,name='comment_remove'),
path('post/(?P<pk>\d+)/publish/',views.post_publish,name='post_publish'),
]
Image
https://i.stack.imgur.com/wbcfn.png
Here is my post_confirm_delete.html
{% extends "blog/base.html" %}
{% block content %}
<form method="POST">
{% csrf_token %}
<p>Are You sure you want to delete {{ object }}?</p>
<input type="submit" class="btn btn-danger" value="Confirm">
</form>
{% endblock %}
Here is my Project Urls.py
"""blogpro URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,include
from django.contrib.auth.views import LoginView,LogoutView
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
path('accounts/login/', LoginView.as_view(), name='login'),
path('accounts/logout/', LogoutView.as_view(), name='logout', kwargs={'next_page': '/'}),
]
You are using path with regex which is not how it work docs, only use regex url string with re_path
it should be :
path('post/<int:pk>/remove/',views.PostDeleteView.as_view(),name='post_remove'),

Categories

Resources