Django Method Not Allowed (POST) - django

In views:
def article_add(request):
print request.user, " is adding an article"
if request.method == "POST":
web_url = request.POST['web_url']
Uploadarticle(web_url)
return redirect('myapp:index')
In html:
<form class="navbar-form navbar-right" role="form" method="post" action="{% url 'myapp:article_add' %}" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<div class="col-sm-10">
<input id="article_url" name="web_url" type="text">
</div>
</div>
<button type="submit" class="btn btn-default"> + </button>
</form>
In url.py:
app_name = 'myapp'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^$', views.article_add, name='article_add'),
]
What i'm trying to do here is to pass the url value through html to view, call the function to upload the database, redirect the user to the same home page as refresh then the newly added item will show up.
Somehow everytime I submit I got a blank page, in terminal I got an errors says:
Method Not Allowed (POST): /
"POST / HTTP/1.1" 405 0

As I can see in the code, you are using same URL for both view, so, whenever you hit URL /, the request goes to first view(IndexView) which probably does not have any post method. Change the URL for article_add view. Do like this:
app_name = 'myapp'
urlpatterns = [
url(r'^article-add/$', views.article_add, name='article_add'),
url(r'^$', views.IndexView.as_view(), name='index'),
]
You will be able to access view from URL {host_address}/article-add/

There is small mistake in your urls.py change your urls.py following way
app_name = 'myapp'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^article-add/$', views.article_add, name='article_add'),
]
if you are incuded the 'myapp' urls.py in the main project urls.py then in the form in html just put action="{% url 'article_add' %}" this way also.

Related

Is this login fail? or? [duplicate]

This question already has answers here:
How to submit a form without having the values shown in the URL?
(4 answers)
Closed 3 months ago.
when click login the page no blank to home page just stay in login page
the terminal show me "GET /login/?csrfmiddlewaretoken=LK82SQKdzu802NaUuXom8CWRn3S86WWK0XrzEqFCCrUmGGCe06MXoMgFtt0JLDRN&username=tim&password=tim123 HTTP/1.1" 200 3148 and the browser link this http://127.0.0.1:8000/login/?csrfmiddlewaretoken=MWNadf5CSlSmTnCFIlJ5aoJDKHL1ShJJ196HZP01ViEIxg4Zeu7Gqy3rQ7TCxYEM&username=tim&password=tim123
login.html
{% extends "main/base.html" %}
{% block title %}
Login Here
{% endblock title %}
{% load crispy_forms_tags %}
{% block content %}
<form class="from-group" method="get">
{% csrf_token %}
{{form | crispy}}
<button type="submit" class="btn btn-success">Login</button>
<p>Don't have an account? Create one Here</p>
</form>
{% endblock content %}
settings.py (i just skip to STARIC it so long
STATIC_URL = 'static/'
CRISPY_TEMPLATE_PACK = "bootstrap4" (add)
LOGIN_REDIRECT_URL = "/" (add)
urls.py
from django.contrib import admin
from django.urls import path, include
from register import views as v
urlpatterns = [
path('admin/', admin.site.urls),
path('register/', v.register, name='register'),
path('', include('main.urls')),
path('', include('django.contrib.auth.urls')),
]
I think you got this message in terminal because of using get method in Html form.
For login form, the request method must be POST not GET.
Instead of this:
<form class="from-group" method="get">
Try this:
<form class="from-group" method="POST">

Reverse for 'register' not found. 'register' is not a valid view function or pattern name

I'm trying to make a simple app that uses the django built-in User model. I have created a registration page, but when I run the server, I get this error at the index page. Here's the code I'm using:
Registration.html
<!DOCTYPE html>
{% extends "basic/base.html" %}
{% block title_block %}
<title>Registration</title>
{% endblock title_block %}
{% block body_block %}
<div class="jumbotron">
{% if registered %}
<h1>Thank you for registering</h1>
{% else %}
<h1>Register here!</h1>
<h3>Fill out the form: </h3>
<form enctype="multipart/form-data" method="post">
{% csrf_token %}
{{userForm.as_p}}
{{profileForm.as_p}}
<input type="submit" value="Register" name="">
</form>
{% endif %}
</div>
{% endblock body_block %}
Views.py for the 'register' method
def register(request):
registered = False
if(request.method == 'POST'):
userForm = forms.UserForm(data=request.POST)
profileForm = forms.UserProfileInfoForm(data=request.POST)
if((userForm.is_valid()) and (profileForm.id_valid())):
user = userForm.save()
user.set_password(user.password)
user.save()
profile = profileForm.save(commit=False)
profile.user = user
if('profileImage' in request.FILES):
profile.profileImage = request.FILES['profileImage']
profile.save()
registered = True
else:
print(userForm.errors, profileForm.errors)
else:
userForm = forms.UserForm()
profileForm = forms.UserProfileInfoForm()
return render(request, 'basic/registration.html', {'userForm':userForm, 'profileForm':profileForm, 'registered':registered})
This is the urls.py for the project
from django.contrib import admin
from django.urls import path, include
from basic import views
urlpatterns = [
path('', views.index, name='index'),
path('admin/', admin.site.urls),
path('basic/', include('basic.urls', namespace='basic'))
]
This is the urls.py for the basic app
from django.urls import path
from . import views
app_name = 'basic'
urlpatterns = [
path('register/', views.register)
]
And the link to the page in base.html
<a class="nav-link" href="{% url 'basic:register' %}">Register</a>
What can cause the error here?
You must include a name argument to the register route.
path('register/', views.register, name='register')
https://docs.djangoproject.com/en/2.1/topics/http/urls/#reverse-resolution-of-urls
try this (inside your html file)
<a class="nav-link" href={% url 'basic:register' %}>Register</a>
and your urls.py (inside your app) as this:
urlpatterns = [
path('register/', views.register,name='register'),
]
this method worked for me I was fasing the same issue.

error while using "django.contrib.auth.views.login"

i am getting error "view must be a callable or a list/tuple in the case of include()." while trying to use django's built-in Login system (login,logout,logout_then_login). can anyone please sort this out.
bookmarks/accounts/urls.py-
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^login/$', 'django.contrib.auth.views.login', name='login'),
url(r'^logout/$', 'django.contrib.auth.views.logout', name='logout'),
url(r'^logout-then-login/$', 'django.contrib.auth.views.logout_then_login',
name='logout_then_login'),
]
bookmarks/urls.py-
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^account/',include("account.urls"))
]
templates/registration/login.html-
<body>
<h1>Log-in</h1>
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% else %}
<p>Please, use the following form to log-in.
{% endif %}
<div class="login-form">
<form action="{% url "login" %}" method="post">
{{ form.as_p }}
{% csrf_token %}
<input type="hidden" name="next" value="{{ next }}" />
<p><input type="submit" value="Log-in"></p>
</form>
</body>
templates/registration/logged_out.html-
<h1>Logged out</h1>
<p>You have been successfully logged out. You can <a href="{% url "login"
%}">log-in again</a>.</p>
</body>
I am assuming you are using django>1.9: So you cannot use strings as views anymore. So you need to do something like this with all views:
from django.contrib.auth.views import login
#.....
url(r'^login/$', login, name='login'),
...
And also with the include:
from django.contrib import admin
from accounts import urls
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^account/',include(urls))
]

Django form POST with NoReverseMatch error

In html:
<form role="form" method="post" action="{% url 'myapp:add_review' %}" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<div class="col-sm-10">
<input id="review" name="review" type="text">
</div>
</div>
<button type="submit" class="btn btn-default"> Submit </button>
</form>
In views:
def add_reviews(request):
if request.method == "POST":
print "Post is here:", request.POST['review']
return render(request, 'myapp/single_item.html')
//or this?? return redirect('myapp:single_item')
In urls.py
app_name = 'myapp'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
# register, login, logout
url(r'^register/$', views.UserFormView.as_view(), name='register'),
url(r'^login/$', views.login_user, name='login'),
url(r'^logout/$', views.logout_user, name='logout'),
# individual article page
url(r'^(?P<item_id>[0-9]+)/$', views.single_item, name='single_item'),
url(r'^(?P<item_id>[0-9]+)/add_review/$', views.add_review, name='add_review'),
]
Really basic stuff, in each individual item page, I want a form to write and post reviews for each item, and go back to the same item page.
When I'm in the individual item page, gives me the following error:
Reverse for 'add_review' with arguments '('',)' and keyword arguments '{}' not found.
1 pattern(s) tried: ['(?P<item_id>[0-9]+)/add_review/$']
Generally, these types of errors indicate that something is not right with an URL, that such pattern was not found, that it misses some parameters and so forth. From this particular error it seems that you are not passing item_id to the url matcher. Hence, Django cannot find an appropriate URL. You have:
url(r'^(?P<item_id>[0-9]+)/add_review/$', views.add_review, name='add_review')
Notice that you wrote ?P<item_id>[0-9]+)/..., which means you must provide item_id whenever you want this URL to be resolved. Try adding item_id as a keyword argument:
<form role="form" method="post" action="{% url 'myapp:add_review' item_id= ... %}" enctype="multipart/form-data">
This should construct a valid url (e.g., .../1/add_review/), which should be recognised by Django. However, I believe your add_review() function will also need to take an item_id argument, otherwise you might get TypeError due to unexpected function arguments.
As for the return value, I would use redirect instead of render, as you are, well, redirecting after a successful POST. Though you might need to pass a item_id, too, since your URL config specifies that: a) URL should have item_id and b) single_item() expects item_id. Something like this should work:
def add_review(request, item_id):
...
return redirect('myapp:single_item', {'item_id': item_id})
And signature of single_item should be something like this: single_item(request, item_id).

Can't use request 'get' in django

I am using django, and want to get simple 'get' request from server. It seems like view is taking it, and in console it have code '200'. But in view I try to check it someway, but I can't. Can somebody tell my what I am doing wrong.
This is my view:
def check_register(request):
if request.GET.get("sign_mail"):
return HttpResponse("YEAH, GET")
else:
return HttpResponse("no didn't")
My form:
<form action="/checkRegister/" method="GET">
<input class="header_input" type="text" size="25" name="sign_mail" placeholder="Email">
<button class="sign_btn" type="submit">ВОЙТИ</button>
</form>
My urls:
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'$', views.index),
url(r'^checkRegister/$', views.check_register),
]