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.
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 using Django 3.0.8
in Python version 3.8.2
I'm getting an FieldError at /post/new/
Exception Type: FieldError
Exception Value: Unknown field(s) (content) specified for Post
PostCreateView is a class-based view in my views.py of under the blog app of my current project
My blog/views.py is here:-
from django.shortcuts import render
from .models import Post
from django.views.generic import (
ListView,
DetailView,
CreateView,
)
# Create your views here.
def home(request):
context = {
'posts': Post.objects.all()
}
return render(request, 'blog/home.htm', context)
def about(request):
return render(request, 'blog/about.htm', {'title': 'About'})
# return HttpResponse('<h1> Blog - About page that we want you to see </h1>')
def order(request):
return render(request, 'blog/order.htm')
class PostListView(ListView):
model = Post
template_name = 'blog/home.htm' # <app>/<model>_<viewtype>.html
context_object_name = 'posts'
ordering = ['-date_posted']
class PostDetailView(DetailView):
model = Post
class PostCreateView(CreateView):
model = Post
fields = ['title', 'content']
My blog/urls.py is here:
from django.urls import path
from . import views
from .views import (
PostListView,
PostDetailView,
PostCreateView
)
urlpatterns = [
path('about/', views.about, name='blog-about'),
path('order/', views.order, name='blog-order'),
path('', PostListView.as_view(), name='blog-home' ),
path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail' ),
path('post/new/', PostCreateView.as_view(), name='post-create' ),
]
My blog/templates/blog/post_form.html is here:-
{% extends "blog/base.htm" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="context-section">
<form method="POST">
{% csrf_token %} <!-- for security perpose -->
<fieldset class="form-group">
<legend class="boder-bottom mb-4">Blog Post</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Post</button>
</div>
</form>
</div>
{% endblock content %}
What wrong is with the code, Please help!!!
I am new to Django and I am completely lost-in here?
I will be very much thankful for your suggestions!!
Thanks and Wellcome
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),
]
How does the CreatePostView in views.py link to the post_form.html.
It does not have "template_name" in it still how does the createpostview links to the post_form.html?
Please look into the following codes that i have added below, and let me know if you can help, Thankyou!
Views.py
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.utils import timezone
from .models import Post, Comment
from .forms import PostForm, CommentForm
from django.views.generic import (TemplateView,ListView,
DetailView,CreateView,
UpdateView,DeleteView)
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin
class CreatePostView(LoginRequiredMixin,CreateView):
login_url = '/login/'
redirect_field_name = 'blog/post_detail.html'
form_class = PostForm
model = Post
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('post/new/', views.CreatePostView.as_view(), name='post_new'),
]
post_form.html
{% extends 'blog/base.html' %}
{% block content %}
<h1>New post</h1>
<form method="POST" class="post-form">
{% csrf_token %}
{{form.as_p}}
<button type="submit" class="save btn btn-default">Save</button>
</form>
<script>var editor = new MediumEditor('.editable');</script>
{% endblock %}
Please help me understand this.
For a model Post in app myapp, the CreateView will use the template myapp/post_form.html.
This is just the documented behaviour of CreateView.
You might find it useful to look at the get_template_names method on the ccbv website to understand how the code works.
What I would like to have is an admin panel that I create where only users with permissions set to "admin" in the UserLevel model can edit certain aspects of the website. However, while I think I have everything coded out properly it isn't working. The way I'm trying to implement this already work on the main content section of my site. My best guess is that since I'm trying to cross-use views between apps something got mixed up, although that may be wrong. Also please keep in mind that while I definitely started with clean code which emulated the code from the working parts of the site this code may not so clean because I have been playing around with it so much that I'm just flat out confused... so any help would be much appreciated.
To be clear, there's no error with the site which is why I think the code is written correctly. However, I made a test widget which is not displaying on the home page at all (it's supposed to), nor will it display on the admin panel page I setup (which is supposed to display any widgets there may be), and I can't get the form for adding a new widget to display on the admin panel page either (it gives me a button to go to another page that has the form on it).
Project urls.py:
"""colors URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
from accounts import views
from colorsets import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$',views.PostListView.as_view(),name='index'),
url(r'^accounts/',include('accounts.urls',namespace='accounts')),
url(r'^colorsets/',include('colorsets.urls',namespace='colorsets')),
url(r'^adminpanel/',include('adminpanel.urls',namespace='adminpanel')),
]
Adminpanel app urls.py:
from django.conf.urls import url
from adminpanel import views
app_name = 'adminpanel'
urlpatterns = [
url(r'^settings/',views.SettingsListView.as_view(),name='settings'),
url(r'^new/$',views.CreateWidgetView.as_view(),name='create-widget'),
url(r'^delete/$',views.DeleteWidget.as_view(),name='delete-widgets'),
]
Adminpanel app views.py:
from django.shortcuts import render
from adminpanel.forms import WidgetForm
from adminpanel.models import Widget
from django.utils import timezone
from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse,reverse_lazy
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from braces.views import SelectRelatedMixin
from django.views.generic import (TemplateView,ListView,
DetailView,CreateView,
UpdateView,DeleteView)
# Create your views here.
class CreateWidgetView(LoginRequiredMixin,CreateView):
login_url = '/login/'
redirect_field_name = 'index.html'
form_class = WidgetForm
model = Widget
def form_valid(self,form):
self.object = form.save(commit=False)
self.object.save()
return super().form_valid(form)
class SettingsListView(ListView):
login_url = '/login/'
redirect_field_name = 'index.html'
form_class = WidgetForm
model = Widget
def form_valid(self,form):
self.object = form.save(commit=False)
self.object.save()
return super().form_valid(form)
def get_query(self):
return Widget.object.filter(order_by('widget_order'))
class DeleteWidget(LoginRequiredMixin,SelectRelatedMixin,DeleteView):
model = Widget
select_related = ('Widget',)
success_url = reverse_lazy('settings')
def get_queryset(self):
queryset = super().get_query()
return queryset.filter(user_id=self.request.user.id)
def delete(self):
return super().delete(*args,**kwargs)
Colorsets app views.py (Where I started mixing things):
from django.shortcuts import render
from colorsets.forms import ColorForm
from colorsets import models
from colorsets.models import ColorSet
from adminpanel.models import Widget
from django.utils import timezone
from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse,reverse_lazy
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from braces.views import SelectRelatedMixin
from django.views.generic import (TemplateView,ListView,
DetailView,CreateView,
UpdateView,DeleteView)
# Create your views here.
#def index(request):
# return render(request,'index.html')
class PostListView(ListView):
model = ColorSet
model = Widget
def get_queryset(self):
return ColorSet.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
return Widget.objects.filter(order_by('widget_order'))
class CreateColorSetView(LoginRequiredMixin,CreateView):
login_url = '/login/'
redirect_field_name = 'index.html'
form_class = ColorForm
model = ColorSet
def form_valid(self,form):
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.save()
return super().form_valid(form)
class DeletePost(LoginRequiredMixin,SelectRelatedMixin,DeleteView):
model = models.ColorSet
select_related = ('user',)
success_url = reverse_lazy('index')
def get_queryset(self):
queryset = super().get_queryset()
return queryset.filter(user_id=self.request.user.id)
def delete(self,*args,**kwargs):
return super().delete(*args,**kwargs)
Adminpanel app models.py:
from django.db import models
# Create your models here.
class Widget(models.Model):
name = models.CharField(max_length=50)
widget_order = models.IntegerField(default=0)
body = models.TextField(max_length=500)
def __str__(self):
return self.name
widget_list.html:
{% extends "base.html" %}
{% block content %}
<div class="container">
<div class="content">
{% for widget in widget_list %}
<p>{{ widget.body }}</p>
{% endfor %}
</div>
</div>
{% endblock %}
_post.html:
<div class="post media">
<div class="media-body">
<strong>{{ colorset.user.username }}</strong>
<div class="media-footer">
{% if user.is_authenticated and UserLevels.access_level == 'admin' %}
<a href="{% url 'colorsets:delete' pk=colorset.pk %}" title="delete" class="btn btn-simple">
Delete
</a>
{% endif %}
</div>
</div>
</div>
widget_form.html:
{% block content %}
<div class="colorset-base">
<h2>Create new widget</h2>
<form id="postForm" action="{% url 'adminpanel:create-widget' %}" method="POST">
{% csrf_token %}
{{ form }}
<button type="submit" class="submit btn btn-primary btn-large">Add Widget</button>
</form>
</div>
{% endblock %}
settings.html:
{% extends "base.html" %}
{% block content %}
<div class="container">
<h2>Settings:</h2>
</div>
{% endblock %}
widget_confirm_delete.html:
{% extends 'base.html' %}
{% block content %}
<h3>Are you sure you want to delete this widget?</h3>
<div class="posts">
{% include "adminpanel/_post.html" with post=object hide_delete=True %}
</div>
<form method="POST">
{% csrf_token %}
<input type="submit" value="Confirm Delete" class="btn btn-danger btn-large" />
<a class="btn btn-simple btn-large" href="{% url 'adminpanel/settings'%}">Cancel</a>
</form>
{% endblock %}
I know not everything is being used by things but this is everything I have.