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
Related
I am trying to display a static image in django. When I select image using django admin portal then it's works fine. it is displaying image. But when I select image from my front-end page, I get:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/media/destination-2.jpg
Raised by: django.views.static.server
Here are my codes:
urls.py
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from mainapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('mainapp.urls')),
]
admin.site.site_header = "Login to our web Portal"
admin.site.site_title = "This is Admin Portal"
admin.site.index_title = "Welcome to Amnet"
#urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
settings.py
STATICFILES_DIRS=[os.path.join(BASE_DIR,'static')
]
MEDIA_URL='/media/'
MEDIA_ROOT=os.path.join(BASE_DIR,'media')
models.py
from django.db import models
# Create your models here.
class Amnet(models.Model):
imagee = models.FileField(default='bg_2.jpg')
views.py
from django.shortcuts import render
from mainapp.models import Amnet
# Create your views here.
def index(request):
if(request.method == "POST"):
imagee= request.POST.get('imagee')
am = Amnet(imagee=imagee)
am.save()
return render(request,'image-main.html')
else:
return render(request,'image-main.html')
html page
<form action="" method="POST">
{% csrf_token %}
<td><input type="file" name="imagee" id="file"></td>
<td><img src="" id="profile-img-tag" width="200px" /></td>
</tr>
</table>
<input type="Submit" value="Submit" id="btn"><br>
</form>
Use enctype="multipart/form-data" to handle file uploads. Add this attribute in the form tag in HTML
I'm making a web app in django and currently I'm facing this problem. I have a dashboard page and an upload page. There's a button in dashboard page which links to the upload page. but whenever I click the button then the upload page url appends the dashboard page.
below is the code:
views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from .models import Registration
from .forms import UploadForm
from django.urls import reverse
# Create your views here.
def homepage(request):
return render(request, 'index.html', {})
def dashboard(request):
posts = Registration.objects.all()
return render(request, "dashboard.html", {'posts': posts})
def upload(request):
form = UploadForm()
return render(request, "upload.html", {'form': form})
def uploadimage(request):
if request.method == 'POST':
form=UploadForm(request.FILES['image'], request.POST)
if form.is_valid():
pic = request.FILES['image']
desc = request.POST
post = Registration(pic='pic', desc='desc')
post.save()
urls.py
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
path('', views.homepage, name='homepage'),
path('dashboard/', views.dashboard, name='dashboard'),
path('upload/', views.upload, name='upload'),
path('create/', views.uploadimage, name='uploadimage'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
dashboard.html
<div class="profile">
<div class="left-s col s12 m3 l3">
<div class="profile-overview">
<img src="{%static 'images/group.jpg' %}" alt="profile-pic" class="circle responsive-img">
<p>Daljit Singh</p>
<p>Lorem ipsum dolor sit amet.</p>
</div>
<hr>
<div class="container">
<ul>
<li>About</li>
<li>Friends</li>
<li>Photos</li>
<li>Likes</li>
</ul>
</div>
<hr>
<button>Upload post</button>
</div>
error:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/dashboard/upload/
Using the URLconf defined in main.urls, Django tried these URL patterns, in this order:
[name='homepage']
dashboard/ [name='dashboard']
upload/ [name='upload']
create/ [name='uploadimage']
^media\/(?P<path>.*)$
The current path, dashboard/upload/, 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.
Help would be appreciated.
It should be - Upload post
If you enter '/' (/upload/) before the path it will append to the base URL and if '/' (upload/) doesn't exist then it will append to the existing path.
Or the Different way suggested in the comment -
Upload post
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.
I am a beginner and did a lot of search but every time I got only "django to html" as search result every time. I am following this tutorial:
http://www.djangobook.com/en/2.0/chapter07.html
but on the way I am not able to pass paramter from html to view.py.
Here is my directory:
directory: mysite:
directory: books
directory: templates
search_form.html
<html>
<head>
<title>Search</title>
</head>
<body>
<form action="/search/" method="get">
<input type="text" name="q">
<input type="submit" value="Search">
</form>
</body>
</html>
views.py
from django.shortcuts import render
from django.http import HttpResponse
def search_form(request):
return render(request, 'books/search_form.html')
def search(request):
if 'q' in request.GET:
message = 'You searched for: %r' % request.GET['q']
else:
message = 'You submitted an empty form.'
return HttpResponse(message)
urls.py for books
from django.conf.urls import url,include
from . import views
urlpatterns = [
url(r'^$',views.search_form,name='search_form'),
url(r'^$', views.search,name='search'),
]
and urls.py in mysite directory
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/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. Add an import: from blog import urls as blog_urls
2. Import the include() function: from django.conf.urls import url, include
3. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import url,include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^books/', include('books.urls')),
]
Now the problem is when I type: http://127.0.0.1:8000/books/
it successfully shows the form's textbox and submit button but when I press submit it shows me this:
Firstly, you need two different regexes for the search_form and search results. For example:
url(r'^$',views.search_form,name='search_form'),
url(r'^search/$', views.search,name='search'),
Next, you need to update the form's action to point to the search view. Since you have included your books/urls.py with the /books/ prefix, you need:
<form action="/books/search/" method="get">
It is better to use the url tag instead of hardcoding your urls. In this case, you would do:
<form action="{% url 'search' %}" method="get">
In addition to the answer of Alasdair I would use "books:search" for clear namespace:
<form action="{% url 'books:search' %}" method="get">
The url /search/ doesn't exist, you didnt define that it should exist.
It would be /books/ judging from that URLs file you showed. Also on a side note, don't use http://www.djangobook.com/en/2.0/index.html
They have a warning on the main page that it is no longer up to date.
Use masteringdjango.com and other up to date resources.
this NoReverseMatch error is driving me nuts. I'm using Django 1.6 and I have checked through my urls and it just doesn't work. Please kindly guide me on this.
I basically want to do something deadly simple, just when I submit a html form, I get the data I want and then redirect to a result page, but it just doesn't work...
Here is my index.html file
<form name="input" action="{% url 'whatspring:sending' %}" method="post">
{% csrf_token %}
Recipient: <input type="text" name="usrname">
<br>
<input type="submit">
</form>
<br>
my view.py
def index(request):
return render(request,'springsend/index.html')
def sending(request):
var = request.POST['usrname']
doSomethinghere()
return HttpResponseRedirect(reverse('whatspring:results'))
def results(request):
return render(request,'springsend/send_results.html')
then my app urls.py
from django.conf.urls import patterns, url
from springsend import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^results/$', views.results, name='results'),
)
and the main urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^send/', include('springsend.urls', namespace="whatspring")),
)
I have tried to look into the problem and it seems that the reverse function cannot get the name for the reverse url that I want (i.e. 'results' under the namespace 'whatspring'....)Am I missing something something trival? Please kindly help.
Your urls.py (springsend one) doesn't seem to have a url for the sending view, that's probably why {% url 'whatspring:sending' %} can't find it.
Simply change it to
from django.conf.urls import patterns, url
from springsend import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^results/$', views.results, name='results'),
url(r'^sending/$', views.sending, name='sending'), # this line
)
Every accessible view needs a url. The user's browser needs to have some address to send things. If it would just send it to your domain without url, Django would have no way to tell which url is requested. Django does not auto-generate these urls (which is probably good).
(The user himself does not need to know this url; you don't need to place any ` links anywhere.)