So, I have a code below:
newEra/urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path("",include('mentor.urls')),]
mentor/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('',views.home_page),
]
my views.py
from django.shortcuts import render,redirect
from .models import *
from .forms import *
def home_page(request):
todo = ToDo.objects.all()
form = ToDoForms()
if request.method == 'POST':
form = ToDoForms(request.POST)
if form.is_valid():
form.save()
return redirect('')
context = {'todo' : todo, 'form':form}
return render(request, 'home.html',context)
home.html
<h1>To-Do list</h1>
<form action="POST" method="/">
{% csrf_token %}
{{form.name}}
<input type="submit" value="Create task" >
</form>
<ul>
{% for to in todo %}
<li>{{ to }}</li>
{% endfor %}
</ul>
But I am getting this error below
**Using the URLconf defined in NewEra.urls, Django tried these URL patterns, in this order:
admin/
The current path, POST, didn't match any of these.**
'mentor' file added to the SETTINGS
URLs are regexes.
Try:
urlpatterns = [
path('^/$',views.home_page),
]
Related
models.py
I write this code for creating a form which has two fileds named Title and Desc
from django.db import models.Here is models.py code.
class Post(models.Model):
title = models.CharField(max_length=200)
desc = models.TextField()
And Here is forms.py Code
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm,AuthenticationForm,UsernameField
from django.contrib.auth.models import User
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title','desc']
# label = {'title':'Title','desc':'Description'}
widgets={'title':forms.TextInput(attrs={'class':'form-control'}),
'desc':forms.Textarea(attrs={'class':'form-control'})}
Here is the views.py code
views.py
from django.shortcuts import render,HttpResponseRedirect
from .forms import SignUpForm,LoginForm,PostForm
from django.contrib import messages
from django.contrib.auth import authenticate,login,logout
from .models import Post
def add_post(request):
if request.user.is_authenticated:
if request.method == "POST":
form = PostForm(request.method)
if form.is_valid():
title1 = form.cleaned_data['title']
description = form.cleaned_data['desc']
pst = Post(title=title1,desc=description)
pst.save()
form = PostForm()
else:
form = PostForm()
return render(request,'blog_app/addpost.html',{'form':form})
else:
return HttpResponseRedirect('/login/')
Here is the addpost.html
addpost.html
{% extends 'blog_app/base.html' %}
{% load static %}
{% block content %}
<div class="col-sm-10">
<h3 class="text-black my-5 alert alert-success">Add Post</h3>
<form action="" method="post">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Add" class="btn btn-primary">
Cancel
</form>
</div>
{% endblock content %}
But When I click on Add Button I got this errorenter image description here
What is the solution of it
Here is Url.py code
urls.py
from django.contrib import admin
from django.urls import path
from blog_app import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home),
path('about/', views.about,name='about'),
path('contact/', views.contact,name='contact'),
path('dashboard/', views.dashboard,name='dashboard'),
path('signup/', views.signup,name='signup'),
path('login/', views.user_login,name='login'),
path('logout/', views.user_logout,name='logout'),
path('add/', views.add_post,name='addpost'),
path('update/<int:id>/', views.update_post,name='updatepost'),
path('delete/<int:id>/', views.delete_post,name='deletepost'),
]
And This is the error Shows in my terminal
terminal img
This line in your view
form = PostForm(request.method)
should be
form = PostForm(request.POST)
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 wan't to get to order_list page after adding new order.
Was trying both reverse and reverse_lazy method also just to set page adres value to success_url directly like success_url = 'orders/order_list' or sucess url = 'order_list' but it always returns me Http 405 error.
views.py
django.shortcuts import render
from django.urls import reverse_lazy
from django.views import View
from django.views.generic import ListView, DetailView, CreateView
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.mixins import PermissionRequiredMixin, LoginRequiredMixin
from .models import Order
from .forms import CreateOrder
from django.contrib.auth.decorators import login_required
# Create your views here.
class OrderCreateView(LoginRequiredMixin, PermissionRequiredMixin, CreateView):
login_url = '/login_required'
permission_required = 'orders.add-order'
model = Order
success_url = reverse_lazy('orders:order_list')
fields = ['airport', 'direction', 'adress', 'client', 'telephone', 'flight_number', 'plane', 'pick_up', 'gate', 'driver']
urls.py
from django.contrib import admin
from django.urls import path
from django.contrib.auth import views as auth_views
from orders.views import OrderCreateView, OrderListView, AboutView, LoginRequiredView
urlpatterns = [
path('admin/', admin.site.urls),
path('add_order/', OrderCreateView.as_view(template_name="orders/add_order.html"), name="add_order"),
path('order_list/', OrderListView.as_view(), name="order_list"),
path('login/', auth_views.LoginView.as_view(template_name="pages/login.html"), name="login"),
path('logout/', auth_views.LogoutView.as_view(template_name="pages/logout.html"), name="logout"),
path('about/', AboutView.as_view(), name="about"),
path('login_required/', LoginRequiredView.as_view(), name='login_required')
]
add_order.html
{% extends 'base.html' %}
{% load static %}
{% load crispy_forms_tags %}
{% block content %}
<div class="container" style="width: 40%; height: 80%;">
<div class="page header">
<h1>Add new order</h1>
</div>
<form action="/order_list/" method="post">
{% csrf_token %}
{{ form|crispy }}
<button type="submit" class="btn btn-success">Save order</button>
</form>
</div>
{% endblock %}
Any ideas what am I doing wrong ?
Change:
success_url = reverse_lazy('orders:order_list')
To:
success_url = reverse_lazy('order_list')
And change:
<form action="/order_list/" method="post">
To:
<form action="/add_order/" method="post">
Note: You are using hardcoded URL which is not recommended. Use the url template tag.
Login cannot be done in my app.I wrote in views.py
from django.shortcuts import render,redirect
from django.urls import reverse
from app.forms import RegisterForm,LoginForm
from app.models import Data
from app.forms import DataForm
from django.db.models import Q
def index(request):
data = Data.objects.order_by('-created_at')
form = RegisterForm()
loginform = LoginForm()
dataform = DataForm()
return render(request, 'index.html',{'data':data,'form':form,'loginform':loginform,'dataform':dataform,'user': request.user})
in index.html
<section id="top">
{% if user and not user.is_anonymous %}
<p>Hello</p>
<h3>{{ user.username }}</h3>
{% else %}
<form action="{% url 'app:index' %}" method="POST">
{{ loginform.non_field_errors }}
{% for field in loginform %}
{{ field }}
{{ field.errors }}
{% endfor %}
<button type="submit">LOGIN</button>
{% csrf_token %}
</form>
{% endif %}
</section>
in forms.py
from django import forms
from django.contrib.auth.forms import (
AuthenticationForm
)
class LoginForm(AuthenticationForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields.values():
field.widget.attrs['class'] = 'form-control'
field.widget.attrs['placeholder'] = field.label
in child's app's urls.py
from django.urls import include, path
from . import views
from django.contrib.auth.views import login
app_name = 'app'
urlpatterns = [
path('index', views.index,name='index'),
]
in parent's app's urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('app/',include('app.urls') ),
]
When I login from loginform,if statement of {% if user and not user.is_anonymous %} did not become true.But when I login in admin site, the statement become true.When I put LOGIN button, no error happens.I really cannot understand what is wrong.How should I fix this?
Your index view doesn't do anything when a POST request is submitted. It just initialises empty forms and returns them. You need to actually process the data that is submitted, authenticate the user and call the login method:
def index(request):
if request.method == 'POST':
loginform = LoginForm(request, data=request.POST)
if loginform.is_valid(): # this authenticates the user
user = loginform.get_user()
# redirect to success view or just render index.html
return render(request, 'index.html', {'user': user})
# else not needed, we go to the end and return the form with errors
else: # request method is 'GET'
loginform = LoginForm()
dataform = ...
...
return render(request, 'index.html',{'data':data,'form':form,'loginform':loginform,'dataform':dataform,'user': request.user})
When i'm submitting a jpg image then it refreshes and shows 'This field required'validation error,so in views i tried to print(request.POST),it shows csrfmiddlewaretoken and pic in console but field validation is getting violated. Please correct me.
models.py
from django.db import models
class picture(models.Model):
pic = models.ImageField(upload_to='documents/')
forms.py
from django import forms
from .models import picture
class pictureForm(forms.ModelForm):
class Meta:
model = picture
fields = ['pic',]
views.py
from django.shortcuts import render,redirect
from .models import picture
from .forms import pictureForm
# Create your views here.
def pictureView(request):
if request.method == 'POST':
print(request.POST)
form = pictureForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
form = pictureForm()
return render(request,'home.html',{'form':form})
urls.py(APP level urls)
from django.urls import path
from . import views
urlpatterns = [
path('',views.pictureView, name = 'home')
]
urls.py(Directory level urls)
from django.contrib import admin
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('',include('post.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Media files
MEDIA_URL ='/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
template
<form method="post">
{% csrf_token %}
{{form.as_p}}
<input value="submit" type="submit">
</form>
based on the doc: uploaded-files-with-a-model
you should initialize your form:
form = pictureForm(request.POST, request.FILES)
and in the template you need add enctype="multipart/form-data"
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{form.as_p}}
<input value="submit" type="submit">
</form>