Here is what i have in base.html (inside the footer, so this newsletter form will be in every page)
<form action="" method="POST">
{% csrf_token %}
<div class="form-group">
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder='Enter email address' onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter email address'">
<div class="input-group-append">
<button class="btn" type="submit"><span class="lnr lnr-arrow-right"></span></button>
</div>
</div>
</div>
</form>
Here is the model (subscribe/models.py)
class Subscriber(models.Model):
email = models.EmailField()
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.email
what i have in views.py
def subscribe_form(request):
if request.method == 'POST':
email = request.POST.get('email')
new_email = Subscriber()
new_email.email = email
new_email.save()
return redirect('home-page')
here is urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.PostListView.as_view(), name='home-page'),
path('subscribe/', views.subscribe_form, name='subscriber'),
path('archive/', views.archive, name='archive-page'),
path('category/', views.category, name='category-page'),
path('contact/', views.contact, name='contact-page')
]
after submitting the submit button i'm getting this error in shell
Method Not Allowed (POST): /
Method Not Allowed: /
[18/Jan/2020 04:13:11] "POST / HTTP/1.1" 405 0
so, i'm a beginner, im trying to build a blog, but i didn't find any useful solution that can solve this issue. maybe i'm going totally wrong, but anyway if someone can help me to make this working.
Thank you all.
In your index URL, you are not allowed to post.So change it to subscribe/
<form action="{% url 'subscriber' %}" method="POST>
Related
I am a beginner in learning code and am working on making a simple django site where users can write comments but I keep getting this error
My urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("profile/<str:name>/", views.profile, name="profile")
]
views.py
class NewPostForm(forms.Form):
title = forms.CharField(label="Title")
description = forms.CharField(widget=forms.Textarea)
def index(request):
if request.method == "POST":
form = NewPostForm(request.POST)
if form.is_valid():
title = form.cleaned_data['title']
description = form.cleaned_data['description']
author = request.user
post = NewPost(title=title, description=description, author=author)
post.save()
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "network/index.html", {
"form": form
})
return render(request, "network/index.html", {
"form": NewPostForm(),
"posts": NewPost.objects.all()
})
models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
pass
class NewPost(models.Model):
title = models.CharField(max_length=32)
description = models.CharField(max_length=256)
author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
and my index.html
{% extends "network/layout.html" %}
{% load static %}
{% load crispy_forms_tags %}
{% block body %}
<div class="form-group">
<form method="post" action="{% url 'index' %}">
{% csrf_token %}
{{form | crispy}}
<button class="btn btn-primary"> Post </button>
</form>
</div>
{% for post in posts %}
<div class="card">
<div class="card-body"> Title: {{post.title}} </div>
<div class="card-body"> Description: {{post.description}}</div>
<p> {{post.author.username}} </p>
<div class="card-body">
<a href="{% url 'profile' post.author.username %}">
#{{post.author.username}}
</a>
</div>
</div>
{% endfor %}
{% endblock %}
But I keep getting
NoReverseMatch at / Reverse for 'profile' with arguments '('',)' not found. 1 pattern(s) tried: ['profile/(?P[^/]+)/$']
It looks like the error is occurring with
<a href="{% url 'profile' post.author.username %}">
Make sure that each of these posts that you are looping through actually has an author and that each author has a username. Django won't be able to properly construct the url if post.author.username is None.
in this url : path("profile/str:name/", views.profile, name="profile")
do you have an view called profile?
and what does name in str:name refer to? username maybe? or author
you need to provide more details,
This is because you have an project with author I faced the similar issue.
Maybe you need to check your admin panel if there is a post without author that's probably the problem
NoReverseMatch at / Reverse for 'profile' with arguments '('',)' not found. 1 pattern(s) tried: ['profile/(?P[^/]+)/$']
It's means something missing in database thats you are working for in loops .Django won't be able to properly construct the url if somthing is blank. First go to the Django admit panel and find whats are missing.Example:Author,User,Admin etc.
If you define a post without assigning a profile (owner) to it, you get this error. in other words, something that Django wants (in your database) is blank!
You must go to the admin panel and check all posts that are defined, None of them should be without an owner.
i am unable to search and get 404 error same problem occur in sitemap views for creating static xml file,
it does not return the url for static file and now have this problem with search as it is unable to find search .html gives this Page not found (404) error while searching through search page Raised by: blog.views.blogpost error.
Search_Form
<form method='GET' action="/blog/search/" class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="search" id="search">
<button class="btn btn-outline-success mx-2 my-1 my-sm-0" type="submit">Search</button>
</form>
Search views.py
def search(request):
myposts = Blogpost.objects.all()
query = request.GET['search']
if len(query)>78:
myposts = Blogpost.objects.none()
else:
post_title = Blogpost.objects.filter(Q(title__icontains=query))
posts_content = Blogpost.objects.filter(Q(content__icontains=query))
posts_slug = Blogpost.objects.filter(Q(slug__icontains=query))
myposts = post_title | posts_content | posts_slug
if myposts.count() == 0:
messages.warning(request, "No search results found. Please enter again.")
context = {'myposts': myposts,'query':query}
return render(request, 'blog/search.html', context)
url.py
urlpatterns = [
path('', views.index, name='bloglist'),
path('<slug:post>/', views.blogpost, name='blogpost'),
path("contact/", views.contact, name="contact"),
path("search/", views.search, name="search")
]
My search.html
{% block body %}
<div class="container mt-3">
<h5> <p> Search Results:</p> </h5>
{% if myposts|length < 1 %}
Your Search -<b> {{query}} </b>- did not match any documents please try again. <br>
<br> Suggestions:
<ul>
<li>Make sure that all words are spelled correctly.</li>
<li>Try more general keywords.</li>
<li>Try different keywords.</li>
</ul>
{% endif %}
<div class="container mt-3">
<div class="row my-2">
{% for post in myposts %}
<div class="col-md-6">
<div class="row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative">
<div class="col p-4 d-flex flex-column position-static">
<h3 class="mb-0">{{post.title}}</h3>
<div class="mb-1 text-muted"></div>
<strong class="d-inline-block mb-2 text-primary"><a>{{post.author}} | {{post.created_on}}</a></strong>
<p class="card-text mb-auto">{{post.content|safe}}</p>
Continue reading
</div>
<div class="col-auto d-none d-lg-block">
<img src="/media/{{post.thumbnail}}" class="bd-placeholder-img" width="200" height="250" aria-label="Placeholder: Thumbnail">
<title>Placeholder</title></img>
</div>
</div>
</div>
{% if forloop.counter|divisibleby:2%}
</div>
<div class="row my-2">
{% endif %}
{% endfor %}</div>
</div>
</div>
{% endblock %}
Project urls.py
from django.contrib.sitemaps.views import sitemap
from blog.sitemaps import StaticViewsSitemap
from blog.sitemaps import BlogSitemap
sitemaps ={
'blogpost': BlogSitemap(),
'static': StaticViewsSitemap(),
}
urlpatterns = [
path('admin/', admin.site.urls),
path('shop/', include('shop.urls')),
path('blog/', include('blog.urls', namespace='blog')),
path('', views.index),
path('register/', views.registerPage),
path('login/', views.loginPage),
path('logout/', views.logoutUser),
path('sitemap.xml/', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py
class Blogpost(models.Model):
STATUS_CHOICES= ( ('0', 'Draft'), ('1', 'Publish'),)
post_id = models.AutoField(primary_key= True)
title = models.CharField(max_length=50, unique=True)
slug = models.SlugField(max_length=50, unique=True)
content = models.TextField(max_length=5000, default="")
author = models.ForeignKey(Author, on_delete=models.CASCADE)
thumbnail = models.ImageField(upload_to='shop/images', default="")
created_on = models.DateTimeField(default=timezone.now)
categories = models.ManyToManyField(Category)
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
objects = models.Manager()
featured = models.BooleanField()
def get_absolute_url(self):
return reverse('blog:blogpost',
args=[self.slug])
class Meta:
ordering = ('-created_on',)
def __str__(self):
return self.title
Try rewriting your form to something like this:
<form method="POST" action="{% url 'search' %}" class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" arialabel="Search" name="search" id="search">
<button class="btn btn-outline-success mx-2 my-1 my-sm-0" type="submit">Search</button>
</form>
And your search view like this:
def search(request):
myposts = Blogpost.objects.all()
if request.method == 'POST'
query = request.POST.get('search')
if len(query) > 78:
myposts = Blogpost.objects.none()
else:
myposts = Blogpost.objects.filter(Q(title__icontains=query))
myposts = Blogpost.objects.filter(Q(content__icontains=query))
myposts = Blogpost.objects.filter(Q(slug__icontains=query))
if myposts.count() == 0:
messages.warning(request, "No search results found. Please enter again.")
context = {'myposts': myposts, 'query': query}
return render(request, 'blog/search.html', context)
UPDATE
So, after going through your GitHub repository I saw a couple of issues, first off there is no urls.py or views.py in your blog app, its either not added in the repo or just doesn't exist, which would explain the router not finding any paths for your views, hovewer there is one in the question so I'm not sure whats the issue here, please check again so that the file is in the right directory in the root of your blog app folder.
Second off in your main project directory there are files called urls.py, views.py and forms.py, that shouldn't be the case, instead create a seperate app and place them there.
Im new to Django. I am trying to create product archvisation, but when i click on the button to archive i've got error ,,Method Not Allowed (POST)". Dunno how to deal with it.
Here is my code
views.py
def to_archive(request):
if request.method == 'POST':
product = request.POST['to_archive']
product_archive = Product.objects.get(id=product)
if not product_archive.is_active:
product_archive.is_active = True
product_archive.archived_date = timezone.now
product_archive.save()
models.py
class Product(models.Model):
is_archived = models.BooleanField(_('Archive'), default=False)
archived_date = models.DateTimeField(_('Date Archived'), blank=True, null=True)
form in html file
<form action="{% url 'to_archive' %}" method="POST">
{% csrf_token %}
<input type="hidden" name="to_archive" value="{{ object }}">
<input id="disactive_button" type="submit" class="btn btn-primary" value="To archive">
</form>
urls.py
urlpatterns = [
path('', IndexView.as_view(), name='home'),
path('to_archive/', to_archive, name='to_archive'),
]
Error:
Method Not Allowed (POST): /product/chair/
Method Not Allowed: /product/chair/
[09/Sep/2020 13:29:27] "POST /product/chair/ HTTP/1.1" 405 0
I am having an issue with successfully calling a redirect after a user tries to log in (successful or unsuccessfully). In the console, I did notice that the GET and POST statements are correct. Thank You all in advance as this is a becoming a royal PIA.
views.py
class UserLoginFormView(View):
form_class = UserLoginForm
template_name = 'home/login.html'
#Display Blank Form
def get(self,request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
#Process Form Data
def post(self,request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
return redirect('products')
urls.py
urlpatterns = [
url(r'^$', views.HomeView, name='home'),
url(r'^register/$', views.UserFormView.as_view(), name="register"),
url(r'^login/$', views.UserLoginFormView.as_view(), name="user_login"),
url(r'^products/$', views.ProductsView, name="products"),
]
login.html
<form class="cozy" action="" method="post">
{% csrf_token %}
<div class="form-group control">
<label for="username" class="control-label">Username</label>
<input type="text" name="username" id="username" class="form-control">
</div>
<div class="form-group control">
<label for="password" class="control-label">Password</label>
<input type="password" name="password" id="password" class="form-control">
</div>
{% if form.errors %}
<p class=" label label-danger">
Your username and password didn't match. Please try again.
</p>
{% endif %}
<div class="d-flex align-content-center justify-content-center">
<button type="submit" class="btn btn-lg btn-accent">Login</button>
</div>
</form>
Console Output
System check identified no issues (0 silenced).
January 25, 2019 - 15:39:24
Django version 1.11.18, using settings 'svcreporter.settings'
Starting development server at http://127.0.0.1:9000/
Quit the server with CTRL-BREAK.
[25/Jan/2019 15:39:28] "GET /home/login/ HTTP/1.1" 200 4490
[25/Jan/2019 15:39:34] "POST /home/login/ HTTP/1.1" 302 0
[25/Jan/2019 15:39:34] "GET /home/ HTTP/1.1" 200 17242
You missed the as_view() part in:
urlpatterns = [
url(r'^$', views.HomeView, name='home'),
# ...
]
it should be:
urlpatterns = [
url(r'^$', views.HomeView.as_view(), name='home'),
# ...
]
and I would say that in some point you'll be struggling with this too:
# Add .as_view() to views.ProductsView
url(r'^products/$', views.ProductsView, name="products")
I have created a "Subscribe" form using Wagtail form builder, with one email field that is required, I have also created a template tag to use this form in different places on the web site.
The problem:
If the user submits the form with an incomplete email address, I'll get a validation error (which is expected). However, if the user submits the form without providing an email address, wagtail sends the user to the actual form url and prompts the user to fill out the form again.
The behavior should be, that if the form is submitted without an email address, a validation error should be triggered as well, this is not happening.
Here is the form model code:
class FormField(AbstractFormField):
page = ParentalKey('SubscribeForm', related_name='form_fields')
class SubscribeForm(AbstractEmailForm):
intro = RichTextField(blank=True)
thank_you_text = RichTextField(blank=True)
content_panels = AbstractEmailForm.content_panels + [
FieldPanel('intro', classname="full"),
InlinePanel('form_fields', label="Form fields"),
FieldPanel('thank_you_text', classname="full"),
MultiFieldPanel([
FieldPanel('to_address', classname="full"),
FieldPanel('from_address', classname="full"),
FieldPanel('subject', classname="full"),
], "Email")
]
Here is the custom template tag code:
from django import template
from home.models import *
register = template.Library()
# Subscribe
#register.inclusion_tag('home/subscribe_form.html', takes_context=True)
def vdecristo_subscribe(context):
page = SubscribeForm.objects.get(slug='subscribase')
return {
'request': context['request'],
'page': page,
'form': page.get_form(),
}
Here is the html code:
{% load wagtailcore_tags vdecristo_tags %}
<!-- Callout Subscribe Form Green -->
<div class="shop-subscribe bg-color-green margin-bottom-40">
<div class="container">
<div class="row">
<div class="col-md-8 md-margin-bottom-20">
<h2>Subscribase para mantenerse<strong> informado</strong></h2>
</div>
<form action="{% pageurl page %}" method="POST">
{% csrf_token %}
<div class="col-md-4">
<div class="input-group">
<input id="id_subscribase" class="form-control" placeholder="Correo Electronico..." name="subscribase"
type="email">
<span class="input-group-btn">
<button class="btn" type="submit"><i class="fa fa-envelope-o"></i></button>
</span>
</form>
</div>
</div>
</div>
</div><!--/end container-->
</div>
Can somebody shed some light on this issue?
Hard to know without seeing your views.py code, but reloading the empty form is the kind of thing that happens when the if request.method == 'POST' ... portion of the view isn't receiving the request.POST form data.