I have two classes in my models, two defs in views and one template in one app. Just one of the functions doesn't work properly. Everything else works fine.
I double checked everything but didn't find the issue. Below the code:
Models
from django.db import models
class BildTextMarkt(models.Model):
fotomarkt = models.ImageField(upload_to='images/')
text = models.TextField(blank=True, max_length= 512)
views
def bildtextmarkt(request):
all_maerkte = BildTextMarkt.objects.all()
context = {'my_maerkte':all_maerkte}
return render(request, 'maerkte/maerkte.html', context)
templates
{% for maerkte2 in my_maerkte %}
<div class="bild">{{ maerkte2.fotomarkt }}</div>
<div>{{ maerkte2.text }} </div>
{% endfor %}
Thank you for any hints.
the imagefield item in the template should be
<img src="{{ maerkte2.fotomarkt.url }}">
Related
``I started to work with class based views, but the codes that I've written initially does not render in the template when I use class based views. The data that is in main_c.main_categories.url, main_c.name (see template) simply does not show up when I use class based views.
When I change back to function based views and refresh the page, the HTML code in the template shows up without any problems. Could someone explain what causes this error?
I've read something about context not been found by the template but I don't really understand what it means and how context resolves the issue.
Thanks in advance!`
views.py
class MainCategoryDeleteView(DeleteView):
model = MainCategory
success_url = reverse_lazy("main_category")
template_name = 'admin_dashboard/categories/maincategory_confirm_delete.html'
class MainCategoryUpdateView(UpdateView):
model = MainCategory
fields = '__all__'
success_url = reverse_lazy("main_category")
template_name = 'admin_dashboard/categories/main_category_edit.html'
class MainCategoryCreateView(CreateView):
model = MainCategory
fields = '__all__'
success_url = reverse_lazy("main_category")
template_name = 'admin_dashboard/categories/main_category.html'
def get_context_data(self, **kwargs):
context = super(MainCategoryCreateView, self).get_context_data(**kwargs)
context['main_categories'] = MainCategory.objects.all()
print(MainCategory.objects.all())
return context
urls.py
path('BaitSouq/MainCategory/', views.MainCategoryCreateView.as_view(), name="main_category"),
path('BaitSouq/MainCategory/<int:pk>/Delete/', views.MainCategoryDeleteView.as_view(), name="main_category_delete"),
path('BaitSouq/MainCategory/<int:pk>/Change/', views.MainCategoryUpdateView.as_view(), name="main_category_update"),
templates
<div class="col-lg-2 d-none d-lg-flex">
<div class="categories-dropdown-wrap style-2 mt-30">
<div class="d-flex categori-dropdown-inner" style="font-size: x-small">
<ul>
{% for main_c in main_categories %}
<li>
<a href="#"> <img
src="{{ main_c.main_categories.url }}"
alt=""/>{{ main_c.name }}</a>
</li>
{% endfor %}
</ul>
</div>
</div>
</div>
This is Template folder
In your template you have:
{% for main_c in main_categories %}
...
src="{{ main_c.main_categories.url }}"
...
{% endfor %}
As you havent't given that model I guess it should be shorter: {{ main_c.url }}.
i am a new to Django, i am trying to make a small blog with two different languages, i got all the translations inside my blog including the admin, but still don't know how to translate the content of my posts.
After i fetch the content using the models queries, inside my template i used to type this {% trans "SOME TEXT" %} and it works just fine, with variables that i am getting from database i am using this code:
{% blocktrans %}
{{head.title_text}}
{% endblocktrans %}
now when i type django-admin makemessages -l ru, inside django.po i can't see any new text that have been added.
Also inside my views.py i tried this:
head = Head.objects.first()
trans_h = _(u'{}'.format(head))
but nothing gets added inside django.po
Please, anyone knows how to resolve this issue ??
I think the best way to translate the content of the Post Model without using any third-party is to create for each fields you need to translate inside your models with different languages and translate them from your admin,and display them in your template when the site change the language, in Django you can translate only the text you can not translate the data from your model
Create your model Post
models.py
class Post(models.Model)
title_fr = models.CharField(max_length=200)
title_en = models.CharField(max_length=200)
content_fr = models.TextField()
content_en = models.TextField()
created_at = models.DateTimeField(auto_now_add=True, auto_now=False)
updated_at = models.DateTimeField(auto_now_add=False, auto_now=True)
In the view you translate the text inside the variable and pass it in your template
views.py
from django.shortcuts import render
from django.template import loader
from django.http import HttpResponse
from .models import Post
from django.utils.translation import ugettext_lazy as _
def post_view(request):
post = Post.objects.all()
# Here is you can translate the text in python
title = _("les meilleurs posts du mois")
context = {
'post':post,
'title':title
}
template = loader.get_template('index.html')
return HttpResponse(template.render(context, request))
Here the idea is once your site is translated in french for example(www.mysite.com/fr/) in your template you will get only the attributes with _fr(title_fr, content_fr) already translated in your admin and if it's in english it will be the same thing
index.html
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_available_languages as LANGUAGES %}
<h1> {{ title}}</h1>
{% if LANGUAGE_CODE|language_name_translated == 'Français' %}
{% for items in home %}
<h2>{{ items.title_fr }}</h2>
<p> {{items.content_fr}}</p>
{% endfor %}
{% if LANGUAGE_CODE|language_name_translated == 'English' %}
{% for items in home %}
<h2>{{ items.title_en }}</h2>
<p>{{items.content_en}}</p>
{% endfor %}
{% endif %}
I hope it can be helpful
I'm trying to display a form, using a model form in django. Everything looks like it's setup properly, and I'm not getting any error. Simply, the form is not showing, although the url is updated...
views.py
from rulz.models import Rulz
class rules_create(CreateView):
model = Rulz
fields=['title', 'content']
models.py
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
class Rulz(models.Model):
title = models.CharField(max_length=255)
content = models.TextField()
country = models.CharField(max_length=255,default='France')
city = models.CharField(max_length=255,default='Paris')
player_num = models.IntegerField(default=2)
complexity = models.IntegerField(default=1)
created_on = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(User,on_delete=models.CASCADE,default=1)
def get_absolute_url(self):
return reverse('rulz:rulz_detail',kwargs={'pk':self.pk})
urls.py (in the app)
app_name = 'rulz'
urlpatterns = [
#/rulz/
url(r'^', views.rules_index.as_view(), name='rulz_index'),
url(r'^index/$', views.rules_index.as_view(), name='rulz_index'),
# /rulz/details
url(r'^(?P<pk>[0-9]+)/$',views.rules_detail.as_view(),name='rulz_detail'),
#rulz/create
url(r'^create/',views.rules_create.as_view(),name='rulz_create'),
]
urls.py (root folder)
...
url(r'^rules/',include('rulz.urls')),
...
app/templates/app/rulz_form.html
{% extends 'rulz/Rulz_base.html' %}
{% block body %}
{% load staticfiles %}
{% include 'rulz/form-template.html' %}
{% endblock %}
app/templates/app/form-template.html
{% for field in form %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<span class="text-danger small">{{ field.errors }}</span>
</div>
<div class="validate-input m-b-26" >
<label class="label-input100">{{ field.label_tag }}</label>
<div class="input100">{{ field }}</div>
<div class="col-sm-offset-2 col-sm-10">
<span class="text-danger small">{{ field.help_text }}</span>
</div>
</div>
</div>
and finally the button with the link in my page to access the form :
Go create Rule
I really don't know what I am missing. When I click this button, the url is uploaded to http://127.0.0.1:8000/rules/create/ but the displayed page is exactly the same.
Any clue ?
Thanks
You need to terminate your index regex. At the moment it matches every string the has a start, which of course means every string. Use the $:
url(r'^$', views.rules_index.as_view(), ...
(As an aside, you should avoid having two patterns for the same view.)
In the documentation you can find the list of the attributes needed to correctly rendering your form using CreateView.
So, you need to modify your class based view to look like at least this example:
from rulz.models import Rulz
class rules_create(CreateView):
form_class = YOUR_FORM # The form that will be used with this class
model = Rulz
fields=['title', 'content']
success_url = 'YOUR_SUCCESS_URL' # If success redirect to this URL
I have only recently started working with Django and was wondering how one would go around to combine two queries from different application/models and display them in a given overview page. I will display some non-functional pseudo-code below to illustrate what I am trying to do:
Index.html
Note that I added two seperate context_object_names here just to illustrate what I am trying to do (latest_news and latest_enzyme)
{% extends 'base.html' %}
{% block body %}
<div id="docs-content">
<div class="section" id="s-module-django.db.models.fields">
<div class="page-header text-primary">
<h3 class="info-header-blue-publication-small">Overview</h3>
</div>
<div>
<h3 class="info-header-blue-publication-tiny">Latest news:</h3>
</div>
{% if latest_news %}
{{ latest_news.news_text }}
{% else %}
<p>No recent news.</p>
{% endif %}
<div>
<h3 class="info-header-blue-publication-tiny">Latest enzyme:</h3>
</div>
{% if latest_enzyme %}
<ul>
<li>{{ latest_enzyme.barcode }}</li>
</ul>
{% else %}
<p>No enzymes are available.</p>
{% endif %}
</div>
</div>
{% endblock %}
Views.py
Note that this contains some commented lines that illustrate the method that I was trying but did not get working, as well as two seperate get_querysets to illustrate my intent.
from django.shortcuts import render from django.http import
HttpResponse from django.views import generic
from gts.models import Enzymes
from news.models import News
# Create your views here.
class IndexView(generic.ListView):
template_name = 'overview/index.html'
#context_object_name = 'latest_enzyme_news'
#def get_queryset(self):
# latest_enzyme = Enzymes.objects.order_by('-pub_date')[0]
# latest_news = News.objects.order_by('-pub_date')[0]
# return (latest_enzyme, latest_news)
context_object_name = 'latest_enzyme'
def get_queryset(self):
return Enzymes.objects.order_by('-pub_date')[0]
context_object_name = 'latest_news'
def get_queryset(self):
return News.objects.order_by('-pub_date')[0]
I have looked at similar questions, where they tried to combine multiple queries from multiple models of the same application (e.g. Display objects from different models at the same page according to their published date) but I would appreciate any hint or tip on what would be the 'best practice' for the situation that I described as I would wish to combine queries from different applications more often.
You don't want a ListView here at all. You're not listing things; you're just getting two separate items.
Rather, use a standard TemplateView and define get_context_data to return the specific items you want.
class IndexView(generic.TemplateView):
template_name = 'overview/index.html'
def get_context_data(self):
latest_enzyme = Enzymes.objects.order_by('-pub_date')[0]
latest_news = News.objects.order_by('-pub_date')[0]
return {'latest_enzyme': latest_enzyme, 'latest_news': latest_news}
(Note also, you could just as easily use a function-based view for this, since you are not really getting any value from the class.)
I want to use an app to create a menu that is easy to edit with the admin interface. Something like this:
class Menu_item
name = models.CharField()
item_url = models.URLField()
My template looks something like this:
{% extends base.html %}
div ID="nav"
{{ foo.navbar.? }}
/div
div ID="Content"
{% block content %}{% endblock %}
/div
I want div#nav to contain a ul based upon the above model but just can't figure out how to accomplish this. It seems like an object_list generic view would be great but, the URL accesses the view for the model that populates div#content. Does anyone have any suggestions? Is there a way to access a generic view without a URL?
Thank you.
I have discovered a solution. Inclusion Tags.
What I did was create an inclusion tag, which amounts to a simple custom template tag (django provides a shortcut for you!).
Here is what I did:
Ignore views.py - It will not be used in this case
Create a sub-directory in the app's dir called "templatetags" containing init.py and get_navbar.py (or whatever you want your tag to be):
mysite/
navbar/
templatetags/
__ init__.py (without the space befire init)
get_navbar.py
I changed my navbar.models to look like this:
from django.db import models
class Menu_choice(models.Model):
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
class Menu_item(models.Model):
name = models.CharField(max_length=20)
navbar = models.ForeignKey(Menu_choice)
item_url = models.CharField(max_length=200)
item_desc = models.CharField(max_length=30)
def __unicode__(self):
return self.name
This allows me to create a Menu_choice object in the admin interface for each layer of navigation (primary, secondary, etc)
get_navbar.py looks like this:
from navbar.models import Menu_choice, Menu_item
from django import template
register = template.Library()
#register.inclusion_tag('navbar/navbar.html')
def get_navbar(navBar):
navbar = Menu_item.objects.filter(navbar__name=navBar)
return { "navbar": navbar }
(Note navBar as opposed to navbar)
Create the navbar.html template:
<ul>
{% for menu_item in navbar %}
<li><a href="{{ menu_item.item_url }}">{{ menu_item.name }}</a></li>
{% endfor %}
</ul>
Finally, I inserted the following into my base.html:
{% load get_navbar %}
And where I want primary navigation:
{% get_navbar "primary" %}
Note: the quotes around the string you are sending to your inclusion tag are important. I spent a ridiculously lengthy bit of time trying to make it work before I figured that out.
Also a big thank you to dikamilo for the help.
First, in you view, get data from db:
def index(request):
navbar = Menu_item.objects.all()
return render_to_response( 'you_template.html',
{ 'navbar': navbar }, context_instance = RequestContext (request ) )
And in template:
<div id="nav">
<ul>
{% for i in navbar %}
<li>{{ i.name }}</li>
{% endfor %}
</ul>
</div>