Django Imagefield url does not contain MEDIA_ROOT - python

I have a model with a ImageField and created an simple Upload Form via CreateForm. I have a simple ListView to show the images (logos).
Upload works fine, Iterating the logos works. Property logo.url is missing but instead it is logo.media. Unfortunately media does not contain the whole path, MEDIA_ROOT is missing. What am I doing wrong here?
models.py:
class Logo(models.Model):
media = models.ImageField(upload_to='uploads')
views.py:
class LogoManager(CreateView):
model = Logo
template_name = 'polls/upload.html'
success_url = '/logos/'
class LogoIndex(ListView):
model = Logo
template_name = 'polls/logos.html'
upload.html:
{% block title %} Upload Form {% endblock %}
{% block content %}
<form id="my_form" action="" method="post" enctype="multipart/form-data">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save Changes" />
</form>
<br />
Back
{% endblock %}
logos.html:
{% block content %}
{% if object_list %}
<ul>
{% for image in object_list %}
<li><img src="{{ image.media }}" width="320" height="200"/></li>
{% endfor %}
</ul>
{% else %}
<p>No Logos are available.</p>
{% endif %}
<br />
{% endblock %}
Output is:
<li><img src="uploads/IMG_5106.JPG" width="320" height="200"/></li>

You'll want to use {{ image.media.url }}, I think.

OK, it was my wrong. I was editing the url in the apps url file. When adding this stanza in root urls.py it works fine:
if settings.DEBUG:
urlpatterns += patterns('django.views.static',
(r'%s(?P<path>.*)' % settings.MEDIA_URL, 'serve', {'document_root': settings.MEDIA_ROOT}),
)
using settings.py:
MEDIA_URL = '/media/'

Related

How can I add a link to another page of my site with Django. I am currently getting a Page not found error

Disquaire\urls.py
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from store import views
urlpatterns = [
url(r'^$', views.index),
url(r'^store/', include('store.urls')),
url(r'^admin/', admin.site.urls),
]
store.urls.py
urlpatterns = [
url(r'^$', views.listing, name='listing'),
url(r'^(?P<album_id>[0-9]+)/$', views.details, name="details"),
url(r'^search/$',views.search,name='search'),
]
list.html
{% for album in albums %}
<div class="col-sm-4 text-center">
<a href="/store/ {% url 'details' album_id=album.id %}">
<img class="img-responsive" src="{{ album.picture }}" alt="{{ album.title }}">
</a>
<h3>{{ album.title }}</h3>
{% for artist in album.artists.all %}
<p>{{ artist.name }}</p>
{% endfor %}
</div>
{% if forloop.counter|divisibleby:3 %}<div class="clearfix"></div>{% endif %}
{% endfor %}
views.py
def details(request, album_id):
album = Albums.objects.get(pk=album_id)
artists = " ".join([artist.name for artist in album.artists.all()])
message = "Le nom de l'album est {}. Il a été écrit par {}".format(album.title, artists)
return HttpResponse(message)
index.html
{% extends 'store\base.html' %}
{% block content %}
{% include 'store\list.html' %}
{% endblock %}
This is the error I get
Page not found
I have already tried many proposals from the site but nothing work, or maybe I didn't applied them well.I am new to Python and Django so I would appreciate all help.
You have written your urls in the manner /store/ {% url 'details' album_id=album.id %} for some reason. The url template tag will give you a relative url from the domain of your site, hence you don't have to prefix your url. Also you write src="{{ album.picture }}" here I assume picture is an image field? If so you should be writing src="{{ album.picture.url }}" instead. Hence change your template to:
{% for album in albums %}
<div class="col-sm-4 text-center">
<a href="{% url 'details' album_id=album.id %}">
<img class="img-responsive" src="{{ album.picture.url }}" alt="{{ album.title }}">
</a>
<h3>{{ album.title }}</h3>
{% for artist in album.artists.all %}
<p>{{ artist.name }}</p>
{% endfor %}
</div>
{% if forloop.counter|divisibleby:3 %}<div class="clearfix"></div>{% endif %}
{% endfor %}

How to render to template with dropdownbox in django?

I'm a beginner Django. And I got a problem with rendering to the template.
I have a model(models.py) which has the class "FuelInfo"; includes ForeignKey.
from django.db import models
class Traveler(models.Model):
traveler_name = models.CharField(max_length=10)
def __str__(self):
return self.traveler_name
class FuelInfo(models.Model):
name = models.ForeignKey(Traveler, on_delete=models.SET_NULL, null=True)
car = models.CharField(null=True, max_length=50)
efficiency = models.FloatField()
def __str__(self):
return str(self.name)
Also views.py is like :
from django.shortcuts import render, get_object_or_404
from .models import FuelInfo
def traveler_list(request):
travelers = FuelInfo.objects.all()
context = {'travelers':travelers}
return render(request, 'fuelcost/home.html', context)
def traveler_detail(request, pk):
traveler = get_object_or_404(FuelInfo, pk=pk)
return render(request, 'fuelcost/calfuel.html', {'traveler': traveler})
And urls.py is :
from django.urls import path
from . import views
app_name = 'fuelcost'
urlpatterns = [
path('', views.traveler_list, name='home'),
path('<int:pk>/', views.traveler_detail, name='calfuel'),
]
I want to make a dropdown that is render to template "calfuel.html" in home.html.
So I made a template("home.html") like :
{% extends "base_generic.html" %}
{% block content %}
<body>
{% if travelers %}
<form method="POST" action="{% url 'fuelcost:calfuel' pk=traveler.pk %}">
{% csrf_token %}
<select name="traveler">
{% for traveler in travelers %}
<option value="{{ traveler.id }}">{{ traveler.name }}</option>
{% endfor %}
</select>
<input type="submit" value="Select" />
</form>
{% else %}
<p>No travelers are available</p>
{% endif %}
</body>
{% endblock %}
But it doesn't works and i received error.
(My urlpattern is fuelcost/.)
Actually I can go into fuelcost/1 or fuelcost/2 that is views.traveler_detail named "calfuel". But I can't go into fuelcost/ that is views.traveler_list named "home".
I don't know what I have to do more. plz, tell me what is wrong with this.
{% block content %}
<body>
{% if travelers %}
{% for traveler in travelers %}
<form method="POST" action="{% url 'fuelcost:calfuel' pk=traveler.pk %}">
{% csrf_token %}
<select name="traveler">
<option value="{{ traveler.id }}">{{ traveler.name }}</option>
</select>
<input type="submit" value="Select" />
</form>
{% endfor %}
{% else %}
<p>No travelers are available</p>
{% endif %}
</body>
{% endblock %}
you have to keep the form inside loop so that it can get pk of traveler

How to use django-summernote in templates

I have setup django-summernote on my project and everything is great, it works very good on admin , but i want to use it on my templates.
Note :
in django-summernote documentation they only explain how to use it if you have forms.py file but I dont
my main urls.py :
urlpatterns = [
path('games/', include('core.urls', namespace='core')),
path('summernote/', include('django_summernote.urls')),
]
my app(name=core) urls.py :
from django.urls import path
from . import views
app_name = 'core'
urlpatterns = [
path('new/', views.GameCreate.as_view(), name='game_new'),
path('<int:pk>/edit/', views.GameUpdate.as_view(), name='game_edit'),
]
my views.py :
class GameCreate(LoginRequiredMixin, CreateView):
model = Game
template_name = 'core/game_new.html'
fields = '__all__'
redirect_field_name = 'home'
class GameUpdate(LoginRequiredMixin, UpdateView):
model = Game
template_name = 'core/game_edit.html'
fields = '__all__'
my template file "game_new.html" :
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block title %} Add New Game {% endblock %}
{% block main %}
<section class="main-section">
<div class="container">
<h1>New Game</h1>
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form|crispy }}
<input type='submit' value="Save" />
</form>
</div>
</section>
{% endblock %}
my template file "game_edit.html":
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block title %} Game Info {% endblock %}
{% block main %}
<section class="main-section"></section>
<div class="container">
<h1>Edit Game Info</h1>
<form action="" method="post">
{% csrf_token %}
{{ form|crispy }}
<input type="submit" value="Update" />
</form>
</div>
</section>
{% endblock %}
my Models.py :
from django.db import models
from django.urls import reverse
# Create your models here.
class Game(models.Model):
name = models.CharField(max_length=140)
developer = models.CharField(max_length=140)
game_trailer = models.CharField(max_length=300, default="No Trailer")
game_story = models.TextField(default='No Story')
Firstly in your template dont forgate to add this:
{{ form.media }} <<<------ To load all js and css attached
In the document your models you must herit summernote widget. Example:
from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget
class FormFromSomeModel(forms.ModelForm):
class Meta:
model = SomeModel
widgets = {
'foo': SummernoteWidget(),
'bar': SummernoteInplaceWidget(),
}

Image not displaying in template django

I have this app in which I need to display an image on the html template which is not happening.
models.py
class cateledetails(models.Model):
cdid=models.IntegerField(unique=True,default=0)
cid=models.ForeignKey(category,to_field='cid',on_delete=models.CASCADE)
elename=models.CharField(max_length=20)
imgsrc=models.ImageField(upload_to='elements/',blank=True)
def __unicode__(self):
return u"{} {}".format(self.cdid,self.elename)
class Meta:
db_table="cateledetails"
views.py
def mainpage(request):
pic_details=get_object_or_404(cateledetails,pk=1)
template=loader.get_template('student/mainpage.html')
context={'pic_details': pic_details,}
return HttpResponse(template.render(context,request))
urls.py
urlpatterns= [
url(r'^mainpage/$',views.mainpage ,name='mainpage'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
mainpage.html
{% block body %}
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<h4>What sound does it make?</h4>
{% for image in pic_details.imgsrc_set.all %}
<img src="{{ image.imgsrc.url }}" alt="image">
{% endfor %}
</form>
{% endblock %}
what do I do?
pic_details is a cateledetails object.
This class has a single ImageField called imgsrc. Since imgsrc isn't a ForeignKey you can't use the ForeignKey <field>_set syntax with it. Instead, simply refer to the field directly:
{% block body %}
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<h4>What sound does it make?</h4>
<img src="{{ pic_details.imgsrc.url }}" alt="image">
</form>
{% endblock %}

DeleteView doesn't delete and just refreshes the delete page

When I click on my delete project link it takes me to my delete page with a button to click which should delete the model data of the project and then take me to the profile page. However when I click the delete button, the page just refreshes and no data gets deleted?!
What am I doing wrong here? Any help would be much appreciated :-)
Views
class DeleteProject(UpdateView):
model = UserProject
template_name = 'howdidu/delete_project.html'
def get_object(self, queryset=None):
obj = super(DeleteProject, self).get_object()
if not obj.user == self.request.user:
raise Http404
return obj
def get_success_url(self):
project_username = self.request.user.username
#project_slug = self.object.slug
return reverse('user_profile', kwargs={'username':project_username})
delete_project.html template
{% extends 'howdidu/base.html' %}
{% load staticfiles %}
{% block title %}Delete project{% endblock %}
{% block body_block %}
<h1>Delete project</h1>
<form method="post">{% csrf_token %}
<p>Are you sure you want to delete "{{ userproject.title }}"?</p>
<input type="submit" value="Confirm" />
</form>
{% endblock %}
Urls
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^register_profile/$', views.register_profile, name='register_profile'),
url(r'^update_profile/$', views.update_profile, name='update_profile'),
url(r'^create_project/$', login_required(views.CreateProject.as_view()), name='create_project'),
url(r'^(?P<username>\w+)/(?P<slug>[-\w]+)/update_project/$', login_required(views.UpdateProject.as_view()), name='update_project'),
url(r'^(?P<username>\w+)/(?P<slug>[-\w]+)/delete_project/$', login_required(views.DeleteProject.as_view()), name='delete_project'),
url(r'^(?P<username>\w+)/$', views.profile_page, name='user_profile'),
url(r'^(?P<username>\w+)/(?P<slug>[-\w]+)/$', views.project_page, name='user_project'),
)
Project.html template which has the delete link on
{% extends 'howdidu/base.html' %}
{% load staticfiles %}
{% block title %}Project{% endblock %}
{% block body_block %}
{% if project %}
<h1>{{ project.title }}</h1>
<img src="{{ project.project_picture.url }}" width = "300" height = "300" />
<h3>{{ project.project_overview }}</h3>
{% if user.is_authenticated %}
{% if project_user.username == user.username %}
<p>Edit project</p>
<p>Delete project</p>
{% endif %}
{% endif %}
{% else %}
The specified project {{ project.title }} does not exist!
{% endif %}
{% endblock %}
You must use DeleteView not UpdateView.
See here.

Categories