image path is not identifiable on index.html of django3 - html

i am following a tutorial based on django 2 and currently running version 3 of django, the problem i am facing is the identifying path of the tag on the front end of index.html, i'll post the code bellow , kindly tell me where i went wrong and any other mistakes
my settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS= (os.path.join(BASE_DIR, 'static'),) #static root added (A2)
MEDIA_ROOT=os.path.join(BASE_DIR, 'media')
MEDIA_URL='/media/'
my urls.py of main project
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('',include('posts.urls')),
path('user/',include('user.urls')),
path('admin/', admin.site.urls),
]+ static(settings.STATIC_URL, document_root=settings.MEDIA_ROOT)
my models.py of app
class Posts(models.Model): #created this model field
def min_len(val): #this is the custom validator working
if len(val)<=9:
raise validators.ValidationError("%(val)s Must be more than 10", params={'val':val})
title=models.CharField(validators=[min_len],max_length=255) #validation list provided
content=models.TextField(validators=[min_len])
thumb_nail=models.FileField(upload_to="posts/",null=True) #file field added
class Posts_Form(forms.ModelForm): #to build a form using django and not html
class Meta: #will get data of the fields=[] only
model=Posts
fields=['title','content','thumb_nail','user','category']
views.py
def index(request):
form=Posts_Form() #created form object
data=Posts.objects.all() #retrive data from the model to display
category=Category.objects.all() #we get all data of category
if request.method=='POST':
form=Posts_Form(request.POST,request.FILES) #request.FILES for file data
if form.is_valid():
# data=Posts(
# title=request.POST['title'],
# content=request.POST['content'],
# )
form.save()
return redirect('/')
return render(request,'index.html',{'title':'Add New Post','form':form,'rows':data,'categories':category})
and my index.html
{% extends "layout.html" %}
{% load static %}
{% block content%}
{%for row in rows%}
<h2>
{{row.title}}
</h2>
<p>
{{row.content}} - <small> {{row.created_at}}-{{row.user.username}} </small>
</p>
<p><img src="{%static 'row.thumb_nail.url' %}" alt="My image" width="150"> </p>
<p>{{row.category.all|join:", "}} </p>
{%endfor%}
</div>
and my layout.html
<!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>
{{title}}
</title>
<!--the below line is for the css bootstrap, from cdnjs official site-->
<!--link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css"-->
</head>
<body>
{% block content %} {% endblock %}
</body>
</html>

Related

How to get a url param in a django template?

I need to get the param of the url inside a html file, but I need to know if is possible in a tag, or how can I get the url params using Class-based views?
My urls.py file
from django.urls import path
from .views import UsersView
urlpatterns = [
path('list/<int:pk>/', UsersView.as_view(), name='user_list'),
]
My html file:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Users</title>
</head>
<body>
{{ request.GET.pk }}
</body>
</html>
You can use
self.kwargs['pk']
Inside a CBV to get the URL parameter, since there is a <int:pk>

Unable to populate select option from database in Django

I am a beginner to Django and unable to populate the items from my database table to <option></option>.
From models.py:
from django.db import models
from django.db.models.fields.related import ForeignKey
# Create your models here.
class Tbl_Category(models.Model):
cat_Id = models.AutoField(primary_key=True)
cat_Name = models.CharField(max_length=20, unique=True)
# def __str__(self):
# return [self.cat_Id, self.cat_Name]
class Tbl_Item(models.Model):
item_Id = models.AutoField(primary_key=True)
item_Name = models.CharField(max_length=30, unique=True)
cat_Idf = models.ForeignKey(Tbl_Category,on_delete=models.CASCADE)
item_Price = models.IntegerField()
From views.py:
from django.shortcuts import render
from orderapp.models import Tbl_Item
# Create your views here.
def displayMain(request):
return render(request,'index.html')
def ct(request):
options = Tbl_Item.objects.filter(cat_Idf=1)
context = {'alloptions' : options}
return render(request, 'index.html', context)
From index.html:
<!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">
{% load static %}
<link rel="stylesheet" href="{% static 'css.css' %}">
<title>DATA COLLECTION</title>
</head>
<body>
<div class="container">
<div class="order-screen">
<div class="element">
<label for="coffee-tea">Coffee-Tea</label>
<select name="coffee-tea" id="coffee-tea">
{% for opt in alloptions %}
<option value="{{opt.item_Id}}">{{opt.item_Name}}</option>
{% endfor %}
</select>
</div>
<div class="cart-screen">CART-SCREEN</div>
</div>
</body>
</html>
I assure you that my database connection is working absolutely fine and there was no problem while running makemigrations and migrate commands. My tables contain values that I have hardcoded. Please guide me with what is wrong with my approach. Thank you.
If I understand you question correctly you want to have a dropdown for different options in a form. In Django this would be done on the model with choices
example
OWNERSHIP=[
('current owner', 'Current Owner'),
('past owner','Past Owner'),
]
class Post(models.Model):
title = models.CharField(max_length=100)
ownership = models.CharField(max_length=100, choices=OWNERSHIP)
then just render the form field as {{ form.ownership }} and it will give you a dropdown

count of likes is not showing in python django .... I don't know why .. Can someone help me

registration and login page is working properly but mine count of likes is not showing in django... I don't know why... Can somebody help me to find this error... It will be the great help... Thank You!!
1.Views.py
from django.shortcuts import render, get_object_or_404, redirect
from datasecurity.models import Post
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
# Create your views here.
#login_required
def likes(request, pk):
post=get_object_or_404(Post, pk=pk)
post.likes.add(request.user)
return HttpResponseRedirect(reverse('datasecurity:datasecurity'))
def datasecurity(request):
allPosts= Post.objects.all()
context={'allPosts': allPosts}
def __init__(self, *args, **kwargs):
stuff = get_object_or_404(Post, id = self.kwargs['pk'])
total_likes = stuff.total_likes()
context['total_likes'] = total_likes
return render(request, 'datasecurity/data.html',context=context)
def blogHome(request, slug):
post=Post.objects.filter(slug=slug).first()
context={"post":post}
return render(request, "datasecurity/blogHome.html", context)
2.Urls.py
from django.conf.urls import url
from . import views
app_name = 'datasecurity'
urlpatterns = [
url(r'^$', views.datasecurity, name="datasecurity"),
url(r'^datasecurity/(?P<slug>[^/]+)', views.blogHome, name='blogHome'),
url(r'^likes/(?P<pk>\d+)/', views.likes, name = "likes"),
]
3.models.py
from django.db import models
from ckeditor.fields import RichTextField
from django.contrib.auth.models import User
# Create your models here.
class Post(models.Model):
sno=models.AutoField(primary_key=True)
title=models.CharField(max_length=255)
author=models.CharField(max_length=14)
slug=models.CharField(max_length=130)
timeStamp=models.DateTimeField(blank=True)
content=RichTextField(blank=True, null=True)
img = models.ImageField(blank=True, null=True, upload_to="dataimage/")
likes = models.ManyToManyField(User)
#property
def total_likes(self):
return self.likes.count()
def __str__(self):
return self.title + " by " + self.author
4.data.html
<!DOCTYPE html>
{% load static %}
<html lang="en" dir="ltr">
<head>
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<link
href="https://fonts.googleapis.com/css?family=Lato:100,300,400,700,900"
rel="stylesheet"
/>
<meta charset="utf-8">
<title></title>
<!-- Bootstrap core CSS -->
<link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
<link rel="stylesheet" href="{% static 'css/datasecurity.css' %}">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=PT+Sans&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Bebas+Neue&family=PT+Sans&display=swap" rel="stylesheet">
<link rel="canonical" href="https://getbootstrap.com/docs/5.0/examples/cover/">
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v9.0" nonce="noEcH88O"></script>
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v3.2"></script>
</head>
<body>
<!-- End header -->
<div id="page-wraper">
<!-- Sidebar Menu -->
<div class="responsive-nav">
<div class="top-navbar">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container">
<marquee><ul class="navbar-nav ml-auto">
<li class="nav-item"><a class="nav-link" href="{% url 'careforallapp:base' %}">Home</a></li>
</ul></marquee>
</div>
</div>
</nav>
</div>
<section class="section about-me" data-section="section1">
<div class="container">
<div class="section-heading">
<h2>Welcome to Data Security</h2>
{% for post in allPosts %}
<div class="line-dec"></div>
<span
>This is a Bootstrap v4.2.1 CSS Template for you. Edit and use
this layout for your site. Updated on 21 May 2019 for repeated main menu HTML code.</span
>
</div>
<div class="left-image-post">
<div class="row">
<div class="col-md-6">
<div class="left-image">
{% if post.img %}
<img src="{{ post.img.url }}" alt="" />
{% endif %}
</div>
</div>
<div class="col-md-6">
<div class="right-text">
<h4>{{post.title}}</h4>
<h6>Article by {{post.author}}</h6>
<h2>{{post.datetime}}</h2>
<p>
{{post.content|safe | truncatechars:280}}
</p>
<form action = "{% url 'datasecurity:likes' pk=post.pk %}" method = "POST">
{% csrf_token %}
<button type="submit" name="post_id" value = "post_id" class="btn"> Like </button> - {{ total_likes }} likes
</form><br><br>
<div class="white-button">
Read More
</div><br>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
{% endfor %}
</div>
<div>
</section>
</div>
There is no error when I debug the code .. may be it is logical error .. I really don't know .. can someone help me to find out the error Thank you
Looks like you want to display all posts in your datasecurity view. You have declared a function __init__ inside it for some reason (not even using it, also it's not even in a class as __init__ might imply). Change the view like this:
def datasecurity(request):
allPosts= Post.objects.all()
context={'allPosts': allPosts}
return render(request, 'datasecurity/data.html',context=context)
Now in your template you are using {{ total_likes }} but you haven't passed any such variable in the context. But I notice you have declared a method on your model that does the same so change it to {{ post.total_likes }}.

Uploading to S3 from Django

I'm trying to add functionality to my Django site to upload files to an AWS S3 bucket. I found django-s3direct, which seems perfectly suited. After following all the setup instructions, though, I'm getting an error rendering the very basic HTML template:
<html>
<head>
<meta charset="utf-8">
<title>s3direct</title>
{{ form.media }}
</head>
<body>
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
</form>
</body>
</html>
I get the error Reverse for 's3direct' not found. 's3direct' is not a valid view function or pattern name. on the line with {{ form.as_p }}.
In my urls.py I have (as specified in the s3direct docs):
from django.conf.urls import url
from .views import get_upload_params, generate_aws_v4_signature, MyView
app_name = 's3direct'
urlpatterns = [
url(r'^$', MyView.as_view(), name='form'),
url('^get_upload_params/', get_upload_params, name='s3direct'),
url('^get_aws_v4_signature/', generate_aws_v4_signature, name='s3direct-signing'),
]
In forms.py:
from django import forms
from s3direct.widgets import S3DirectWidget
class S3DirectUploadForm(forms.Form):
csv = forms.URLField(widget=S3DirectWidget(dest='csv_destination'))
And in views.py (along with a couple other long functions from s3direct):
from django.views.generic import FormView
from .forms import S3DirectUploadForm
class MyView(FormView):
template_name = 'form.html'
form_class = S3DirectUploadForm
I've configured an IAM policy and added keys to my Django settings file, as well as made a CORS policy for my S3 bucket. I'm using Django 2.0. I'm stuck on this reverse error, and can't seem to figure out what's causing it.
According to docs urls.py should contain
urlpatterns = [
url(r'^s3direct/', include('s3direct.urls')),
]

Django: Using static, hard time with paths to render css

This is a bit embarrassing, but I don't know how to solve this problem:
First off, my project directory looks like this (there are more directories, but we aren't concerned with them):
projectfolder/
wsgi/
openshift/
templates/
home/
simple-sidebar.html
static/
css/
fonts/
js/
And the file we are concerned with is simple-sidebar.html which looks like the following :
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<title>Starter Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<link href= "{% static "css/bootstrap.css" %}" rel="stylesheet">
<!-- Add custom CSS here -->
<link href="{% static "css/simple-sidebar.css" %}" rel="stylesheet">
<link href="{% static "font-awesome/css/font-awesome.min.css" %}" rel="stylesheet">
</head>
Now for some reason my static template tags are not working, but that's probably because I don't know how to set up my static template stuff in my settings.py:
STATIC_ROOT = os.path.join(PROJECT_DIR, '..', 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = () <--- dont know if I need this one?
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
PS: Also how would you do this without the {% static %} tag? I am not sure how my style sheets href would look like.
Try removing the dots from your STATIC_ROOT, for example
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
STATICFILES_DIRS are there for you if you'd like to map additional folders to your application that can be anywhere on your machine. When you run ./manage.py collectstatic you're essentially asking python to find all the files within said directories and drop them into the static folder defined in STATIC_ROOT
If you would like to map your files manually (without the static tag) you'd have to write out the full path of your file, for example /some/directory/path/css/style.css.
Lastly if you're running with DEBUG = True you are required to add your static and media urls to urls.py so there is an actual path in place. For example
from django.conf import settings
# ... your normal urlpatterns here
if settings.DEBUG:
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}),
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.STATIC_ROOT}))