Hey guys I was making a page where people can download my stuff.I made a model of thta and It is succesfull in uploading that but the problem i swhen I click on the download button front end I t doesn,t download that stuff .Instead of that it downloads the copy of the page.
Here,s the models.py
class Upload(models.Model):
image = models.ImageField(upload_to = 'images',)
file = models.FileField(upload_to = 'images/%Y/%M/%d/')
name = models.CharField(max_length = 200)
def __str__(self):
return self.name
Here,s the views.py
def upload(request):
upload = Upload()
return render(request,'app/download.html',{'upload':upload})
Here,s the html file
{% block content %}
<div class="container">
<div class="download">
<p style="text-align: center;">
<img src="{{upload.image}}" alt="Image containing link to you,r success">
</p>
</div>
<h2>Click on the button below</h2>
<button class="btn btn-primary"><a href="{{upload.file.id}}" download>Yeah do it</a></button>
</div>
{% endblock %}
try
{% block content %}
<div class="container">
<div class="download">
<p style="text-align: center;">
<img src="{{upload.image}}" alt="Image containing link to you,r success">
</p>
</div>
<h2>Click on the button below</h2>
Yeah do it
</div>
{% endblock %}
Changes explained:
{{upload.file.url}} will give you the url to your uploaded file.
directly add "btn btn-primary" to your anchor tag. It'll display as button. You don't need seperate <button> tag
Related
I'm building an app in Django, using Bulma for styling. I have a Polishes model that has a favorites field, which references the User (users can save polishes to their list of favorites):
models.py:
class Polish(models.Model):
name = models.CharField(max_length=100)
image = models.CharField(max_length=400, default="https://www.dictionary.com/e/wp-content/uploads/2018/02/nail-polish-light-skin-tone.png")
brand = models.ForeignKey(Brand, on_delete=models.CASCADE, related_name='polishes')
favorites = models.ManyToManyField(User, related_name='favorite', default=None, blank=True)
def __str__(self):
return self.name
The add_favorites function checks to see if the polish has been added to the user's favorites already, and if it has, it removes the polish from the list. If it hasn't, it adds it:
views.py:
# login_required
def add_favorite(request, id):
polish = get_object_or_404(Polish, id=id)
if polish.favorites.filter(id=request.user.id).exists():
polish.favorites.remove(request.user.pk)
else:
polish.favorites.add(request.user.pk)
return redirect('favorites_list')
When I render the list of polishes, I'm using Bulma cards, displaying one polish per card. In the footer of the card, I want it to say 'Save to Favorites' if the polish is not in the user's list of favoties and 'Remove from Favorites' if it is. I'm struggling to get this piece to work. It will currently show either Save to Favorites or Remove from Favorites on all of the cards.
Does anyone have any insight on how to render a different message only on those that are already on the favorites list?
polish_list.html:
...
<div class="gallery">
{% for polish in polishes %}
<a href="{% url 'polish_reviews' polish.pk %}">
<div class="card">
<div class="card-header">
<p class="card-header-title">{{polish.name}} by {{polish.brand}}</p>
</div>
<div class="card-image">
<figure class="image is-square">
<img src="{{polish.image}}" alt="{{polish.name}}" />
</figure>
</div>
<footer class="card-footer">
{% if polish.favorites %}
Remove from Favorites
{% elif user.is_authenticated %}
Save to Favorites
{% else %}
Save to Favorites
{%endif%}
</footer>
</div>
</a>
{% empty %}
<article class="message">
<div class="message-header">
<p>No Polishes Available</p>
</div>
</article>
{% endfor %}
</div>
...
I have tried using a conditional in my polish_list.html - {% if polish.favorites %} - but this will make the change on all of the cards rather than just on those that are saved to favorites.
In my edit.html I have a form where the user can edit information on a trainee. The user can add many trainees, edit them, delete them etc. Everything works fine there except the image. The imagefield of form appears in a very messy state. Also it does not update when I select a new image. Here is my code. I have cut down my code to make it more readable
models.py
class Trainee(models.Model):
TraineePic = models.ImageField(null=True, blank= True, upload_to="traineeImg/")
Name = models.CharField(max_length=50)
class Meta():
db_table = "Trainee"
forms.py
class TraineeForm(forms.ModelForm):
TraineePic = forms.ImageField(label="Image :", required=False)
Name = forms.CharField(widget=forms.TextInput(attrs={'class':'col-sm-4'}), label='Name :')
class Meta():
model = Trainee
fields = ("Name","TraineePic",)
views.py
class UpdateTrainee(UpdateView):
model = Trainee
template_name = 'MyTestApp/edit.html'
form_class = TraineeForm
success_url = reverse_lazy('show')
edit.html
{% extends "MyTestApp/base.html" %}
{% block body_block %}
{% load static %}
<link rel="stylesheet" href="{% static '/css/bootstrap.min.css'%}" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<style>
ul#id_Gender li{
display: inline-block;
}
</style>
<body>
<div class="jumbotron">
<h2> Edit Trainee </h2>
<form method="post" class="form-group" type="multipart/form-data" data-ajax="false">
{%csrf_token%}
{{form.errors}}
<div class="form-group row">
<label class="col-sm-3 col-form-label">{{ form.TraineePic.label }}</label>
{{form.TraineePic}}
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label">{{ form.Name.label }}</label>
{{ form.Name }}
</div>
<input type="submit" value="Update" class="btn btn-dark">
</form>
</div>
</body>
{% endblock %}
Here is how the form.TraineePic looks like:
I also tried adding FileInput like this TraineePic = forms.ImageField(label="Image :", required=False,widget=forms.FileInput)
But then I don't get any image. Any help would be appreciated.
You must use #request.FILES to get image from frontend to backend and make it successfully save on database.
In views.py
Example:
Trainee_Pic= self.request.FILES.get('TraineePic') # Use request.FILES
I found the solution. Looks like there was a typo in my form in edit.html
I changed my form from
form method="post" class="form-group" type="multipart/form-data">
to
form method="post" class="form-group" enctype="multipart/form-data">
And the image field in the form which looked very bad previously, I put it in a div with style='display: inline-block' so now it looks pretty ok.
I am trying to get the "About us" information from my database to my web application but its not displaying, what could be wrong...
here is the code from the database
class About(models.Model):
about_us = models.TextField()
achieve = models.TextField(blank=True)
image_abt = models.ImageField(upload_to="admin_pics", null=True)
class Meta:
verbose_name_plural = "About Us"
def __str__(self):
return self.about_us
and here is the Html code `
{% extends 'jtalks/base.html' %}
{% load static %}
{%block content%}
<section id="about-home">
<h2>About Us</h2>
</section>
<section id="about-container">
{% for about in abouts %}
<div class="about-img">
<img src="{{ about.image_abt.url }}" alt="">
</div>
<div class="about-text">
<h2>Welcome to TechEduca, Enhance your skills with best Online Courses</h2>
<p>{ about.about_us}</p>
<div class="about-fe">
<img src="images/fe1.png" alt="">
<div class="fe-text">
<h5>400+ Courses</h5>
<p>You can start and finish one of these popular courses in under our site</p>
</div>
</div>
<div class="about-fe">
<img src="images/fe2.png" alt="">
<div class="fe-text">
<h5>Lifetime Access</h5>
<p>You can start and finish one of these popular courses in under our site</p>
</div>
</div>
</div>
{% endfor %}
</section>
{% endblock %}
Nothing is displaying in the frontend of the website.
Thanks for sharing the view. You forgot to pass data to your template. To do that you have to create the queryset and pass that into a dictionary like below. Add the context variable to your render method so you can access the data in the template.
def about(request):
about = About.objects.all()
context = {
'abouts': about,
}
return render(request, 'jtalks/about.html', context)
also, in your html code i see { about.about_us}, but you have to use double curly brackets: {{ about.about_us }}
I'm working on a portfolio project and I want to add multiple images on the Django admin site then displaying one of the header_image and title of a project on the home/list page (like card class functionality in bootstrap) and other images on the detail page. Is it possible?
Models.py
class MultiImage(models.Model):
header_image = models.ImageField(upload_to='media/')
title = models.CharField(max_length=100)
other_images = models.ImageField(upload_to='media/') # want this to be multiple image field
description = models.TextField()
link = models.URLField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
publish = models.BooleanField(default=True)
class Meta:
ordering = ('created', 'updated')
def __str__(self):
return self.title
index.html
{% for project in projects %}
<div class="col-lg-4 col-md-6 portfolio-item filter-app">
<div class="portfolio-wrap">
<img src="{{ project.image.url }}" class="img-fluid" alt="">
<div class="portfolio-links">
<i class="bx bx-plus"></i>
<i class="bx bx-link"></i>
</div>
</div>
</div>
{% endfor %}
detail.html
<div class="container">
<div class="portfolio-details-container">
<div class="owl-carousel portfolio-details-carousel">
<img src="{% static 'img/portfolio-details-1.jpg' %}" class="img-fluid" alt="">
<!-- all the images goes here -->
</div>
<div class="portfolio-info">
<h3>Project Information</h3>
<ul>
<li><strong>Project </strong>: {{ project.title }}</li>
<li><strong>Project Link to GitHub:</strong>: <a href="{{ project.link }}">{{ project.title }}</a </li>
</ul>
</div>
</div>
</div>
list/index page img
detail page img1
detail page img2
If you want to have several images stored against a single MultiImage object, the best way to do this is to create a separate image model (where you will store all of the images) and then point them back to the MultiImage instance with a foreign key. It will look something like this:
class Image(models.Model):
# add in anything else you want here
image = models.ImageField((upload_to='media/')
multiImage = models.ForeignKey(Reporter, on_delete=models.CASCADE, related_name='other_images')
This will mean, each image you create 'points' to a MultiImage instance. The related_name property is how you get all of the images you need. For example:
multi_image_instance = MultiImage.objects.get(id=...)
images = multi_image_instance.other_images # this will return a QuerySet
In the detail view you can do something like:
{% for image in images %}
<img src={image.image.url} />
{% endfor %}
I have a modal that stores the file_name, file_link, is_active and an uploaded on field. I can add the PDF via the admin site but I am trying to allow the users the ability to download the PDF or view the PDF on a new tab from the front end webpage that I created.
Currently, the view that I created is getting the information for each PDF so that I can display the name, link, etc. If I put the {{ pdf.file_link }} into an it doesn't do anything.
I would really appreciate getting some assistance on this so that I can stope spinning my wheels. Thank you in advance!+
EDIT:
Models:
class HelpfulPDF(models.Model):
file_name = models.CharField(max_length=256)
file_link = models.FileField(upload_to='pdfs')
uploaded_on = models.DateField(auto_now=True)
is_active = models.BooleanField(default=True)
def __str__(self):
return "{} - {}".format(self.id, self.file_name)
View:
As you can see in the view, I am only getting the date from the model. I am not doing anything special with the actual PDF yet. That is the question.
#login_required()
def help_center_view(request):
data = dict()
data['userprofile'] = request.user.userProfile
data['get_pdfs'] = HelpfulPDF.objects.filter(is_active=True)
return render(request, 'help_center.html', data.items())
Template:
{% extends 'base.html' %}
{% load staticfiles %}
{% block content %}
<hr>
<div class="text-center">
<b>Please look at the below PDF's.</b> <i>(You can view in browser or download to your computer)</i>
</div>
<hr>
<br><br>
<div class="text-center">
{% if get_pdfs %}
{% for each_pdf in get_pdfs %}
<div style="display: inline-block; width:275px; height: auto; border: thin grey solid; border-radius: 15px ">
<br>
{% if each_pdf.file_name %}
<h6>{{ each_pdf.file_name }}</h6>
{% else %}
<h6>Helpful PDF</h6>
{% endif %}
<hr>
<div style="margin-top: 13em">
<hr>
<button class="btn-primary btn-sm">Download PDF</button>
<button class="btn-primary btn-sm">View PDF Online</button>
</div>
<br>
</div>
{% endfor %}
{% else %}
<h4>There are no PDF's to display at this time.</h4>
{% endif %}
</div>
{% endblock %}
If your link to the pdf file works (try going to it in your browser and see what happens), then it should be possible to do the equivalent of this in your template:
<a href={{ your_link }}></a>
Add the target="_blank" attribute to have it open in another tab.
You can add a download attribute to the anchor element if you want it to download on click.
The browser should handle opening or downloading the PDF automatically. If not, then either your link is not valid (the most likely cause) or (much less likely because you'd probably know it) your server is sending the wrong content-type header in the response (which you can inspect from the browser dev console in the Network tab on Chrome).
You can create a view to proxy the PDF files and return specific headers, see the following answer: How to show a PDF file in a Django view