Media files uploaded by the user are not getting displayed - html

Using django for rendering user uploaded data from a "/blogs/createblog" form web page to "/blogs" webpage, but the image file uploaded by the user is not getting displayed in his/her blogpost ("/blogs") page. My settings.py, base level/urls.py, app/models.py, app/views.py and the html templates are something like this:
settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
baseproject/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
from django.urls import re_path
from django.views.static import serve
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('home.urls')),
path('blogs/',include('blog.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
app/models.py
from django.db import models
from django.utils.timezone import now
from django.contrib.auth.models import User
# Create your models here.
class BlogPost(models.Model):
blog_id=models.AutoField(primary_key=True)
author=models.CharField(max_length=200)
title=models.CharField(max_length=300)
pub_date=models.DateField()
category=models.CharField(max_length=200,default="Promotional Blogs")
heading1=models.CharField(max_length=300,blank=True)
content1=models.TextField(blank=True)
heading2=models.CharField(max_length=300)
content2=models.TextField()
about=models.TextField()
likes=models.ManyToManyField(User, related_name="blogpost_like")
image=models.ImageField(upload_to="blog/images")
def number_of_likes(self):
return self.likes.count()
def __str__(self):
return self.title + " by " + self.author
app/views.py
def createblog(request):
if request.method=="POST":
author=request.POST.get("author")
title=request.POST.get("title")
today=date.today()
category=request.POST.get("category")
heading=request.POST.get("heading")
body=request.POST.get("body")
about=request.POST.get("about")
pic=request.POST.get("pic")
new_post=BlogPost(author=author,title=title,pub_date=today,category=category,heading2=heading,content2=body,about=about,image=pic)
new_post.save()
messages.success(request,"Your blog is published successfully.")
return redirect("/blogs")
return render(request,"blog/editor.html")
app/editor.html
{% extends 'blog/basic.html' %}
{% block title %}Editor - BlogLikho{% endblock %}
{% block body %}
<div class="container my-4">
<h1 class="mb-4" style="text-align:center;">Blog Editor</h1>
<form method="POST" action="/blogs/createblog">{% csrf_token %}
<div class="row">
<div class="mb-3 col-md-6">
<label for="author" class="form-label" style="font-weight: bold;">Author</label>
<input type="text" class="form-control" id="author" name="author" placeholder="" required>
</div>
<div class="mb-3 col-md-6">
<label for="title" class="form-label" style="font-weight: bold;">Title</label>
<input type="text" class="form-control" id="title" name="title" placeholder="Blog title" required>
</div>
</div>
<div class="mb-3">
<label for="category" class="form-label" style="font-weight: bold;">Category</label>
<select class="form-select" aria-label="Default select example">
<option selected>Open this select menu</option>
<option value="Coding Blogs">Coding Blogs</option>
<option value="Sports Blogs">Sports Blogs</option>
<option value="Traveling Blogs">Traveling Blogs</option>
<option value="Educational Blogs">Educational Blogs</option>
<option value="Business Blogs">Business Blogs</option>
<option value="Marketing Blogs">Marketing Blogs</option>
<option value="Technology Blogs">Technology Blogs</option>
<option value="Sales Blogs">Sales Blogs</option>
</select>
<input type="hidden" name="category" value="Coding Blogs">
</div>
<div class="mb-3">
<label for="heading" class="form-label" style="font-weight: bold;">Heading</label>
<input type="text" class="form-control" id="heading" name="heading" placeholder="" required>
</div>
<div class="mb-3">
<label for="body" class="form-label" style="font-weight: bold;">Body</label>
<textarea class="form-control" id="body" name="body" rows="4" required></textarea>
</div>
<div class="mb-3">
<label for="about" class="form-label" style="font-weight: bold;">About you</label>
<textarea class="form-control" id="about" rows="3" name="about" placeholder="Write a bit about yourself" required></textarea>
</div>
<div class="mb-3">
<label for="pic" class="form-label" style="font-weight: bold;">Blog display image</label>
<input class="form-control" type="file" id="pic" name="pic">
</div>
<button type="submit" class="publish btn btn-success">Publish</button>
</form>
</div>
{% endblock %}
app/yourblogs.html
{% extends "blog/basic.html" %}
{% block activeblogs %}active{% endblock %}
{% block title %}Blogs - BlogLikho{% endblock %}
{% load static %}
{% block body %}
<div class="container my-4">
<div class="row mb-2">
{% for blog_item in myblogs %}
<div class="col-md-6">
<div class="row g-0 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">
<strong class="d-inline-block mb-2 text-success">{{blog_item.author}}</strong>
<h4 class="mb-0">{{blog_item.title | truncatechars:25 }}</h4>
<div class="mb-1 text-muted">{{blog_item.pub_date}}</div>
<p class="card-text mb-auto" style="margin-bottom: revert!important;">{{blog_item.content1 | truncatewords:10}}</p>
<button type="button" class="btn btn-primary" style="width: fit-content;">Continue reading</button>
</div>
<div class="col-auto d-none d-lg-block">
<img src="/media/{{blog_item.image}}" class="bd-placeholder-img" width="250" height="250" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Thumbnail" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title>
</div>
</div>
</div>
{% endfor %}
{% endblock %}
What might be the problem?? The error which i am getting by clicking on the image url inside the specific BlogPost ImageField is..
404:Page not found
Please suggest me the solution.

Related

Django change password

Trying to change password using PasswordChangeView, but cannot get it working.
urls.py
from django.contrib.auth import views as auth_views
urlpatterns = [
path('profiles/settings/', update_profile, name='update_profile'),
path('profiles/settings/', auth_views.PasswordChangeView.as_view(template_name='accounts/settings.html'),
name='password_change'),
]
And i am trying to get the input fields correct in my html
<div class="tab-pane fade" role="tabpanel" id="password">
<form id="id_password_change_form" method="POST" class="form-signin">{% csrf_token %}
<div class="form-group row align-items-center">
<label class="col-3">Current Password</label>
<div class="col">
<input
type="password"
placeholder="Enter your current password"
name="old_password"
class="form-control"
id="id_old_password"
required="true" />
</div>
</div>
<div class="form-group row align-items-center">
<label class="col-3">New Password</label>
<div class="col">
<input
type="password"
placeholder="Enter a new password"
name="new_password1"
class="form-control"
id="id_new_password1"
required="true" />
<small>Password must be at least 8 characters long</small>
</div>
</div>
<div class="form-group row align-items-center">
<label class="col-3">Confirm Password</label>
<div class="col">
<input
type="password"
placeholder="Confirm your new password"
name="new_password2"
class="form-control"
id="id_new_password2"
required="true" />
</div>
</div>
{% for field in form %}
{% for error in field.errors %}
<p style="color: red">{{ error }}</p>
{% endfor %}
{% endfor %}
<div class="d-flex justify-content-end">
<button type="submit" class="btn btn-primary">Change Password</button>
</div>
</form>
There is no error, and it do not update the password as supposed to. according to PasswordChangeView, I should not need to alter anything.
I think you have a problem because of the wrong URLs definition, take a look at you urls.py:
from django.contrib.auth import views as auth_views
urlpatterns = [
path('profiles/settings/', update_profile, name='update_profile'),
path('profiles/settings/', auth_views.PasswordChangeView.as_view(template_name='accounts/settings.html'),
name='password_change'),
]
You always hit update_profile view instead of PasswordChangeView. I think this is typo.

Symfony - pass GET parameters to another route?

I have a table with filters, and i want to download the rows as csv, filtered.
My function to get filters from form:
public function getFilters($request)
{
$filters = [
'stato' => $request->get('stato'),
'cliente' => $request->get('cliente'),
'registrar' => $request->get('registrar'),
'creazione_inizio' => $request->get('creazione_inizio'),
'creazione_fine' => $request->get('creazione_fine'),
'scadenza_inizio' => $request->get('scadenza_inizio'),
'scadenza_fine' => $request->get('scadenza_fine'),
'scadenza_pagamento_inizio' => $request->get('scadenza_pagamento_inizio'),
'scadenza_pagamento_fine' => $request->get('scadenza_pagamento_fine'),
];
return $filters;
}
On the page where the table is i have this code and it works fine:
/**
* #Route("/dashboard", name="dashboard")
*/
public function dashboard(Request $request, PaginatorInterface $paginator): Response
{
$filters = $this->getFilters($request);
}
But on the route to export csv i have this and $filters is always null:
/**
* #Route("/report/report.csv", name="domains_data_csv")
*/
public function exportDomainsDataCsvAction(Request $request)
{
$filters = $this->getFilters($request);
}
I have the filters form and the button to download csv on the dashboard page.
Any tips to make it work?
EDIT
My dashboard page is made like this:
<div class="mb-2">
<span class="h2">Dashboard</span>
</div>
<div class="mb-3">
{{ include('Admin/includes/_search.html.twig') }}
</div>
{{ include('Admin/includes/_filter.html.twig') }}
{% if domains %}
<div class="col-auto">
Scarica CSV
</div>
{{ include('Admin/includes/_domains_table.html.twig',{ 'domains':domains }) }}
{% if is_granted('ROLE_ADMIN') %}
<a class="btn btn-primary" aria-current="page" href="{{path('new_domain')}}" role="button">Nuovo dominio</a>
{% endif %}
{% else %}
{% endif %}
Filters form:
<div class="card">
<div class="row align-items-center">
<a class="text-decoration-none text-reset" id="filter-header" href="#collapseExample" data-bs-toggle="collapse" aria-expanded="false">
<div class="card-header d-flex align-items-center">
<h5 class="pe-3">Filtri</h5>
<div class="border-1 bg-success border border-success w-100" style="opacity:unset;"></div>
<i class="bi bi-chevron-right ps-3 fs-3 text-success arrow"></i>
</div>
</a>
</div>
<div class="collapse" id="collapseExample">
<div class="card-body">
<form id="form-filter-status" method="GET">
{% if is_granted('ROLE_ADMIN') %}
<div class="row mb-3 justify-content-center">
<div class="card col-sm-3 mx-3">
<div class="card-body">
<div class="card-title">Stato:</div>
<div class="col-sm">
<select name="stato" class="form-select" onchange='this.form.submit();'>
<option value="" {% if filters.stato is empty %} selected {% endif %}>Seleziona...</option>
<option value="1" {% if filters.stato == 1 %} selected {% endif %}>Attivo</option>
<option value="2" {% if filters.stato == 2 %} selected {% endif %}>Richiesta Dismissione</option>
<option value="3" {% if filters.stato == 3 %} selected {% endif %}>Dismesso</option>
<option value="4" {% if filters.stato == 4 %} selected {% endif %}>Richiesto Trasferimento</option>
<option value="5" {% if filters.stato == 5 %} selected {% endif %}>Trasferito</option>
</select>
</div>
</div>
</div>
<div class="card col-sm-3 mx-3">
<div class="card-body">
<div class="card-title">Cliente:</div>
<div class="col-sm">
<select name="cliente" class="form-select" onchange='this.form.submit();'>
<option value="" {% if filters.cliente is empty %} selected {% endif %}>Seleziona...</option>
<option value="1" {% if filters.cliente == 1 %} selected {% endif %}>KINETIKON s.r.l.</option>
<option value="2" {% if filters.cliente == 2 %} selected {% endif %}>CINQUEBIT s.r.l.</option>
<option value="3" {% if filters.cliente == 3 %} selected {% endif %}>JAKALA S.p.A.</option>
<option value="4" {% if filters.cliente == 4 %} selected {% endif %}>IN.SI. s.r.l.</option>
<option value="5" {% if filters.cliente == 5 %} selected {% endif %}>PAGNOSSIN s.r.l.</option>
<option value="6" {% if filters.cliente == 6 %} selected {% endif %}>ELEPHASE s.r.l.</option>
</select>
</div>
</div>
</div>
<div class="card col-sm-3 mx-3">
<div class="card-body">
<div class="card-title">Register:</div>
<div class="col-sm">
<select name="registrar" class="form-select" onchange='this.form.submit();'>
<option value="" {% if filters.registrar is empty %} selected {% endif %}>Seleziona...</option>
<option value="1" {% if filters.registrar == 1 %} selected {% endif %}>Register</option>
<option value="2" {% if filters.registrar == 2 %} selected {% endif %}>OpenProvider</option>
<option value="3" {% if filters.registrar == 3 %} selected {% endif %}>TowerTech</option>
<option value="4" {% if filters.registrar == 4 %} selected {% endif %}>Aruba</option>
<option value="5" {% if filters.registrar == 5 %} selected {% endif %}>Aruba Business</option>
</select>
</div>
</div>
</div>
</div>
{% endif %}
<div class="row justify-content-center">
<div class="card col-sm-3 mx-3">
<div class="card-body">
<div class="card-title">Creazione</div>
<div class="input-group mb-3">
<span class="input-group-text col-2" id="creazione_inizio">Da:</span>
<input type="date" name="creazione_inizio" class="form-control" value="{{filters.creazione_inizio}}" placeholder="Creazione inizio" aria-label="Creazione inizio" aria-describedby="creazione_inizio">
</div>
<div class="input-group mb-3">
<span class="input-group-text col-2" id="creazione_fine">A:</span>
<input type="date" name="creazione_fine" class="form-control" value="{{filters.creazione_fine}}" placeholder="Creazione fine" aria-label="Creazione fine" aria-describedby="creazione_fine">
</div>
<div class="d-grid gap-2">
<button class="btn btn-outline-success" type="submit">Filtra data creazione</button>
</div>
</div>
</div>
<div class="card col-sm-3 mx-3">
<div class="card-body">
<div class="card-title">Scadenza</div>
<div class="input-group mb-3">
<span class="input-group-text col-2" id="scadenza_inizio">Da:</span>
<input type="date" name="scadenza_inizio" class="form-control" value="{{filters.scadenza_inizio}}" placeholder="Scadenza inizio" aria-label="Scadenza inizio" aria-describedby="scadenza_inizio">
</div>
<div class="input-group mb-3">
<span class="input-group-text col-2" id="scadenza_fine">A:</span>
<input type="date" name="scadenza_fine" class="form-control" value="{{filters.scadenza_fine}}" placeholder="Scadenza fine" aria-label="Scadenza fine" aria-describedby="scadenza_fine">
</div>
<div class="d-grid gap-2">
<button class="btn btn-outline-success" type="submit">Filtra data scadenza</button>
</div>
</div>
</div>
<div class="card col-sm-3 mx-3">
<div class="card-body">
<div class="card-title">Scadenza pagamento</div>
<div class="input-group mb-3">
<span class="input-group-text col-2" id="scadenza_pagamento_inizio">Da:</span>
<input type="date" name="scadenza_pagamento_inizio" class="form-control" value="{{filters.scadenza_pagamento_inizio}}" placeholder="Scadenza pagamento inizio" aria-label="Scadenza pagamento inizio" aria-describedby="scadenza_pagamento_inizio">
</div>
<div class="input-group mb-3">
<span class="input-group-text col-2" id="scadenza_pagamento_fine">Da:</span>
<input type="date" name="scadenza_pagamento_fine" class="form-control" value="{{filters.scadenza_pagamento_fine}}" placeholder="Scadenza pagamento fine" aria-label="Scadenza pagamento fine" aria-describedby="scadenza_pagamento_fine">
</div>
<div class="d-grid gap-2">
<button class="btn btn-outline-success" type="submit">Filtra data scadenza pagamento</button>
</div>
</div>
</div>
</div>
{% if query is defined %}
<input type="hidden" name="query" value="{{query}}">
{% endif %}
</form>
</div>
</div>
To pass the current GET parameters (from URL, not form) You should be able to modify the href as follows:
Scarica CSV
To use the current form values you need to use JavaScript to set the form's action attribute value to that returned by {{ path('domains_data_csv') }} and submit the form.

In my form there is an image upload section. If user not upload any file, then it gives MultiValueDictKeyError. How to get rid of it?

I am working on a project for a Django web-based application. In this project, there is a section in which I take info from the user through an HTML form. I added a section "image upload " but it gives a MultiValueDictKeyError error when the user does not upload any file. I tried this but not working for me.
This is error section : error image
This is my addpost.html section. It consists of a form through which, I am taking info.
<form action="{% url 'addpost' %}" method='POST' enctype="multipart/form-data" novalidate>
{% include 'includes/messages.html' %}
{% csrf_token %}
{% if user.is_authenticated %}
<input type="hidden" name="user_id" value="{{user.id}}">
{% else %}
<input type="hidden" name="user_id" value="0">
{% endif %}
<div class="row ">
<div class="tex-center">
<div class="row">
<div class="col-md-6 text-left">
<div class="form-group name">
<input type="text" name="author" class="form-control" placeholder="Author"
{% if user.is_authenticated %} value="{{user.first_name}}" {% endif %} readonly>
</div>
</div>
<div class="col-md-6">
<div class="form-group name">
<input type="text" name="title" class="form-control" placeholder="title" required>
</div>
</div>
<div class="col-md-6">
<div class="form-group name">
<input type="text" name="location" class="form-control" placeholder="location" required>
</div>
</div>
<div class="col-md-6">
<div class="form-group name">
<input type="text" name="short_desc" class="form-control"
placeholder="Write short description" required>
</div>
</div>
<div class="col-md-12">
<div class="form-group message">
<textarea class="form-control" name="full_desc"
placeholder="Write full description"></textarea>
</div>
</div>
<input type="file" id="myFile" name="place_photo" required/>
<div class="col-md-12">
<div class="send-btn text-center">
<input type="submit" class="btn btn-outline-success mr-1" value="Send Post">
Cancel
</div>
</div>
</div>
</div>
</div>
</form>
This is the views.py file where I receive POST data
def add_post(request):
if request.method == "POST":
try:
is_private = request.POST['is_private']
except MultiValueDictKeyError:
is_private = False
author = request.POST['author']
title = request.POST['title']
user_id = request.POST.get('user_id')
location = request.POST['location']
short_desc = request.POST['short_desc']
full_desc = request.POST['full_desc']
place_photo = request.FILES['place_photo']
post = Post(author=author, user_id=user_id, title=title, location=location,
short_desc=short_desc,full_desc=full_desc, place_photo=place_photo)
post.save()
messages.success(request,"Your post uploaded successfully")
return render(request,'community/addpost.html')
This is my models.py file
class Post(models.Model):
author = models.CharField(max_length=100, default=' ')
title = models.CharField(max_length=150)
user_id = models.IntegerField(blank=True)
location = models.CharField(max_length=100, default=' ')
short_desc = models.CharField(max_length=255, default='In less than 250 words')
full_desc = models.TextField()
place_photo = models.ImageField(upload_to='photos/%Y/%m/%d/')
added_date = models.DateTimeField(default=datetime.now,blank=True)

How should I save to the database?

I have created a Customer model in Django and am not able to save the data to the database table and when I click the signup button it just redirects me back to the home page.
I have attached below the customer model and the signup function.
...please help me resolve the issue.
customer.py
from django.db import models
class Customer(models.Model):
first_name= models.CharField(max_length=50)
last_name= models.CharField(max_length=50)
phone=models.CharField(max_length=15)
email=models.EmailField()
password=models.CharField(max_length=500)
def register(self):
self.save()
views.py
def signup(request):
if request.method == 'GET':
return render(request, 'signup.html')
else:
postData=request.POST
first_name=postData.get('firstname')
last_name=postData.get('lastname')
phone=postData.get('phone')
email=postData.get('email')
password=postData.get('password')
print(first_name,last_name,phone,email,password)
customer=Customer(first_name=first_name,last_name=last_name,phone=phone,email=email,password=password)
customer.register()
return HttpResponse("Signup success")
signup.html
{% extends 'base.html' %}
{% block content %}
<div class="container">
<div class="p-4 m-4">
<div class="col-lg-5 mx-auto border rounded pt-4">
<h3 class="alert alert-light border rounded" >Create An Account</h3>
<form action="/" method="POST">
{% csrf_token %}
<!--firstname-->
<div class="form-group">
<label for="">First Name</label>
<input type="text" name="firstname" id="" class="form-control form-control-sm" placeholder="Mike">
</div>
<!--lastname-->
<div class="form-group">
<label for="">Last Name</label>
<input type="text" name="lastname" id="" class="form-control form-control-sm" placeholder="Ross">
</div>
<!--phone-->
<div class="form-group">
<label for="">Phone No</label>
<input type="text" name="phone" id="" class="form-control form-control-sm" placeholder="9876543210">
</div>
<!--email-->
<div class="form-group">
<label for="">Email</label>
<input type="email" name="email" id="" class="form-control form-control-sm" placeholder="abc#gmail.com">
</div>
<!--password-->
<div class="form-group">
<label for="">Password</label>
<input type="password" name="password" id="" class="form-control form-control-sm" placeholder="********">
</div>
<div class="form-group">
<input class="btn btn-sm btn-info" type="submit" value="Sign Up">
</div>
</form>
</div>
</div>
</div>
{% endblock %}
Try this change
Model
def register(self):
return self.save()

Getting smaller size for text input field in django bootstrap

I am using textfields, radiobuttons, textarea etc in my form. The textfield size is very small and looks very bad:
How can I make slightly larger? How the height of text area is smaller than that of gender field?
Code is:
<div class='form-group'>
<label class='control-label col-md-2 col-md-offset-2' for='id_name'>Name</label>
<div class='col-md-6'>
{% render_field form.name class="form-control" placeholder="Full Name" type="text" %}
{% if form.name.errors %}
<div class="alert alert-danger tpad">
{{ form.name.errors.as_text }}
</div>
{% endif %}
</div>
</div>
<!-- name ends here -->
{# Gender goes here #}
<div class='form-group'>
<label class='control-label col-md-2 col-md-offset-2' for='id_name'>Gender</label>
<div class='col-md-6'>
{% for radio in form.gender %}
{{ radio }}
{% endfor %}
{{form.gender.errors}}
</div>
</div>
<!-- enroll ment number -->
<div class='form-group'>
<label class='control-label col-md-2 col-md-offset-2' for='id_enrollment_number'>Enrollment Number</label>
<div class='col-md-6'>
{% render_field form.enrollment_no class='form-control' placeholder='Enrollment Number' type='text' %}
{% if form.enrollment_no.errors %}
<div class="alert alert-danger tpad">
{{ form.enrollment_no.errors.as_text }}
</div>
{% endif %}
</div>
</div>
<div class='form-group'>
<label class='control-label col-md-2 col-md-offset-2' for='id_faculty_name'>Faculty Name</label>
<div class='col-md-6'>
{% render_field form.faculty_name class='form-control' rows="1" cols="1" placeholder='Faculty Name' type='text' %}
{% if form.faculty_name.errors %}
<div class="alert alert-danger tpad">
{{ form.faculty_name.errors.as_text }}
</div>
{% endif %}
</div>
</div>
The code generated is:
<div class='form-group'>
<label class='control-label col-md-2 col-md-offset-2' for='id_name'>Name</label>
<div class='col-md-6'>
<input class="form-control" id="id_name" maxlength="200" name="name" placeholder="Full Name" type="text" />
</div>
</div>
<!-- name ends here -->
<div class='form-group'>
<label class='control-label col-md-2 col-md-offset-2' for='id_name'>Gender</label>
<div class='col-md-6'>
<select id="id_gender" name="gender">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</div>
</div>
Solution: The text size rendered by bootstrap was 20px. I changed it manually to 40px, here:
.uneditable-input{display:inline-block;height:40px;padding:4px 6px;margin-bottom:10px;font-size:14px;line-height:20px;color:#555;vertical-align:middle;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}input,textarea,
Since your code generate an id for the name input, adding (or update) this rule in your CSS would do the trick
#id_name {
height: 30px; /* where you give it same height as your select */
}
Another way, more generic for your form elements (input text and select), could be like this
form-control select,
form-control input[type=text] {
height: 30px;
}
I think you should resize the box like: cols or you should make it as a textarea.
For example that part of the box:
{% render_field form.name class="form-control" cols="1" placeholder="Full Name" type="text" %}