I am trying to allow users to upload photos and to be able to change them. Whenever the user comes back and changes the photos I get an Integrity error, "UNIQUE constraint failed: portal_content.user_id". I assume it's that I am trying to save the user when there already is one. The problem with this though is that I do not know how work around around it and fix it. I've seen similar problems, but do to my skill level I am not really sure on how to fix it. Here is my code:
Model:
def content_file_name(instance, filename):
return '/'.join(['content', instance.user.username, filename])
class Content(models.Model):
user = models.OneToOneField(User, unique=True)
image1 = models.ImageField(upload_to=content_file_name, null=True, blank=True)
image2 = models.ImageField(upload_to=content_file_name, null=True, blank=True)
image3 = models.ImageField(upload_to=content_file_name, null=True, blank=True)
image4 = models.ImageField(upload_to=content_file_name, null=True, blank=True)
image5 = models.ImageField(upload_to=content_file_name, null=True, blank=True)
image6 = models.ImageField(upload_to=content_file_name, null=True, blank=True)
image7 = models.ImageField(upload_to=content_file_name, null=True, blank=True)
image8 = models.ImageField(upload_to=content_file_name, null=True, blank=True)
terms = models.ImageField(upload_to=content_file_name, null=True, blank=True)
View:
#login_required
def register(request):
if request.POST:
content = Content()
content.user = request.user
content.image1 = request.FILES.get('image1_upload', None)
content.image2 = request.FILES.get('image2_upload', None)
content.image3 = request.FILES.get('image3_upload', None)
content.image4 = request.FILES.get('image4_upload', None)
content.image5 = request.FILES.get('image5_upload', None)
content.image6 = request.FILES.get('image6_upload', None)
content.image7 = request.FILES.get('image7_upload', None)
content.image8 = request.FILES.get('image8_upload', None)
content.terms = request.POST.get('terms')
content.save()
return redirect('/portal/register')
try:
gallery = Content.objects.get(user=request.user)
return render(request, 'portal/register.html', {'gallery': gallery})
except ObjectDoesNotExist:
print 'Does Not Exist!'
return render(request, 'portal/register.html')
Template:
{% extends 'portal/base.html' %}
{% load staticfiles %}
{% block head_block %}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
<script language="javascript" type="text/javascript" src="{% static 'js/input.js' %}"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js" type="text/javascript"></script>
{% endblock %}
{% block body_block %}
<div class="container">
<form role="form" method="post" action="." id="js-upload-form" enctype="multipart/form-data">
{% csrf_token %}
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">{{ user.username }}</h1>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" id="image1" src="/media/{{ gallery.image1 }}" alt="">
</a>
<input type="file" name="image1_upload" id="image1_upload" multiple>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" id="image2" src="/media/{{ gallery.image2 }}" alt="">
</a>
<input type="file" name="image2_upload" id="image2_upload" multiple>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" id="image3" src="/media/{{ gallery.image3 }}" alt="">
</a>
<input type="file" name="image3_upload" id="image3_upload" multiple>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" id="image4" src="/media/{{ gallery.image4 }}" alt="">
</a>
<input type="file" name="image4_upload" id="image4_upload" multiple>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" id="image5" src="/media/{{ gallery.image5 }}" alt="">
</a>
<input type="file" name="image5_upload" id="image5_upload" multiple>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" id="image6" src="/media/{{ gallery.image6 }}" alt="">
</a>
<input type="file" name="image6_upload" id="image6_upload" multiple>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" id="image7" src="/media/{{ gallery.image7 }}" alt="">
</a>
<input type="file" name="image7_upload" id="image7_upload" multiple>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" id="image8" src="/media/{{ gallery.image8 }}" alt="">
</a>
<input type="file" name="image8_upload" id="image8_upload" multiple>
</div>
</div>
<br>
<!--<div class="form-group">-->
<!--<textarea name="terms" id="terms" class="form-control input-sm" placeholder="Terms" value="{{ content.terms }}"></textarea>-->
<!--</div>-->
<div class="form-group">
<input type="text" name="terms" id="terms" class="form-control input-sm" placeholder="terms" value="{{ gallery.terms }}">
</div>
<br>
<input type="submit" value="Register" id="js-upload-submit" class="btn btn-info btn-block">
</form>
<br>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
iPad View
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">{{ user.Username }}</h1>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" src="/media/{{ gallery.image1 }}" alt="">
</a>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" src="/media/{{ gallery.image2 }}" alt="">
</a>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" src="/media/{{ gallery.image3 }}" alt="">
</a>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" src="/media/{{ gallery.image4 }}" alt="">
</a>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" src="/media/{{ gallery.image5 }}" alt="">
</a>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" src="/media/{{ gallery.image6 }}" alt="">
</a>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" src="/media/{{ gallery.image7 }}" alt="">
</a>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" src="/media/{{ gallery.image8 }}" alt="">
</a>
</div>
</div>
<p>
{{ gallery.terms }}
</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<script language="javascript" type="text/javascript" src="{% static 'js/preview.js' %}"></script>
{% endblock %}
<!--http://jsfiddle.net/Mqvgx/-->
Your register() view attempts to create a new Content object each time. Since every user can only be related to a single Content object, when attempting to create a second one, it will fail.
You could replace content = Content() with a content, created = Content.objects.get_or_create(user=request.user). This would take care of multiple Content objects for a user.
P.S. a much better approach would be to use Django's ModelForms.
Related
I'm trying to add a range price filter for a list of products with django and I'm having some trouble with how to proceed
Here's the code for the template : ( produits.html )
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
var user = '{{request.user}}'
function getToken(name)
{
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getToken('csrftoken');
</script>
</head>
<body>
{% block content %}
<div class="bg-light py-3">
<div class="container">
<div class="row">
<div class="col-md-12 mb-0">Home <span class="mx-2 mb-0">/</span> <strong class="text-black">Shop</strong></div>
</div>
</div>
</div>
<div class="site-section">
<div class="container">
<div class="row mb-5">
<div class="col-md-9 order-2">
<ul class="nav nav-pills flex-column mb-md-3">
<li class="nav-item">
<div class="nav-link active">Les Produits :</div>
</li>
</ul>
<div class="row mb-5">
{% for item in prod %}
<div class="col-sm-6 col-lg-4 mb-4" data-aos="fade-up">
<div class="block-4 text-center border">
<figure class="block-4-image">
<img src="{{item.imageURL}}" alt="Image placeholder" class="img-fluid">
</figure>
<div class="block-4-text p-4">
<p class="text-primary font-weight-bold">{{item.nom}}</p>
<p class="mb-0">{{item.description}}</p>
<p class="text-primary font-weight-bold">{{item.prix}}</p>
<button data-product="{{item.id}}" data-action="add" class="btn btn-outline-secondary add-btn update-cart"> Add to Cart</button>
View
</div>
</div>
</div>
{% endfor %}
</div>
<div class="row" data-aos="fade-up">
<div class="col-md-12 text-center">
<div class="site-block-27">
</div>
</div>
</div>
</div>
<div class="col-md-3 order-1 mb-5 mb-md-0">
<div class="border p-4 rounded mb-4">
<h3 class="mb-3 h6 text-uppercase text-black d-block">Categories</h3>
<ul class="list-unstyled mb-0">
{% for i in categ %}
<li class="mb-1"><span>{{i.nom}}</span> <span class="text-black ml-auto">{{nb}}</span></li>
{% endfor %}
</ul>
</div>
<div class="border p-4 rounded mb-4">
<div class="mb-4">
<h3 class="mb-3 h6 text-uppercase text-black d-block">Filter by Price</h3>
<div id="slider-range" class="border-primary"></div>
<input type="text" name="PRICE" id="amount" class="form-control border-0 pl-0 bg-white" disabled="" />
</div>
<div class="mb-4">
<h3 class="mb-3 h6 text-uppercase text-black d-block">Size</h3>
<label for="s_sm" class="d-flex">
<input type="checkbox" id="s_sm" class="mr-2 mt-1"> <span class="text-black">Small (2,319)</span>
</label>
<label for="s_md" class="d-flex">
<input type="checkbox" id="s_md" class="mr-2 mt-1"> <span class="text-black">Medium (1,282)</span>
</label>
<label for="s_lg" class="d-flex">
<input type="checkbox" id="s_lg" class="mr-2 mt-1"> <span class="text-black">Large (1,392)</span>
</label>
</div>
<div class="mb-4">
<h3 class="mb-3 h6 text-uppercase text-black d-block">Color</h3>
<a href="#" class="d-flex color-item align-items-center" >
<span class="bg-danger color d-inline-block rounded-circle mr-2"></span> <span class="text-black">Red (2,429)</span>
</a>
<a href="#" class="d-flex color-item align-items-center" >
<span class="bg-success color d-inline-block rounded-circle mr-2"></span> <span class="text-black">Green (2,298)</span>
</a>
<a href="#" class="d-flex color-item align-items-center" >
<span class="bg-info color d-inline-block rounded-circle mr-2"></span> <span class="text-black">Blue (1,075)</span>
</a>
<a href="#" class="d-flex color-item align-items-center" >
<span class="bg-primary color d-inline-block rounded-circle mr-2"></span> <span class="text-black">Purple (1,075)</span>
</a>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="site-section site-blocks-2">
<div class="row justify-content-center text-center mb-5">
<div class="col-md-7 site-section-heading pt-4">
<h2>Categories</h2>
</div>
</div>
<div class="row">
<div class="col-sm-6 col-md-6 col-lg-4 mb-4 mb-lg-0" data-aos="fade" data-aos-delay="">
<a class="block-2-item" href="#">
<figure class="image">
<img src="{%static 'images/women.jpg' %}" alt="" class="img-fluid">
</figure>
<div class="text">
<span class="text-uppercase">Collections</span>
<h3>Women</h3>
</div>
</a>
</div>
<div class="col-sm-6 col-md-6 col-lg-4 mb-5 mb-lg-0" data-aos="fade" data-aos-delay="100">
<a class="block-2-item" href="#">
<figure class="image">
<img src="{%static 'images/children.jpg' %}" alt="" class="img-fluid">
</figure>
<div class="text">
<span class="text-uppercase">Collections</span>
<h3>Children</h3>
</div>
</a>
</div>
<div class="col-sm-6 col-md-6 col-lg-4 mb-5 mb-lg-0" data-aos="fade" data-aos-delay="200">
<a class="block-2-item" href="#">
<figure class="image">
<img src="{%static 'images/men.jpg' %}" alt="" class="img-fluid">
</figure>
<div class="text">
<span class="text-uppercase">Collections</span>
<h3>Men</h3>
</div>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="{%static 'js/cart.js' %}"></script>
{% endblock content %}
</body>
</html>
Here's the model code for products :
class Product(models.Model):
nom = models.CharField(max_length=200,null= True, blank=True)
prix = models.DecimalField(max_digits=7,decimal_places=2,null=True,blank=True)
description = models.TextField(null=True,blank=True)
nbr_stock = models.IntegerField(null=True,blank=True,default=0)
image= models.ImageField(null=True,blank=True)
taille= models.CharField(max_length=5,null=True,blank=True)
categorie=models.CharField(max_length=200,null= True, blank=True)
#property
def imageURL(self):
try :
url = self.image.url
except :
url = ''
return url
def __str__(self):
return self.nom
My question is how can I "retrieve" the value from the range slider and then show the products according to the price? thank you in advance
here is my front-end and everything is working fine however, i don't want all rate to display at once, i want the rate to display one at a time depending on the card category i select.
From the image i uploaded, current rate of other card category are showing which i don't want, please i need help even if it will require using javascript of ajax
Here is my index(template)
{% for giftcard in giftcards %}
<!-- Card -->
<div class="col-lg-4 gift__card col-6 p-0">
<a type="button" class="btn">
<img class="img-fluid gift__card-img" src="{{ giftcard.card_image.url }}">
</a>
<div class="container d-flex align-items-center justify-content-center">
<div class="gift__card-modal-container py-5">
<div class="card__container">
<div class="gift__card-overlay"></div>
<div class="container-fluid bg-light gift__card-modal shadow-lg">
<div class="pop p-5">
<div class="row d-flex align-items-center justify-content-between">
<div class="col-lg-5 col-12 p-0 m-0">
<img class="img-fluid gift__card-img" style="width: 40rem;" src="{{ giftcard.card_image.url }}">
<p class="text-muted">Select the card category and the amount.</p>
</div>
<div class="col-lg-6 col-sm-12 card-details">
<form class="card-form">
<div class="form-group py-2">
<label for="card-category">Card category</label>
<select id="category" class="form-select py-2" aria-label="Default select example">
{% for spec in giftcard.category_set.all %}
<option value="{{ spec.category }}">{{ spec.category }}</option>
{% endfor %}
</select>
</div>
<div class="form-group py-2">
<label for="Amount">Amount</label>
<div class="d-flex align-items-center amount">
<input type="text" class="form-control" id="amount"
placeholder="Please enter amount">
<span class="">#100,000</span>
</div>
</div>
<div class="form-group py-3">
{% for spec in giftcard.category_set.all %}
<label for="rate">Current rate - {{ spec.rate }}</label>
{% endfor %}
</div>
<div class="border-none pt-2 pl-3 d-flex justify-content-end">
<button type="button" class="btn process-card-btn">Proceed</button>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="gift__terms-card hide fade" id="terms" tabindex="-1" role="dialog"
aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content terms">
<div class="p-5">
<h4 class="terms-title pb-4">Trading terms</h4>
{% for spec in giftcard.category_set.all %}
<p class="pb-2">{{ spec.terms }}</p>
{% endfor %}
<div class="border-none pt-3 pl-3 d-flex justify-content-end">
<button type="button" class="btn process-card-btn">Proceed</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
Here is my models
class Giftcard(models.Model):
name = models.CharField(max_length=100, unique=True)
card_image = models.ImageField(upload_to='Giftcard/', blank=False)
date = models.DateTimeField(auto_now_add=True)
publish = models.BooleanField(default=False)
class Category(models.Model):
category = models.CharField(max_length=250)
rate = models.IntegerField()
terms = models.TextField()
card_category = models.ForeignKey(Giftcard, on_delete=models.CASCADE)
Here is my views
def giftcard(request):
giftcards = Giftcard.objects.filter(publish=True)
context = {
'giftcards': giftcards
}
return render(request, 'dashboard/giftcard.html', context)
I'm working on a portfolio project and i face a strange problem when trying to list a project, ( class-based-views-DetailView). More specifically when trying to list a project for example /project/3/evillio i got following error Reverse for 'project-detail' with arguments '('', '')' not found. 1 pattern(s) tried: ['project/(?P<pk>[0-9]+)/(?P<slug>[-a-zA-Z0-9_]+)$'] but when i add a new project, i'm able to list /project/3/evillio with no problem, however i got the same error on the next project /project/4/urban.
For example i add 2 projects in project table (using Postgres) then going to list details of each project. Click on project1 and works fine. Then click on project 2 and i got error above. Then i add a third project in project table and going to list details of each project. Click on project1 works fine, click on project2 works fine, click on project3 and i got the same error as on project2 before adding project3.
I hope is more clear.
urls.py
path('project/<int:pk>/<slug:slug>', WorkProjectsDetailView.as_view(), name='project-detail'),
views.py
class IndexView(ListView):
model = Project
template_name = 'pages/index.html'
context_object_name = 'projects'
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context['slider_projects'] =
Project.objects.all().filter(slider_project=True)
return context
class WorkProjectsView(ListView):
model = Project
template_name = 'work/work.html'
queryset = Project.objects.all()
context_object_name = 'projects'
ordering = ['-date_created']
def get_context_data(self, *, object_list=None, **kwargs):
context = super(WorkProjectsView, self).get_context_data(**kwargs)
context['categories'] = Category.objects.all()
return context
class WorkProjectsDetailView(DetailView):
model = Project
template_name = 'work/project-detail.html'
context_object_name = 'single_project'
def get_context_data(self, **kwargs):
context = super(WorkProjectsDetailView, self).get_context_data(**kwargs)
context['next'] = Project.objects.filter(id__gt=self.kwargs['pk']).order_by('pk').first()
return context
work.html
<div class="projects-list gallery">
{% if projects %}
{% for project in projects %}
<div class="item brand">
<a href="{% url 'project-detail' pk=project.pk slug=project.slug %}" class="effect-ajax" data-dsn-ajax="work"
data-dsn-grid="move-up">
<img class="has-top-bottom" src="{{ project.featured_image.url }}" alt="" />
<div class="item-border"></div>
<div class="item-info">
<h5 class="cat">{{ project.category }}</h5>
<h4>{{ project.title }}</h4>
<span><span>View Project</span></span>
</div>
</a>
</div>
{% endfor %}
{% else %}
<div class="col-lg-8">
<p>No Projects Available</p>
</div>
{% endif %}
</div>
index.html
{% for project in slider_projects %}
<div class="work-item slick-slide">
<img class="has-top-bottom" src="{{ project.featured_image.url }}" alt="">
<div class="item-border"></div>
<div class="item-info">
<a href="{% url 'project-detail' pk=project.pk slug=project.slug %}" data-dsn-grid="move-up" class="effect-ajax">
<h5 class="cat">{{ project.category}}</h5>
<h4>{{ project.title }}</h4>
<span><span>View Project</span></span>
</a>
</div>
</div>
{% endfor %}
project-detail.html
{% extends 'base.html' %}
{% load static %}
{% block content %}
<main class="main-root">
<div id="dsn-scrollbar">
<header>
<div class="headefr-fexid" data-dsn-header="project">
<div class="bg w-100" id="dsn-hero-parallax-img" data-dsn-ajax="img">
<div class="bg-image cover-bg" data-overlay="4"
data-image-src="{{ single_project.hero_image.url }}"></div>
</div>
<div class="scroll" data-dsn-animate="ajax">
<span class="background"></span>
<span class="triangle"></span>
</div>
<div class="project-title" id="dsn-hero-parallax-title" style="margin-top: 100px;">
<div class="title-text-header">
<div class="cat">
<span>{{ single_project.category}}</span>
</div>
<span class="title-text-header-inner">
<span data-dsn-animate="ajax">{{ single_project.title }}</span>
</span>
</div>
<div class="sub-text-header" data-dsn-animate="ajax">
<h5>Published</h5>
<span>- {{ single_project.date_created }}</span>
</div>
</div>
<div class="project-page__inner">
<div class="h-100">
<div class="row justify-content-center align-items-end h-100">
<div id="descover-holder" class="col-lg-12 project-meta__content">
<div class="link">
<a target="_blank"
href="https://www.behance.net/gallery/57437111/Under-Armour-Cal?tracking_source=search%7CPhotography">View
Website</a>
</div>
</div>
</div>
</div>
</div>
</div>
</header>
<div class="wrapper">
<div class="root-project">
<div class="container intro-project section-margin">
<div class="intro-text">
<div class="title-cover" data-dsn-grid="move-section" data-dsn-opacity="0.1"
data-dsn-duration="170%" data-dsn-move="0%">
Nile
</div>
<div class="inner">
<h2 data-dsn-animate="text">A whole new brand</h2>
<p data-dsn-animate="up">Striking and powerful Aston Martin Vantage captivates you at
the first sight. We couldn’t resist the temptation to create a series of beautiful
images for this car.</p>
<a class="bottom-link" data-dsn-animate="up"
href="https://www.behance.net/gallery/66646747/Nile" target="_blank">
<span></span>
<span></span>
<div class="content">
<div class="inner">
<p>VISIT SITE</p>
</div>
</div>
</a>
</div>
</div>
</div>
<div class="container section-margin">
<div class="img-box-small dsn-parallax-full" data-dsn-grid="move-up">
<img src="{{ single_project.photo_1.url }}" alt="">
<div class="cap">
<span>Web Design</span>
</div>
</div>
</div>
<div class="container-fluid section-margin">
<div class="img-box-small dsn-parallax-full" data-dsn-grid="move-up" data-dsn-triggerhook="0">
<img src="{{ single_project.photo_2.url }}" alt="" data-dsn-y="30%" data-dsn-scale="1.08">
<div class="cap">
<span>Web Design</span>
</div>
</div>
</div>
<div class="container intro-project section-p section-margin">
<div class="intro-text text-center">
<div class="title-cover" data-dsn-grid="move-section" data-dsn-opacity="0.1"
data-dsn-duration="170%" data-dsn-move="0%">
Nile
</div>
<div class="inner">
<h2 data-dsn-animate="text">
The Brief team has been sincerely committed to
designing great communication around our projects. Our customers love
their
creative work - and so do we!
</h2>
</div>
</div>
</div>
<!--Video-->
<div class=" " data-dsn="video" data-overlay="4" data-dsn-ajax="img">
<video class="image-bg cover-bg dsn-video" controls loop muted>
<source src="{{ single_project.video.url }}" type="video/mp4">
</video>
</div>
<!--<div class="container section-margin">
<div class="img-box-small dsn-parallax-full" data-dsn-grid="move-up">
<img src="{{ single_project.photo_3.url }}" alt="">
<div class="cap">
<span>Web Design</span>
</div>
</div>
</div>-->
<div class="container-fluid section-margin">
<div class="img-box-small dsn-parallax-full" data-dsn-grid="move-up" data-dsn-triggerhook="0">
<img src="{{ single_project.photo_4.url }}" alt="" data-dsn-y="30%" data-dsn-scale="1.08">
<div class="cap">
<span>Web Design</span>
</div>
</div>
</div>
</div>
<div class="next-project" data-dsn-footer="project">
<div id="dsn-next-parallax-img" class="bg">
<div class="bg-image cover-bg" data-overlay="2"
data-image-src="{{ next.featured_image.url }}"></div>
</div>
<div id="dsn-next-parallax-title" class="project-title">
<a href="{% url 'project-detail' next.pk next.slug %}" class="effect-ajax" data-dsn-ajax="next-project">
<div class="title-text-header">
<div class="title-text-header-inner">
<span>{{ next.title }}</span>
</div>
</div>
<div class="sub-text-header">
<h5>Next Project</h5>
</div>
</a>
</div>
</div>
Any help appreciated.
The error you're receiving is because of this line toward the bottom of project-detail.html:
<a href="{% url 'project-detail' next.pk next.slug %}" class="effect-ajax" data-dsn-ajax="next-project">
if there is no next (context["next"]), then django can't figure out the url, and you get the error you're seeing.
Wrap the last segment for the link to "next" with {% if next %}:
{% if next %}
<div class="next-project" data-dsn-footer="project">
<div id="dsn-next-parallax-img" class="bg">
<div class="bg-image cover-bg" data-overlay="2"
data-image-src="{{ next.featured_image.url }}"></div>
</div>
<div id="dsn-next-parallax-title" class="project-title">
<a href="{% url 'project-detail' next.pk next.slug %}" class="effect-ajax" data-dsn-ajax="next-project">
<div class="title-text-header">
<div class="title-text-header-inner">
<span>{{ next.title }}</span>
</div>
</div>
<div class="sub-text-header">
<h5>Next Project</h5>
</div>
</a>
</div>
</div>
{% endif %}
I've create a simple form to create and update the blogposts. After the creation of the update view happen something strange that I can't solve.
views.py
def createPost(request):
if request.method == "POST":
form = BlogPostForm(request.POST or None)
if form.is_valid():
new_post = form.save(commit=False)
new_post.slug_post = slugify(new_post.title)
new_post.save()
return redirect('post_list')
else:
form = BlogPostForm()
context = {
'form': form,
}
template = 'blog/editing/create_post.html'
return render(request, template, context)
def updatePost(request, slug_post=None):
update_post = get_object_or_404(BlogPost, slug_post=slug_post)
form = BlogPostForm(request.POST or None, instance=update_post)
if form.is_valid():
update_post = form.save(commit=False)
update_post.slug_post = slugify(update_post.title)
update_post.save()
return redirect('post_list')
context = {
'form': form,
}
template = 'blog/editing/create_post.html'
return render(request, template, context)
urls.py
urlpatterns = [
path("blog/", views.listPost, name='post_list'),
path("blog/<str:slug_post>/", views.singlePost, name='single_post'),
path("blog/create-post/", views.createPost, name='create_post'),
path("blog/<str:slug_post>/update-post/", views.updatePost, name='update_post'),
path("blog/<str:slug_post>/delete-post/", views.deletePost, name='delete_post'),
]
post_list.html
<div class="row">
{% for post in post_list %}
{% if forloop.first %}<div class="card-deck">{% endif %}
<div class="card mb-3 shadow" style="max-width: 540px;">
<div class="row no-gutters">
<div class="col-md-4">
<img src="{{ post.header_image_link }}" class="card-img" alt="{{ post.title }}" style="height: 250px;">
</div>
<div class="col-md-8">
<div class="card-body">
<h4 class="card-title">{{ post.title }}</h4>
<p class="card-text">{{ post.description }}</p>
<p class="card-text my-0 py-0"><small class="text-muted"><strong>Published: </strong>{{ post.publishing_date|date }}</small></p>
</div>
</div>
</div>
</div>
{% if forloop.counter|divisibleby:"4" or forloop.last %}</div>{% endif %}
{% if forloop.counter|divisibleby:"4" and not forloop.last %}<div class="card-deck">{% endif %}
{% empty %}
<div class="row justify-content-md-center my-3 mx-1 py-2 shadow bg-danger rounded">
<div class="col-md-auto">
<h1 class="text-center px-2 py-2" id="text-shadow">Empty list!</h1>
</div>
</div>
{% endfor %}
</div>
create_post.html
<form class="" method="POST" enctype="multipart/form-data" novalidate>{% csrf_token %}
<div class="form-group">
<div class="row">
<div class="col-sm-9">
<div class="form-group mb-4">
<div>{{ form.title }}</div>
<label for="id_title">
<span class="text-info" data-toggle="tooltip" title="{{ form.title.help_text }}">
<i class="far fa-question-circle"></i>
</span>
<small class="text-danger">{{ form.title.errors }}</small>
</label>
</div>
<div class="form-group mb-4">
<div>{{ form.description }}</div>
<label for="id_description">
<span class="text-info" data-toggle="tooltip" data-placement="bottom" title="{{ form.description.help_text }}">
<i class="far fa-question-circle"></i>
</span>
<small class="text-danger">{{ form.description.errors }}</small>
</label>
</div>
<div class="form-group mb-4">
<div>{{ form.contents }}</div>
<label for="id_contents">
<span class="text-info" data-toggle="tooltip" data-placement="bottom" title="{{ form.contents.help_text }}">
<i class="far fa-question-circle"></i>
</span>
<small class="text-danger">{{ form.contents.errors }}</small>
</label>
</div>
<div class="form-group mb-4">
<div>{{ form.header_image_link }}</div>
<label for="id_highlighted">
<span class="text-info" data-toggle="tooltip" title="{{ form.header_image_link.help_text }}">
<i class="far fa-question-circle"></i>
</span>
<small class="text-danger">{{ form.header_image_link.errors }}</small>
</label>
</div>
</div>
<div class="col-sm-3">
<div class="form-inline mb-4 py-0">
<div class="input-group mx-1">
<label for="id_highlighted">{{ form.highlighted.label }}</label>
<div class="ml-1">{{ form.highlighted }}</div>
</div>
<div class="input-group mx-1">
<label for="id_draft">{{ form.draft.label }}</label>
<div class="ml-1">{{ form.draft }}</div>
</div>
</div>
<div class="form-group mb-4">
<label for="publishing_date_field">
{{ form.publishing_date.label }}
<small class="text-danger">{{ form.publishing_date.errors }}</small>
</label>
<div class="input-group date" data-target-input="nearest">
{{ form.publishing_date }}
<div class="input-group-append" data-target="#publishing_date_field" data-toggle="datetimepicker">
<div class="input-group-text"><i class="fa fa-calendar"></i></div>
</div>
</div>
<script>
$(function () {
$("#publishing_date_field").datetimepicker({
format: 'DD/MM/YYYY HH:mm',
});
});
</script>
</div>
<div class="form-group mb-4">
<div class="row justify-content-md-center py-4 border border-warning rounded">
<h5 class="text-justify px-3">Clicca sul tasto che segue per vedere l'elenco delle immagini. Potrai copiare il link all'immagine che ti interessa ed usarlo per creare l'immagine di testata o migliorare i contenuti del post.</h5>
<button type="button" class="btn btn-primary mt-2 mx-2" data-toggle="modal" data-target=".bd-example-modal-xl">Image list</button>
</div>
<div class="modal fade bd-example-modal-xl" tabindex="-1" role="dialog" aria-labelledby="myExtraLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-xl modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-body">
{% for image in images_url_list %}
{% if forloop.first %}<div class="card-deck">{% endif %}
<div class="card mx-1 my-1" style="height: 100%; width: 300px;">
<img src="{{ image.file.url }}" class="card-img-top h-100" alt="{{ image.file.url }}" id="{{ image.id }}">
<div class="card-body">
<button class="btn btn-outline-primary btn-sm" type="button" onclick="CopyToClipboard('{{ image.id }}')">Copy URL</button>
</div>
</div>
{% if forloop.counter|divisibleby:"3" or forloop.last %}</div>{% endif %}
{% if forloop.counter|divisibleby:"3" and not forloop.last %}<div class="card-deck">{% endif %}
{% endfor %}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<hr>
<div class="row justify-content-md-center">
<div class="col-md-auto">
<input type="submit" class="btn btn-info" value="Pubblica">
</div>
</div>
</div>
</form>
I have this error message if I try to create a new post with my form:
Page not found (404) Request Method: GET Request URL:
http://127.0.0.1:8000/blog/create-post/ Raised by:
blog.views.singlePost
As I said this happen after the creation of updatePost. If I comment the path of the single post path("blog/<str:slug_post>/", views.singlePost, name='single_post'), I can create a post whitout problems.
What I've wrong?
Move path("blog/<str:slug_post>/", views.singlePost, name='single_post') to the bottom of your list, below the update and delete paths.
urlpatterns = [
path("blog/", views.listPost, name='post_list'),
path("blog/create-post/", views.createPost, name='create_post'),
path("blog/<str:slug_post>/update-post/", views.updatePost, name='update_post'),
path("blog/<str:slug_post>/delete-post/", views.deletePost, name='delete_post'),
path("blog/<str:slug_post>/", views.singlePost, name='single_post'),
]
I've seen similar problems on stackoverflow, but cannot seem to get mine to work. When I have a user upload photos if a input is left blank Django will throw a MultiValueDictKeyError. I have blank=True in my imageField, but it does not seem to work.
I have the following class article in my app:
def content_file_name(instance, filename):
return '/'.join(['content', instance.user.username, filename])
class Content(models.Model):
user = models.OneToOneField(User, unique=True)
image1 = models.ImageField(upload_to=content_file_name, null=True, blank=True)
image2 = models.ImageField(upload_to=content_file_name, null=True, blank=True)
image3 = models.ImageField(upload_to=content_file_name, null=True, blank=True)
image4 = models.ImageField(upload_to=content_file_name, null=True, blank=True)
image5 = models.ImageField(upload_to=content_file_name, null=True, blank=True)
image6 = models.ImageField(upload_to=content_file_name, null=True, blank=True)
image7 = models.ImageField(upload_to=content_file_name, null=True, blank=True)
image8 = models.ImageField(upload_to=content_file_name, null=True, blank=True)
terms = models.ImageField(upload_to=content_file_name, null=True, blank=True)
This is what my views.py looks like:
def register(request):
if request.POST:
content = Content()
content.user = request.user
content.image1 = request.FILES['image1_upload']
content.image3 = request.FILES['image3_upload']
content.image4 = request.FILES['image4_upload']
content.image5 = request.FILES['image5_upload']
content.image6 = request.FILES['image6_upload']
content.image7 = request.FILES['image7_upload']
content.image8 = request.FILES['image8_upload']
content.terms = request.POST.get('terms')
content.save()
return redirect('/portal/register')
try:
gallery = Content.objects.get(user=request.user)
return render(request, 'portal/register.html', {'gallery': gallery})
except ObjectDoesNotExist:
print 'Does Not Exist!'
return render(request, 'portal/register.html')
This is the error Django throws:
Request Method: POST
Request URL: http://127.0.0.1:8000/portal/register/
Django Version: 1.8.2
Exception Type: MultiValueDictKeyError
Exception Value: "'image1_upload'"
Exception Location: /Library/Python/2.7/site-packages/django/utils/datastructures.py in __getitem__, line 322
Python Executable: /usr/bin/python
html where the images are uplaoded:
<div class="container">
<form role="form" method="post" action="." id="js-upload-form" enctype="multipart/form-data">
{% csrf_token %}
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">{{ user.username }}</h1>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" id="image1" src="/media/{{ gallery.image1 }}" alt="">
</a>
<input type="file" name="image1_upload" id="image1_upload" multiple>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" id="image2" src="/media/{{ gallery.image2 }}" alt="">
</a>
<input type="file" name="image2_upload" id="image2_upload" multiple>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" id="image3" src="/media/{{ gallery.image3 }}" alt="">
</a>
<input type="file" name="image3_upload" id="image3_upload" multiple>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" id="image4" src="/media/{{ gallery.image4 }}" alt="">
</a>
<input type="file" name="image4_upload" id="image4_upload" multiple>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" id="image5" src="/media/{{ gallery.image5 }}" alt="">
</a>
<input type="file" name="image5_upload" id="image5_upload" multiple>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" id="image6" src="/media/{{ gallery.image6 }}" alt="">
</a>
<input type="file" name="image6_upload" id="image6_upload" multiple>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" id="image7" src="/media/{{ gallery.image7 }}" alt="">
</a>
<input type="file" name="image7_upload" id="image7_upload" multiple>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" id="image8" src="/media/{{ gallery.image8 }}" alt="">
</a>
<input type="file" name="image8_upload" id="image8_upload" multiple>
</div>
</div>
If the form field is left blank then request.FILES['form_field'] wont exist.
You should instead use something more like:
content.image1 = request.FILES.get('image1_upload', None)
That way if the form field doesn't exist the model field will get set to None.
You can also just check if the file field exists in files, but it ends up being slightly more verbose:
if 'image1_upload' in request.FILES:
content.image1 = request.FILES.image1_upload