image 404 in django template - django

I am making a catalog of film directors for an introduction to django exercise and im trying to load the images from my database to my template but is not working.
All my steps:
I added an imagefield to the directors model class, which I have then filled in from the admin version.
Then in my view I have made a request to collect a list of all directors like so:
directors = Directors.objects.all()
and then I have returned it with render.
In the template I have done this
{%for director in directors%}
<img src="{{director.director_image.url}}" alt="{{director.first_name}}">
{% endfor %}
And everything is fine except that the images are not loaded, the alt with the names of the directors are ok :D (an advance). I get the feeling that somehow I have to define the url of the images??? because from the browser console it get the url of the images properly but it gives a 404.
im really on my first days using django so I guess im missing something with how the media urls works.
hope someone can help me. tysm <3
What I tried?
I haven't tried anything else since I'm very new to django. I have searched in google how images are treated and I have read that a root is necessary for your media? I simply added the imagefield to my model and in the admin view I uploaded it but I have not done anything else.
What I want?
I want to show the images of all the directors in my template

You mispelled directors spelling in template.
change this:
{%for director in directors%} #According to view, you mispelled directors spelling here
<img src="{{director.director_image.url}}" alt="{{director.first_name}}">
{% endfor %}
To this:
{%for director in directores%} #Here you did mistake
<img src="{{director.director_image.url}}" alt="{{director.first_name}}">
{% endfor %}
Now your problem is solved.

Related

Using placeholder tags in non-django CMS pages

In the Django CMS there's the {% placeholder 'content' %}. I tried to use it on a non-django-cms page, i.e., a detail-view page that comes from an apphook. However, when I switch to the structure view in the detail-view page and the placeholder does not seem to reflect. Is that's how it's supposed to work or is there a problem with my code? If it's how it's supposed to work is there a way to make placeholder appear in the page?
You can't use {% placeholder outside of CMS pages.
If you're on one of these pages, you can use a static placeholder. These will show the same content on any page where a static placeholder with the same name exists. So a good example of these is a footer, or header where you'd want it to be the same on all pages;
{% static_placeholder "footer" %}
Another thing you can use, good for your example of a detail page in an apphook, is a PlaceholderField on your models.
Take this example;
from django.db import models
from cms.models.fields import PlaceholderField
class Category(models.Model):
name = models.CharField(max_length=20)
description = PlaceholderField('category_description')
In your template you can then render this placeholder and it'll behave like a standard placeholder on a cms page;
{% load cms_tags %}
{% render_placeholder category_instance.description language 'en' %}
You can find docs for PlaceholderField here

Django - Checkboxes & ManytoMany relationships in TemplateView

I have a app where users can register their company and then select a number of settings from a list. Both the company and services are different models.
class Company(models.Model):
name = models.CharField(max_length=100)
(...)
class Service(models.Model):
name = models.CharField(max_length=100)
linked_companies = ManyToManyField(Company, blank=True)
What I want is to have a large list of services, with checkboxes behind their names, so the owner can quickly select the services that he wants to connect to his model. This used to be done through the admin interface, but due popular demand this feature is moved to 'the front'.
The problem is that I do not know how to fit this into the traditional (generic) view/form combinations that we' ve been using so far, since two different models are involved.
I am trying a more custom solution, but have hit a wall and I am wondering if you could help me. I have created a html page that should display both the list of services and a 'save' button.
<form action="." method="POST" class="post-form">{% csrf_token %}
<ul>
{% recursetree services %}
<li>
<label><input type="checkbox" name='service' value={{ node.pk }}><h3>{{ node.name }}</h3></label>
{% if not node.is_leaf_node %}
<ul class="children">
{{ children }}
</ul>
{% endif %}
</li>
{% endrecursetree %}
</ul>
<button type="submit" class="save btn btn-default">Add Selected
</button>
</form>
I am using the following ModelForm:
class FacetForm(forms.ModelForm):
class Meta:
model = Services
fields = ['linked_tenants', 'name']
widgets = {
'linked_tenants' : CheckboxSelectMultiple()
}
This HTML page seems to work as intended, showing a long list of services with checkboxes after their names.
However, I have trouble creating a function view. Together with a collegue the following view was created
class FacetList(TenantRootedMixin, TemplateView):
def get_context_data(self, **kwargs):
d = super(ServiceList, self).get_context_data(**kwargs)
d['services'] = Services.objects.all()
d['current_company'] = self.context.company.id
return d
def form_valid(self, *args, **kwargs):
return super(ServiceList, self).form_valid(*args, **kwargs)
This view works in the sense that it shows all of the relevant information (with the checkboxes). If I change the query to filter the services by 'company id'. the view works as desired as well.
The problems I have revolve around the fact that pressing 'save'. crashes the program, throwing the following error.
'super' object has no attribute 'post'
Our program works mostly through generic classbased views and modelforms, so we have relativly limited experience with creating our own custom solutions. By my own estimation the problem seems to be twofold:
The view is probably not configured right to process the 'post' data
It is questionable if the data will be processed to the database afterwards.
Though are 'sollution' is currently flawed, are we looking in the right direction? Are we on the right way to solve our problem?
Regards
I believe you are on the right track. What I would suggest is to not be afraid to move away from generic views and move toward a more custom solution (even if you are inexperienced with it.)
The first routine that comes to my mind would be as follows:
gather all the id's that were checked by the user into a list from request.POST
Update the appropriate object's M2M field to contain these new id's.
Save the fore-mentioned object.
[Edit]
One thing I have trouble with is gathering the ID' s from the request.POST. Could you provide me with an example on how to do this?
Sure, from your HTML file I see you are creating inputs with name=service. That leads me to believe you could do something like:
ids = request.POST.get('service')
but to teach you how to fish rather than giving you a fish, you should try to simply:
print request.POST.items()
This will return and print to the console everything that was posted from your form to your view function. Use this to find out if you are getting a list of id's from the template to the server. If not, you may have to re-evaluate how you are building your form in your template.
Your first point is correct: TemplateView has no "post" method defined and that is why you get the error message when you call super().form_valid. You must either define it yourself or use a CBV which has a post method that you can override (e.g. UpdateView)
And I also believe that your second point is correct.
You would need to use an UpdateView to use the built in functionality (or CreateView).
I had a similar problem to solve (selecting values from many-to-many fields in the front-end) and I ended up with doing it "by hand" because I could not get it to work with CBV. "by-hand" => parse the values from the form, update the database, return HttpResponse
You might want to look at ModelFormSets:
https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/#model-formsets
Hope this helps!
Alex

Django admin dashboard, is there a way to lowercase model name?

I'm looking for a way to lowercase the first letter of a model in my django admin site.
i.e.:
model verbose name is "agent-1.0.0" is shown as "Agent-1.0.0" on the dashboard,
simple but IDK
grappelli trick will also work for me.
django - 1.7.1
also - need this only for one app models group - not all of my dashboard should be lowercase...
so, overriding the index.html is not so efficient
The capitalization is hard-coded in the template, same for the templates in Grappelli.
You can use catavaran's suggestion, but this will transform every model name. Overriding the template is a huge pain in the ass to maintain for something this small.
The only workable solution I can think of is to bypass the capfirst filter with a space:
class Meta:
verbose_name = " agent-1.0.0"
As capfirst only forcibly capitalizes the first character, nothing will happen if the first character is not a letter.
Model name passed to template as capfirst(model._meta.verbose_name_plural) so you have to lowercase it in the admin/index.html tempate or via CSS. Imho CSS option is simpler:
div.module tr[class^=model-] th {
text-transform: lowercase;
}
If you want lowercase only some models (for example User) then change CSS selector to this:
div.module tr.model-user th {
text-transform: lowercase;
}
With Grapelli you could create a custom Dashboard by running:
python manage.py customdashboard
and setting GRAPPELLI_INDEX_DASHBOARD on your settings to your custom class.
You can make this custom class extend from the Dashboard class that grappelli offers and override it to your needs. Look especially at the ModelList class, where you can specify the title you want for the model.
There is a CSS-way for those who don't want to override Django admin classes. Override and extend templates/admin/base_site.html template as follows:
{% extends "admin/base_site.html" %}
{% block extrahead %}
<style>
h1.model-title {text-transform: lowercase;}
h1.model-title:first-letter {text-transform: uppercase;}
</style>
{% endblock %}
{% block content_title %}
{% if title %}<h1 class="model-title">{{ title }}</h1>{% endif %}
{% endblock %}
This will make only first letter of each content_title uppercase.
You can use the same way to lowercase model name in admin tables as well as sidebar. However, I'd like to point that by tacit agreement model's verbose_name as well as verbose_name_plural shouldn't be capitalized. This will save you a lot of overrides in your project, like I provided above to normalize change_list header.

django-seo - nothing is displayed

I have one app in my django project.
I created seo.py file and add:
from rollyourown import seo
class MyMetadata(seo.Metadata):
title = seo.Tag(head=True, max_length=68)
description = seo.MetaTag(max_length=155)
keywords = seo.KeywordTag()
class HelpText:
title = "This will appear in the window/tab name, as well as in search results."
keywords = "A comma separated list of words or phrases that describe the content"
description = "This will appear in the description"
class Meta:
seo_views = ('app_name', )
in my base.html in head I added:
{% load seo %}
{% get_metadata %}
but nothing is displayed. What is wrong? (Of course, I added data in the admin panel - My metadatas (View))
Loading a template tag library will not work if you haven't put that application in your INSTALLED_APPS variable in settings.py. Have you put rollyourown.seo in there?
The paths you need to set up should be in the format '/pagename/'. For your homepage you just need '/'.
#ringfirebug, probably you already solved your issue, but I will answer.
You don't need to set Path for each page. Use Model, Model Instance or a view. From your configuration I see that you have still a default view in seo_views. It should look like this to start working:
class Meta:
seo_views = ('your_app_name.view_name',)
seo_models = ('your_model_1', 'your_model_2',)
So, when creating a new Metadata entry in Models or Views you will be able to see these models and / or views in the select box.
Next, in your template, if it still doesn't work, you have to get seo data exactly for this object,
this worked for me.
{% load seo %}
{% get_metadata for obj as metadata %}
{% metadata %}
Here 'obj' is the object, for example you product that you path to the template through your view by RequestContext.
Let me know if you managed to solve it.
By the way, if you already have managed to use external data in your metatags, like "Best {{ product.name }} of the year", let me know how.

Django : Customizable templates

I am working on creating a web portal and I want to offer the users the feature of making changes to there profile/dashboard like changed background. etc.
Can anybody please guide me to an efficient approach to achieve this?
Thanks
This is trickery that has more to do with css and javascript than with django templates.
The only thing that is django related here is the actual storing of these preferences.
e.g. the filepaths of the actual background images.
After that you will do something similar to what is described in this answer:
how to change html background dynamically
EDIT
I don't see why you need different directories for every user. Django templates
give you more than enough power to do what you want.
For example, let's say that each user can upload his own background picture. Also
I assume that you follow this popular django pattern for storing additional information
about your users. https://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users
So we have this UserProfile model:
class UserProfile(models.Model):
CHOICES = (
('vertical', 'Vertical'),
('horizontal', 'Horizontal'),
)
user = models.OneToOneField(User)
background_image = models.ImageField(upload_to='images')
dashboard_layout = models.CharField(max_length=10, choices=CHOICES)
You can pass this extra information to your javascript context(either with Ajax or without)
and then change the background image for every individual user.
Also we could do special layout at the template level like this:
{% extends "base.html" %}
{% block main_body %}
{% if request.user.get_profile.dashboard_layout == 'vertical' %}
{% include "layouts/vertical.html" %}
{% else %}
{% include "layouts/horizontal.html" %}
{% endif %}
{% endblock main_body %}