i created methods within my model class to handle my redirects all work except for the one i created for a link in my list view(go_to_create method ) im using class based views
class Todo(models.Model):
name = models.CharField(max_length=100, default='unamedTodo')
description = models.CharField(max_length=200)
Todo_date = models.DateTimeField('Todo Date')
pub_date = models.DateTimeField('Date Published')
def get_absolute_url(self):
return reverse('ToDo:detail', kwargs={'id': self.id})
def get_back_home(self):
return reverse('ToDo:todos', kwargs={})
def go_to_update(self):
return reverse('ToDo:update', kwargs={'id': self.id})
def go_to_create(self):
return reverse('ToDo:create', kwargs={})
class TodoCreateView(CreateView):
template_name = 'ToDo/todo_create.html'
form_class = TodoForm
queryset = Todo.objects.all()
from django.urls import path
from .views import (
TodoListView,
TodoDetailView,
TodoCreateView,
TodoUpdateView,
TodoDeleteView,
)
app_name = "ToDo"
urlpatterns = [
path('Todos/', TodoListView.as_view(), name='todos'),
path('Todos/<int:id>/', TodoDetailView.as_view(), name='detail'),
path('Todos/create/', TodoCreateView.as_view(), name='create'),
path('Todos/<int:id>/update/', TodoUpdateView.as_view(), name='update'),
path('Todos/<int:id>/delete/', TodoDeleteView.as_view(), name='delete')
]
<h1>ToDo's</h1>
<ul>
{% for object in object_list %}
<li>
<p>
{{ object.id }} -
{{ object.name }}
</p>
</li>
{% endfor %}
<p>Create new Todo here</p>
</ul>
the link calling the go_to_create method does not work i stay on the same page no error is generated
Instead of a method call directly on template,that will do the job.
{% url 'ToDo:create' %}
Related
I'm trying to display a group of images classified by category. When the user clicks on a category name, the page should display the images that belongs to that category. I'm getting the the next browser error:
NoReverseMatch at /services/
'services' is not a registered namespace
. . .
Error during template rendering
The models belongs to different apps, one (that contains the Category model) works fine, and this other (That contains the Services model) just works if I delete the html content that I need. Help me please.
Here are my files:
home_app/models.py
from django.db import models
from django.urls import reverse
class Category(models.Model):
name=models.CharField(primary_key=True, max_length=50)
slug=models.SlugField(unique=True, blank=True, null=True)
image=models.ImageField(upload_to='category_home')
description=models.CharField(max_length=100)
content=models.TextField(max_length=500, default="Service")
created=models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name = 'Category'
verbose_name_plural = 'Categories'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('services:services_by_category', args=[self.slug])
services_app/models.py
from django.db import models
from home_app.models import Category
class Services(models.Model):
category=models.ForeignKey(Category, on_delete=models.CASCADE)
title=models.CharField(max_length=50)
completed=models.DateField(auto_now_add=False, null=True, blank=True)
content=models.CharField(max_length=50, null=True, blank=True)
image=models.ImageField(upload_to='services_services')
created=models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name = 'Service'
verbose_name_plural = 'Services'
def __str__(self):
return '%s de %s' % (self.category, self.title)
services_app/views.py
from django.shortcuts import render, get_object_or_404
from .models import Services
from home_app.models import Category
def service_list(request,category_slug=None):
category = None
categories = Category.objects.all()
services = Services.objects.all()
if category_slug:
category = get_object_or_404(Category,slug=category_slug)
services = services.filter(category=category)
return render(request, 'services_app/services.html', {'categories':categories, 'category':category, 'services':services,})
services_app/urls.py
from django.urls import path
from services_app import views
urlpatterns = [
path('', views.service_list, name='Services'),
path('<slug:category_slug>', views.service_list, name='services_by_category'),
]
services_app/templates/services_app/services.html
{% extends "home_app/base.html" %}
{% load static %}
{% block content %}
<!-- The app only works if I delete this section -->
<div id="sidebar">
<h3>Categories</h3>
<ul>
{% for c in categories %}
<li>
<h4>{{ c.name }}</h4>
</li>
{% endfor %}
</ul>
</div><br>
<div>
<h1>{% if category %}{{ category.name }}{% endif %}</h1>
{% for service in services %}
<img src="{{service.image.url}}">
{% endfor %}
</div>
{% endblock %}
Also my main urls:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('home_app.urls')),
path('services/', include('services_app.urls')),
path('contact/', include('contact_app.urls')),
]
Just change en models.py the following:
def get_absolute_url(self):
return reverse('services_by_category', args=[self.slug])
'cause you have not defined the namespace services.
I'm pretty new to Django and already have read a lot about class-based views before coming here. I'm trying to build a one page website, with dynamic blocks that can be written from the Django admin. My problem is that I cannot manage to render variables from my database in my template. Here's what I wrote:
models.py
from django.db import models
from tinymce.models import HTMLField
class MyResume(models.Model):
subline = models.CharField(max_length=200)
content = HTMLField()
class Meta:
verbose_name = "My Resume"
verbose_name_plural = "My Resume"
def __str__(self):
return "My Resume"
class AboutMe(models.Model):
subline = models.CharField(max_length=200)
content = HTMLField()
cover_img = models.ImageField(upload_to="about_me")
class Meta:
verbose_name = "About me"
verbose_name_plural = "About me"
def __str__(self):
return "About me"
class Experience(models.Model):
subline = models.CharField(max_length=200)
pres_content = models.TextField()
exp_content = HTMLField()
date_exp = models.IntegerField()
class Meta:
verbose_name = "Experience"
verbose_name_plural = "Experiences"
def __str__(self):
return "Experience"
class ProjectPost(models.Model):
title = models.CharField(max_length=200)
technology = models.CharField(max_length=100)
subline = models.CharField(max_length=200)
content = HTMLField()
project_post_cover = models.ImageField(upload_to="projectpost_cover")
class Meta:
verbose_name = "Project Post"
verbose_name_plural = "Project Posts"
def __str__(self):
return self.title
class BlogPost(models.Model):
title = models.CharField(max_length=200)
overview = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
content = HTMLField()
blogpost_thumbnail = models.ImageField(upload_to="blogpost_thumbnail")
class Meta:
verbose_name = "Blog Post"
verbose_name_plural = "Blog Posts"
def __str__(self):
return self.title
class Contact(models.Model):
subline = models.CharField(max_length=200)
presentation_content = HTMLField()
def __str__(self):
return "Contact section text"
views.py
from django.shortcuts import render
from django.views.generic.base import TemplateView
from .models import *
class IndexTemplateView(TemplateView):
template_name = 'index.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs) # first, call super get context data
context['myresume'] = MyResume.objects.all()
context['aboutme'] = AboutMe.objects.all()
context['experience'] = Experience.objects.all()
context['projectpost'] = ProjectPost.objects.all()
context['blogpost'] = BlogPost.objects.all()
context['contact'] = Contact.objects.all()
return context
core.urls.py:
from django.urls import path
from .views import IndexTemplateView
urlpatterns = [
path('', IndexTemplateView.as_view()),
]
appname.urls.py:
from django.contrib import admin
from django.urls import include, path
from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^tinymce/', include('tinymce.urls')),
path('', include('core.urls')),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
and a snippet from my index.html template:
{% extends 'base.html' %}
{% load static %}
{% block content %}
(...)
<!-- ==================== ABOUT ==================== -->
<section id="about" class="section">
<h2 class="title">ABOUT</h2>
<div class="section-des">
{{ aboutme.subline }}
</div>
<div class="content-670">
<p>
{{ aboutme.content }}
</p>
</div>
<img class="about-img block-right" data-jarallax-element="0 -40" src="{{ aboutme.cover_img.url }}" alt="">
(...)
{% endblock content %}
All of the variables you've added to your template context are querysets, not objects. But you're trying to read them as individual objects in your template, which is why it doesn't work. You have two options:
Iterate over each queryset in your template:
{% for item in aboutme %}
<h2 class="title">ABOUT</h2>
{{ item.subline }}
{{ item.content }}
{% endfor %}
If you only want to display one of each model, then you need to fix your context method to only return one object, e.g.,
context['aboutme'] = AboutMe.objects.first()
Where here you're just returning the first AboutMe object in the database. If you do this, then your existing template logic will work. How you determine which object to return depends on what your data looks like.
{% for obj in myresume %}
<p>{{ obj.subline }}</p>
{% endfor %}
{% for obj in aboutme %}
<p>{{ obj.subline }}</p>
{% endfor %}
you can call your objects in this way in your templates. Also modify str function in models to get the dynamic content.
class MyResume(models.Model):
subline = models.CharField(max_length=200)
content = HTMLField()
class Meta:
verbose_name = "My Resume"
verbose_name_plural = "My Resume"
def __str__(self):
return self.sublime
I have a DetailView, in which I show contents of a post and as well I wanted to add comments functionality to that view. I found 2 ways to do it: combine a DetailView and FormView or make a custom view with mixins. Since I am new to Djanfgo, I went on the 1st way, guided by this answer: Django combine DetailView and FormView but i have only a submit button and no fields to fill on a page.
Here is a necessary code:
#urls.py
from . import views
app_name = 'bankofideas'
urlpatterns = [
path('<int:pk>/', views.DetailView.as_view(), name='idea'),
path('<int:idea_id>/vote', views.vote, name='vote'),
path('<formview', views.MyFormView.as_view(), name='myform')
]
#views.py
class DetailView(generic.DetailView):
model = Idea
template_name = 'bankofideas/detail.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
return Idea.objects.filter(pub_date__lte=timezone.now())
def get_context_data(self, **kwargs): # передача формы
context = super(DetailView, self).get_context_data(**kwargs)
context['comment_form'] = CommentForm#(initial={'post':
self.object.pk})
return context
class MyFormView(generic.FormView):
template_name = 'bankofideas/detail.html'
form_class = CommentForm
success_url = 'bankofideas:home'
def get_success_url(self):
post = self.request.POST['post']
Comment.objects.create()
return '/'
def form_valid(self, form):
return super().form_valid(form)
#models.py
class Idea(models.Model):
main_text = models.CharField(max_length=9001, default='')
likes = models.IntegerField(default=0)
pub_date = models.DateTimeField('date published',
default=timezone.now)
def __str__(self):
return self.main_text
def save(self, *args, **kwargs):
''' On save, update timestamps '''
if not self.id:
self.pub_date = timezone.now()
#self.modified = timezone.now()
return super(Idea, self).save(*args, **kwargs)
class Comment(models.Model):
post = models.ForeignKey(Idea, on_delete=models.PROTECT) #
related_name='comments',
user = models.CharField(max_length=250)
body = models.TextField(default=' ')
created = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.body
def get_absolute_url(self):
return reverse('post_detail', args=[self.post.pk])
#forms.py
from .models import Idea, Comment
from django import forms
class IdeaForm(forms.ModelForm):
class Meta:
model = Idea
fields = ('main_text',)
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
exclude = ['post', 'datetime']
#detail.html
{% extends 'base.html' %}
{% load bootstrap3 %}
{% block body %}
<div class="container">
<p>{{ idea.main_text }} {{ idea.likes }} like(s)</p>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'bankofideas:vote' idea.id %}" method="post">
{% csrf_token %}
<input type="submit" name="likes" id="idea.id" value="{{ idea.likes }}" />
</form>
{% for comment in idea.comment_set.all %}
<p>{{comment.body}}</p>
{% empty %}
<p>No comments</p>
{% endfor %}
<form action="{% url "bankofideas:myform" %}" method="post">
{% csrf_token %}
{{ myform. }}
<input type='submit' value="Отправить" class="btn btn-default"/>
</form>
</div>
{% endblock %}
As a result, I have an ability to see post, read all comments, like it, but cannot leave a comment. I tried to rename the form both in view and template, but it didn't work.
The question is: What should i do to bring comment form on the page?
I'm new in Django. There is a html page (project_details) which should show the title and the tasks of the project, but shows only the title of the project, not the tasks. The tasks exists, the problem is the filter!!!
views.py The error is here
from .models import Project,Task
from django.views.generic import ListView, DetailView
class ProjectsList(ListView):
template_name = 'projects_list.html'
queryset= Project.objects.all()
class ProjectDetail(DetailView):
model = Project
template_name = 'projects_details.html'
def get_context_data(self, **kwargs):
context = super(ProjectDetail, self).get_context_data(**kwargs)
## the context is a list of the tasks of the Project##
##THIS IS THE ERROR##
context['tasks'] = Task.object.filter(list=Project) <---->HERE ((work with Task.object.all() ))
return context
models.py
class Project(models.Model):
title = models.CharField(max_length=30)
slug = AutoSlugField(populate_from='title', editable=False, always_update=True)
class Task(models.Model):
title = models.CharField(max_length=250)
list = models.ForeignKey(Project)
slug = AutoSlugField(populate_from='title', editable=False, always_update=True)
urls.py
from django.conf.urls import url
from .models import Project
from .views import ProjectsList, ProjectDetail
urlpatterns = [
url(r'^$', ProjectsList.as_view(), name='project_list'),
url(r'(?P<slug>[\w-]+)/$',ProjectDetail.as_view() , name='project_details'),]
projects_details.html
{% extends './base.html' %}
{% block content %}
<div>
<a href={{ object.get_absolute_url }}>
<h4> {{object.title}} </h4>
</a>
<ul>
{% for task in tasks %} <----> NO OUTPUT <li>
<li> {{task}}</li>
{% endfor %}
</ul>
</div>
{% endblock content %}
Sorry for my bad English.
Project is the model class, so doing (list=Project) doesn't make sense.
If you want to access the object in the detail view's get_context_data method, you can use self.object:
def get_context_data(self, **kwargs):
context = super(ProjectDetail, self).get_context_data(**kwargs)
context['tasks'] = Task.objects.filter(list=self.object)
return context
However, you don't actually have to override the get_context_data method at all. In your template, you can follow the relationship backwards from a project to get its tasks:
{% for task in object.task_set.all %}
<li>{{task}}</li>
{% endfor %}
Django Template not displaying model data, showing blank page
...Have a look at it:
models.py
class appointment(models.Model):
patient_name1= models.ForeignKey('identity')
appoint_date= models.DateTimeField('Appoinment time and date')
patient_info= models.TextField()
fees= models.CharField('Fees',max_length=100,blank=True)
class Meta:
verbose_name = 'Appointment Detail'
verbose_name_plural = 'Appoinment Details'
ordering = ['appoint_date']
def __str__(self):
return '%s (%s)' % (self. patient_name1, self.appoint_date)
views.py
from django.shortcuts import render
from .models import identity, appointment
def index(request):
return render(request, 'appoint/index.html')
def appointment_list(request):
Appointments = appointment.objects.all()
context = {'Appointments': Appointments}
return render(request, 'appoint/appointment_list.html', context)
appointment_list.html
<p>{{Appointments.patient_name1}}</p>
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^appointment_list/$', views.appointment_list, name='appointment_list'),
url(r'^aboutme/$', views.aboutme, name='about_us'),
url(r'^contact/$', views.contact, name='contact_us'),
url(r'^apply_appoint/$', views.apply_appoint, name='apply_appoint'),
]
please help me i am new to Django 1.9
you need to iterate over the queryset and then access object's attribute:
<p>
{% for appointment in Appointments %}
{{ appointment.patient_name1 }}
{% endfor %}
</p>
Appointments is a queryset which is a list of instances of Appointment class.
and you need to name your classes with Capital letter btw. Normally objects are in lowercase and class names begin with Capital letter.
Appointments is a list of model objects you need to loop over them in template
like this:
<p>
{% for object in Appointments %}
{{ object.patient_name1 }} , {{ object.appoint_date }}
{% endfor %}
</p>