URLS Django not working - python

I am trying to create a user form and then post the input to the database model.However I keep getting this error message
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/hiresite/Recruiter
Using the URLconf defined in recruitment.urls, Django tried these URL patterns, in this order:
^hiresite ^$ [name='index']
^hiresite ^Recruiter$ [name='Recruiter']
^admin/
The current URL, hiresite/Recruiter, didn't match any of these.
I am a bit confused because I can see the url Recruiter above and yet I get the error message.Your help would be much appreciated .
1.Here is my Urls.py for the app
from django .conf.urls import url
from. import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^Recruiter$', views.Recruiter, name='Recruiter')
]
2.Here is my Urls.py for the Project
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^hiresite', include('hiresite.urls')),
url(r'^admin/', admin.site.urls),
]
3.Here is the view for the Url Recruiter
def Recruiter(request):
if request.method == 'POST':
form = register_job(request.POST)
if form.is_valid():
title = request.POST.get('title', ' ')
description = request.POST.get('description', ' ')
salary = request.POST.get('salary', ' ')
reference = request.POST.get('reference', ' ')
user_obj = jobsearch(title=title, description=description, salary=salary, reference=reference)
user_obj.save()
return render(request, 'hiresite/Recruiter.html', {'user_obj ': user_obj, 'is_registered': True})
else:
form = register_job()
return render(request, 'hiresite/Recruiter.html', {'form': form})
4.Here is the Html template file used in the views.py file for the Url Recruiter
!DOCTYPE html>
<html lang="en">
<head>
<title>Learning Html the Hard way</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
{% load staticfiles %}
<link rel='stylesheet' href= " {% static 'css/bootstrap.min.css' %}" type = 'text/css'/>
</head>
<body>
 <form action="{% url 'hiresite:Recruiter' %}" method="post">
    {% csrf_token %}
   {{ form }}
    <input type="submit" value="Submit">
    </form>
</body>
</html>

convert this line :
url(r'^hiresite', include('hiresite.urls')),
To this line :
url(r'^hiresite/', include('hiresite.urls')),

Related

Django stops updating data to mysql after page refresh

I'm fairly new to using the django framework and recently I made a system with it where it submits data to mysql db through a html form. I got it working eventually and everything seemed quite fine, though I noticed a bug where if I refresh the page django stops sending data to mysql, has this ever happened to anyone?
Stuff for reference:
views.py
from django.shortcuts import render
from websiteDB.models import dbInsert
from django.contrib import messages
def insertToDB(request):
if request.method == "POST":
if request.POST.get('uname') and request.POST.get('email') and request.POST.get('message'):
post = dbInsert()
post.uname = request.POST.get('uname')
post.email = request.POST.get('email')
post.message = request.POST.get('message')
post.save()
messages.success(request, "Message sent successfully.")
return render(request, "contact.html")
else:
return render(request, "contact.html")
models.py
from django.db import models
class dbInsert(models.Model):
uname = models.CharField(max_length=100)
email = models.EmailField()
message = models.TextField()
class Meta:
db_table = "contactrequest"
urls.py
"""
websiteDB URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.views.generic import TemplateView
from . import views
from . import index
urlpatterns = [
#path('admin/', admin.site.urls),
path('homepage', index.page_home, name= 'hpage'),
path('', views.insertToDB),
path('contactpage', index.contact_page, name= 'cpage')
]
contact.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Outfit:wght#200&display=swap" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="{% static 'css/css/styles.css' %}">
<title>Document</title>
</head>
<body style="background-color: rgb(74, 36, 110);">
<script src="{% static 'js/main.js' %}"></script>
<div class="top-nav">
HOME
PRODUCTS
CONTACT
ABOUT
COMMUNITY
</div>
<div class="div-align">
<h2>Contact</h2>
<p>Reach us for questions/concerns through the form below.</p>
</div>
<form class="fontmaker" method="post">
{% csrf_token %}
<label for="Username">Username:</label><br>
<input type="text" id="Username" name="uname" required><br>
<label for="E-mail">E-mail:</label><br>
<input type="text" id="Email" name="email" required>
<label for="Reason" class="margin">Message:</label>
<textarea id="Reason" name="message" rows="10" cols="60" required>Type your reason of contact here.</textarea>
<input type="submit" value="Submit" class="rounded-corners" id="submitBtn">
{% if messages %}
{% for message in messages %}
{{message}}
{% endfor %}
{% endif %}
</form>
</body>
</html>
There are no errors in terminal, and the button click also properly sends a POST req:
Terminal output
I'm also new to posting on stackoverflow, tell me if there's something else to improve on in the future when posting.
index.py
from django.http import HttpResponse
from django.shortcuts import render
def page_home(request):
return render(request, 'index.html')
def contact_page(request):
return render(request, 'contact.html')
Thanks in advance.
If you render the contactpage/ URL, then if you submit the form, you will submit it to the contact view, but that view does not handle the data, nor does it create any entry. You must make sure that you post the form to the insertToDB view. You can do this by giving the view a name:
urlpatterns = [
# …,
path('', views.insertToDB, name='insertToDB'),
# …
]
and then specify the endpoint in the form:
<form class="fontmaker" method="post" action="{% insertToDB %}">
<!-- … -->
</form>
In case of a successful POST request, you should also redirect, for example with:
from django.shortcuts import redirect
def insertToDB(request):
if request.method == 'POST':
if request.POST.get('uname') and request.POST.get('email') and request.POST.get('message'):
post = dbInsert.objects.create(
uname = request.POST['uname'],
email = request.POST['email'],
message = request.POST['message']
)
messages.success(request, 'Message sent successfully.')
return redirect('cpage')
return render(request, 'contact.html')
else:
return render(request, 'contact.html')
I would advise to work with Django forms [Django-doc], for example a modelform [Django-doc] to validate and clean form input and remove a lot of boilerplate code.

not able to upload and display django form

1.views.py
from django.shortcuts import render
from . models import User
from .forms import Userform
def Home(request):
if request.method == "POST":
form = Userform(request.POST or None,request.FILES or None)
if form.is_valid():
form.save()
else:
form = Userform()
return render(request,"home.html",{"form":form})
def read(request):
read = User.objects.all()
return render(request,"read.html",{"read":read})
2.models.py
from django.db import models
class User(models.Model):
name = models.CharField(max_length=12)
rollno = models.IntegerField()
# files = models.FileField()
3.form.py
from django import forms
from .models import User
class Userform(forms.ModelForm):
class Meta:
model = User
fields = ('name','rollno')
urls.py
from django.contrib import admin
from django.urls import path
from app import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path("",views.Home,name="Home"),
path("read/",views.read, name="read"),
]
urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
4.home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form method="POST" action="read/" enctype="multipart/form-data">
{%csrf_token%}
{{form}}
<button type=submit>click to submit</button>
</form>
</body>
</html>
read.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
{%block containt%}
{%for i in read%}
{{i.name}}
{{i.rollno}}
{%endfor%}
{%endblock%}
</body>
</html>
i want to add data to django admin using a form but data is not uploading at django admin
Not able to upload data into django admin hence cant read it
please help
i want to add data to django admin using a form but data is not uploading at django admin
Not able to upload data into django admin hence cant read it
please help
Problem is in the action of your form, you have entered the wrong URL in the action
You have to put home URL instead of read/, because you are handling your form submission in your home function so replace your form action by this
<form method="POST" action="{% url 'Home' %}" enctype="multipart/form-data">
{%csrf_token%}
{{form}}
<button type=submit>click to submit</button>
</form>

why request.GET.get() returns 'None' and value of html element is not visible in URL

index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HELLO</title>
</head>
<body>
<form action="/removepunc", method="get">
<input type="text",name='text' value="Hello,Django" />
<input type="submit">
</form>
</body>
</html>
views.py
from django.http import HttpResponse
from django.shortcuts import render
def index(request):
return render(request,'index.html')
def removepunc(request):
print("Text is :"+request.GET.get('text','default'))
return HttpResponse("Hello")
urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.index,name='index'),
path('removepunc',views.removepunc,name='rempunc')
]
This is first screen after run the code
When I click on submit in Url it did not show "hello django"
Also in terminal it print default not "hello django"
There is a comma in your <input> box between "text" and name.
The <input> tag should thus look like:
<input type="text" name="text" value="Hello,Django" />
not:
<input type="text",name='text' value="Hello,Django" />

Displaying Audio/Video in Python Django Website

I am building a blog website where I can upload audio/video files to the database and then run a for loop to output the files in HTML audio/video tags. I have succeeded in saving the files to the database and also output them on the website but for some reason I can't get them to play.
I am still pretty new to Python/Django and I would appreciate it if anybody can help me figure this one out. Thanks in anticipation
Here is my models.py
from django.db import models
class Track(models.Model):
track_title = models.CharField(max_length=250)
track = models.FileField(upload_to='album/')
def __str__(self):
return self.track_title
Here is my index.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
{% for track in tracks %}
<figure>
<figcaption>Audio</figcaption>
<audio controls>
<source src="{{ track.track.url }}" type="audio/mp3">
</audio>
</figure>
{% endfor %}
This is my views.py
from django.shortcuts import render
from .models import Track
def songView(request):
tracks = Track.objects.all()
context = {
'tracks':tracks
}
return render(request, 'album/index.html', context)
And my urls.py
from django.urls import path
from . import views
app_name = 'album'
urlpatterns = [
path('', views.songView, name='song'),
]

Download files in django from database and also view pdf file in that

Well, I am trying to make a simple app in django in which I upload files from admin panel. The user is greeted with a simple search page in which he enters an id which thus needs to produce the related file. The file is to be in pdf format. So if there is a way I could view the pdf file in the browser and a download button which downloads the file. The code is hosted on Github, the link is https://github.com/tahseen09/delhipatho
Add STATIC_ROOT = '/static/' to your settings.py
urls.py
urlpatterns = [
path('',views.index, name='index'),
path('admin/', admin.site.urls),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py
from report.models import query
def index(request):
if request.method == "POST":
form = Form(request.POST)
if form.is_valid():
query = query.objects.filter(id__exact =form.cleaned_data['id'])
return render(request, 'ans.html', {'query':query})
else:
form = Form()
return render(request,"index.html", {'form':form})
ans.html
{% load static %}
<!DOCTYPE HTML>
<html>
<head>
<title>Delhi Patho</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="stylesheet" href="{% static 'assets/css/main.css' %}" />
</head>
<body class="is-preload">
<p><a href="{{query.repo.url}}">Download</p>
<!-- Scripts -->
<script src="{% static 'assets/js/main.js' %}"></script>
</body>
</html>

Categories

Resources