Django: Page not found , Raised by:django.views.static.serve - python

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

Related

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

I am Working on my project and I don't know how this error I got
Can anybody see what I'm missing?
This is my root project urls.py
from django.contrib import admin
from django.urls import path, include
from .import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index),
path('onlinePizza/', include('onlinePizza.urls')),
path('cart/', include(('cart.urls'), namespace='cart')),
path('accounts/', include(('accounts.urls'), namespace='accounts')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This is my cart app urls.py
from django.urls import path
from .import views
from cart.views import AddCart
app_name = 'cart'
urlpatterns = [
path('add_cart/', views.AddCart, name='Cart'),
]
This is my cart app views.py
from django.shortcuts import render, redirect
from cart.models import *
def AddCart(request):
product = request.POST.get('product')
remove = request.POST.get('remove')
cart = request.session.get('cart')
if not cart:
request.session['cart'] = {}
if cart:
quantity=cart.get(product)
if quantity:
if remove:
if quantity<=1:
cart.pop(product)
else:
cart[product]=quantity-1
else:
cart[product]=quantity+1
else:
cart[product]=1
else:
cart={}
cart[product]=1
request.session['cart']=cart
return redirect ('Menu')
This is my onlinePizza/pc_menu.html template
<form action="{% url 'cart:AddCart' %}" method="POST">{% csrf_token %}
<input hidden type="text" name="product" value="{{i.id}}">
<button class="main-btn cart cart-btn" style="padding: 5px 32px">Add <i class="fa-solid fa-cart-shopping"></i></button>
</form>
I try to solve this problem, but I show this error everywhere in my project.
You need that name:
urlpatterns = [
path('add_cart/', views.AddCart, name='Cart'),
]
and that link generator:
{% url 'cart:AddCart' %}
refering to the exactly same value. So it has to be either 'Cart' and 'cart:Cart' or 'AddCart' and 'cart:AddCart'.

how to make custom form without database - DJANGO

So i want to upload file but only sent to locals storage NOT DATABASE too. But i don't know how to make custom forms.
suddenly, here's my models.py :
from django.db import models
class Audio_store(models.Model):
record=models.FileField(upload_to='mp3/')
forms.py :
from django import forms
from .models import Audio_store
class AudioForm(forms.ModelForm):
class Meta:
model = Audio_store
urls.py :
from django.contrib import admin
from django.conf.urls import url
from . import views
from django.urls import path, re_path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^decode/$', views.decode),
url(r'^$', views.homepage),
path('audio', views.Audio_store),
]
if settings.DEBUG: #add this
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
fields= ['record']
html:
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{form}}
<button type="submit" class="dsnupload">
<i class="large material-icons" style="font-size: 50pt; margin-top: 10px;">audiotrack</i>
<p style="font-weight: bold; color: white;">Insert file audio (mp3)</p>
</button>
</form>
Django has forms.ModelForm which requires DB model and forms.Form which you can use without any model.
https://docs.djangoproject.com/en/4.0/topics/forms/#the-form-class
from django import forms
class YourForm(forms.Form):
upload_file = forms.FileField()
for the fileinput refer https://docs.djangoproject.com/en/4.0/ref/forms/fields/#django.forms.FileField

Unable to render form in Django

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.

Django-CMS - Django Model Form not rendering

I'm building a new site in Django with Django-CMS that needs a form to filter JSON results and return the filtered set.
My issue is that, initially, I can't even get the Django Model Form to render yet I can get the CSRF token to work so the form is technically rendering, but the inputs/fields aren't showing up at all.
models.py:
from django.db import models
from .jobs.jobs import *
roles = get_filters()
loc = roles[0]
j_type = roles[1]
industry = roles[2]
class Filter(models.Model):
country = models.CharField(max_length=255)
job_type = models.CharField(max_length=255)
industry = models.CharField(max_length=255)
search = models.CharField(max_length=255)
jobs/jobs.py
try:
from BeautifulSoup import BeautifulSoup
except ImportError:
from bs4 import BeautifulSoup
import urllib3
import json
http = urllib3.PoolManager()
def get_filters():
response = http.request('GET', 'http://206.189.27.188/eo/api/v1.0/jobs')
jobs = json.loads(response.data.decode('UTF-8'))
job_list = []
for job, values in jobs.items():
job_list.append(values)
roles_data = []
for job in job_list[0]:
roles_data.append(job)
roles_data = sorted(roles_data, key=lambda role : role["id"], reverse=True)
loc = []
j_type = []
industry = []
for role in roles_data:
loc.append(role['location'])
j_type.append(role['type'])
industry.append(role['industry'])
return loc, j_type, industry
views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import FilterForm
def index(request):
form = FilterForm()
context = {
'form': form,
}
return render(request, 'blog.html', context)
forms.py
from django.forms import ModelForm
from .models import Filter
class FilterForm(ModelForm):
class Meta:
model = Filter
fields = ['country', 'job_type', 'industry', 'search']
urls.py
from __future__ import absolute_import, print_function, unicode_literals
from cms.sitemaps import CMSSitemap
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.i18n import i18n_patterns
from django.contrib import admin
from django.contrib.sitemaps.views import sitemap
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.static import serve
from . import views
admin.autodiscover()
urlpatterns = [
url(r'^sitemap\.xml$', sitemap,
{'sitemaps': {'cmspages': CMSSitemap}}),
url(r'^accounts/', admin.site.urls),
url(r'^services/latest-roles/', views.filter_form, name="filter_form" )
]
urlpatterns += i18n_patterns(
url(r'^admin/', include(admin.site.urls)), # NOQA
url(r'^', include('cms.urls')),
)
# This is only needed when using runserver.
if settings.DEBUG:
urlpatterns = [
url(r'^media/(?P<path>.*)$', serve,
{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
] + staticfiles_urlpatterns() + urlpatterns
blog.html
{% extends 'includes/templates/layout.html' %}
{% load cms_tags i18n sekizai_tags zinnia %}
{% block main_content %}
{% include 'components-header-image.html' %}
<section class="module">
<div class="container">
<div class="row">
<div class="col-md-12 m-auto text-center">
<form action="POST" class="col-md-12">
{% csrf_token %}
{{ form.as_p }}
<button name="submit" class="btn btn-brand">Search</button>
</form>
{% get_all_roles%}
</div>
<div class="col-md-12">
<div class="space" data-MY="120px"></div>
</div>
<div class="col-md-12 flex-center text-center">
{% placeholder 'jobs-bottom-statement' %}
</div>
</div>
</div>
</section>
<!-- Image-->
{% include 'components-contact.html' %}
<!-- Image end-->
{% endblock %}
Sorry for the masses of information, just wanted to include anything anyone might need.
As I said, the CSRF token is displaying, nothing is throwing an error anywhere but it's just not displaying the fields at all.
Really appreciate any help or advice.
I'm 95% sure your view isn't being called.
You need to integrate your application as a CMS apphook or hard code your URLs into your root urls.py which is the easier integration test as it doesn't depend on CMS integration.
So Add your view to your URLs like this;
urlpatterns += i18n_patterns(
url(r'^admin/', include(admin.site.urls)), # NOQA
url(r'^blog/$', views.index, name='blog'),
url(r'^', include('cms.urls')),
)
Then go to localhost:8000/blog/ in your browser & you should hit your view.
To confirm you're hitting it you could make a simple amendment to your view;
def index(request):
form = FilterForm()
context = {
'form': form,
}
print "index hit"
return render(request, 'blog.html', context)
Then you'll see "index hit" in your console if your view is called.

Django urls.py not rendering correct template

This is my urls.py
"""s7h URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/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. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^articles/', include('article.urls')),
url(r'^',include('django.contrib.auth.urls')),
url(r'^projects/', include('project.urls')),
#Serve Media Files
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
#subscribe
url(r'^subscribe/$', 'article.views.subscribe'),
url(r'^verify/$', 'article.views.activateSubscriber'),
# user auth urls
url(r'^home/$', 's7h.views.home'),
url(r'^', 's7h.views.home'),
url(r'^accounts/login/$', 's7h.views.login'),
url(r'^accounts/auth/$', 's7h.views.auth_view'),
url(r'^accounts/logout/$', 's7h.views.logout'),
url(r'^accounts/loggedin/$', 's7h.views.loggedin'),
url(r'^accounts/invalid/$', 's7h.views.invalid_login'),
# user registration urls
url(r'^accounts/register/$', 's7h.views.register'),
url(r'^accounts/register_success/$', 's7h.views.register_success'),
url(r'^accounts/register_auth/$', 's7h.views.register_auth'),
url(r'^contact/$', 's7h.views.contact'),
]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
handler400 = 's7h.views.custom_400'
handler403 = 's7h.views.custom_403'
handler404 = 's7h.views.custom_404'
handler500 = 's7h.views.custom_500'
if not settings.DEBUG:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
This is my views.py
from django.shortcuts import render, render_to_response, RequestContext
from django.http import HttpResponseRedirect
from django.contrib import auth,messages
from django.core.context_processors import csrf
from django.template import RequestContext
from django.template.loader import get_template
from forms import MyRegistrationForm
from article.models import Article, ArticleCategory
from project.models import Project, ProjectCategory
def home(request):
args={}
article = Article.objects.earliest("-pub_date")
project = Project.objects.earliest("-pub_date")
article_category = ArticleCategory.objects.all()
project_category = ProjectCategory.objects.all()
args.update(csrf(request))
args['article'] = article
args['project'] = project
args['project_categories'] = project_category
args['article_categories'] = article_category
args['loggedin'] = request.session.get('email', None)
return render_to_response('home.html', args)
def login(request):
c = {}
c.update(csrf(request))
return render_to_response('login.html', c)
def auth_view(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
request.session['email'] = user.email
return render(request, "loggedin.html", locals(),context_instance=RequestContext(request))
else:
return HttpResponseRedirect('/accounts/invalid/')
def loggedin(request):
return render_to_response('loggedin.html', {})
def invalid_login(request):
return render_to_response('invalid_login.html')
def logout(request):
auth.logout(request)
return HttpResponseRedirect('/accounts/login/')
This is my template for login
{% extends "user_forms.html" %}
{% block title %}
S7H - Login
{% endblock %}
{% block main %}
<span class="fa fa-user bigicon"></span>
<h2>Enter Details</h2>
<form action = "/accounts/auth/" method = "POST">{% csrf_token %}
<p><input type="text" name="username" required placeholder="Username" autofocus></p>
<p><input type="password" name="password" required placeholder="Password"></p>
<button class="btn btn-default" type="submit" name="submit" />Sign In</button>
Sign Up
</form>
<small>Forgot your password?</small><br />
{% if messages %}
{% for message in messages %}
<small {% if message.tags %} class="{{message.tags}}" {% endif %}>{{message}}</small>
{% endfor %}
{% endif %}
{% endblock %}
Now when I do http://127.0.0.1:8000/accounts/login/ , Django should render login.html because url accounts/login/ leads me to def login(request): and there in render_to_response() I have mentioned login.html to get rendered but instead of it, Django renders my home.html file. URL of the browser changes to http://127.0.0.1:8000/accounts/login/ when I press the login button on my home page but it keeps on rendering the same home.html template.
This thing is happening with other urls also. Every url is rendering home.html template.
I double checked all my urls, views and templates, I have not been able to figure out my mistake. Django is also not giving any Exceptions and Error messages.
Also in the terminal the HTTP response is 200 OK :/
[08/Jun/2015 01:38:40]"GET /accounts/login/ HTTP/1.1" 200 10201
Help me!
Your s7h.views.home pattern has no terminating $ so it matches every URL.

Categories

Resources