I'm working on an app called Start the dark from the tutorial django from ground up.
I have just started on the tutorial and I have difficulty displaying the result on html.
The app is suppose to display the description of the event . The creator of the event and the time it was posted and when I type the link . It's display nothing.
I spent few hours troubleshooting and so far I learn't the problem is not my html form either it's my URL cause I did some test. I think it's getting the results from the models.py into my views.py and executing it
My models.py are :
from django.db import models
from datetime import datetime, timedelta
from django.contrib.auth.models import User
from django.db.models.query import QuerySet
class Event(models.Model):
description = models.TextField()
creation_date = models.DateTimeField(default = datetime.now)
start_date = models.DateTimeField(null=True, blank= True)
creator = models.ForeignKey(User , related_name = 'event_creator_set')
attendees = models.ManyToManyField(User , through = "Attendance")
latest = models.BooleanField(default=True)
def __unicode__(self):
return self.description
def save(self, **kwargs):
now = datetime.now()
start = datetime.min.replace(year = now.year , month=now.month,day=now.day)
end = (start + timedelta(days=1)) - timedelta.resolution
Event.objects.filter(latest=True, creator=self.creator).filter(creation_date__range=(start,end)).update(latest=False)
super(Event,self).save(**kwargs)
class Attendance(models.Model):
user = models.ForeignKey(User)
event = models.ForeignKey(Event)
registration_date = models.DateTimeField(default=datetime.now)
def __unicode__(self):
return "%s is attending %s" %(self.user.username,self.event)
My views.py
from events.models import Event
from django.shortcuts import render_to_response
from django.template import RequestContext
def tonight(request):
events = Event.objects.filter(latest=True)
return render_to_response('events/tonight.html',{'events':events},context_instance = RequestContext(request))
My tonight.html
{% if events %}
<ul>
{{events.description}}
{{events.start_date}}
{{events.creator}}
</ul>
{% endif %}
My events URL.CONF
from django.conf.urls.defaults import *
from django.contrib import admin
from events import views
urlpatterns = patterns('events.views',
url(r'^tonight/$','tonight',name='ev_tonight')
)
My main URLconf
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls.static import static
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^events/',include('events.urls')),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
Some other models.
from django.db import models
from django.contrib import admin
class student(models.Model):
First_name = models.CharField(max_length=30)
Last_name = models.CharField(max_length=30)
Age = models.BigIntegerField()
Body = models.TextField()
def __unicode__(self):
return self.First_name
Here events is a queryset. Refer django docs on querysets. You need to iterate over the objects in it. Edit your template code like this;
{% if events %}
{% for each_event in events %}
<ul>
{{each_event.description}}
{{each_event.start_date}}
{{each_event.creator}}
</ul>
{% endfor %}
{% endif %}
Related
I have problem with django request.I dont know. I tried to do everything, but I got
'blog' object has no attribute 'get'. I want to do mini blog on my website,but it isnt working now. I would like to get all objects from database.(Sorry,If I did something wrong,I am beginner in django and tried to functions for my website) :)
models.py
from django.db import models
# Create your models here.
CHOOSE =[
('Usual','Обычный тариф'),
('Premium','Премиум тариф'),
('Prise','Аукционный')
]
class VDSTARIFS( models.Model):
id = models.CharField(max_length=40, primary_key= True,serialize=True)
name = models.CharField(max_length=20, verbose_name = 'Цены')
choosen = models.CharField(max_length= 20, choices = CHOOSE, verbose_name = 'Тариф', help_text='Выбор тарифного плана.')
title = models.CharField(max_length= 15)
def __str__(self):
return str(self.title)
class blog(models.Model):
id = models.CharField(max_length=40, primary_key= True,serialize=True)
message = models.TextField( verbose_name= 'Сообщение блога')
titleblog = models.CharField(max_length=50, verbose_name = 'Название')
img = models.ImageField(upload_to = 'admin/', verbose_name= 'Картинка' )
def __str__(self):
return str(self.titleblog)
def get_all_objects(self): ##maybe I have troubles with it.
queryset = self.__class__.objects.all()
blog.html
{% csrftoken %}
{% for item in message %}
{% endfor %}
views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render
from django.http import HttpResponseRedirect
import os
from polls.models import VDSTARIFS
from polls.models import blog
from django.template.loader import render_to_string
def index_view(request):
#return HttpResponse("<h1>Hello</h1>")
return render(request, "home.html", {})
def about(request):
return render(request, "about.html", {})
def minecraft(request):
return render(request, "minecraft.html",{})
def vds(request):
HTML_STRING = render_to_string("vds.html", context = context1)
return HttpResponse(HTML_STRING)
try:
VDS1 = VDSTARIFS.objects.get(id=0)
name = VDS1.name
except VDSTARIFS.DoesNotExist:
VDS1 = None
context1 = {
'name':name,
'prise':VDS1,
}
def messagesblog(request,self):
HTML_STRING = render_to_string('blog.html')
return HttpResponse(HTML_STRING)
urls.py
from django.contrib import admin
from django.urls import path
from polls import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index_view, name='home'),
path('vds', views.vds, name='vds' ),
path('minecraft', views.minecraft, name='minecraft' ),
path('about', views.about, name='about'),
path('blog', views.blog, name='blog')
]
The actual error is probably caused by the wrong url pattern:
path('blog', views.blog, name='blog')
views.blog refers to the blog model due to:
from polls.models import blog
What you need here is the view not the model, so:
path('blog', views.messagesblog, name='blog')
Then, remove the "self" argument from your messagesblog function.
Use the "render" function from django.shortcuts and provide a context with the blog objects:
def messagesblog(request):
return render(request, "blog.html", {message: blog.objects.all()})
That might solve your problem.
Still, there are some things you could improve.
E.g.: Don't use "id" fields in your model definitions if you don't really, really have to, as this is usually an auto-generated number (BigInt) field.
That's only one tip from an old Django veteran happy to be finally heard. You'll find out much more yourself as you proceed.
I am a complete beginner so I apologies for my noobiness explanation. I am in the process of categorising my blogs.
I created a model -> migrated it -> imported in view.py -> Imported the view that I created into urls.py -> and created URL for my new page but when I add the href to other pages (home) it takes me to the error.
My codes:
models.py
class Category(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Post(models.Model):
title = models.CharField(max_length=100)
content=models.TextField()
date_posted=models.DateTimeField(default=timezone.now)
author=models.ForeignKey(User, on_delete=models.CASCADE)
category = models.CharField(max_length=100, default='Engineering')
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
Views.py:
from .models import Post, Category
class CategoryListView(ListView):
model = Post
template_name= 'blog/category_posts.html'
context_object_name = 'posts'
ordering = ['-date_posted']
paginate_by = 3
urls.py:
from django.urls import path
from .views import (
PostListView,
PostDetailView,
PostCreateView,
PostUpdateView,
PostDeleteView,
UserPostListView,
CategoryListView)
path('category/<str:category>/', CategoryListView.as_view(), name='category-posts'),
home.html
{{ post.category }}
In addition to what Arun said.
I think you need to set url_patters in your urls.py. Something like this:
from django.urls import path
from .views import (
PostListView,
PostDetailView,
PostCreateView,
PostUpdateView,
PostDeleteView,
UserPostListView,
CategoryListView)
urlpatterns = [
path('category/<str:category>/', CategoryListView.as_view(), name='category-posts'),
]
You should also pass the category in your url, like this
{{ post.category }}
Because your url needs a str parameter category.
My goal is to Create hyperlinks which would toss a keyword into a views function which would then pull a query from my db onto the page.
GOAL: Press hyperlink which would give me query of a specific major.
I was attemping to use the converter,
So the goal was, 1 being the first step, 3 being final step.
Is this possible?
1) Click the hyperlink -> Major = Accounting
2)URL.py
path(<str:Accounting/, views.Major, name=Major)
3)Views.py
def Major(request, Accounting):
major_choice = professor.objects.filter(Major = Accounting)
return render(request, 'locate/major.html', {'major_choice': major_choice})
NOTE: I replaced variables with what I want it to contain "Accounting", you will notice inside the bottom views.py its called "Major".
Index.html
Accounting
major.html
<ul>
{% for major in major_choice %}
<li>{{major.ProfessorName}}</li>
{%endfor%}
</ul>
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('<str:Major/', views.Major, name='Major')
]
models.py
from django.db import models
class professor(models.Model):
ProfessorIDS = models.IntegerField()
ProfessorName = models.CharField(max_length=100)
ProfessorRating = models.DecimalField(decimal_places=2,max_digits=4)
NumberofRatings = models.CharField(max_length=50)
Major = models.CharField(max_length=50)
def __str__(self):
return self.ProfessorName
views.py
from django.http import HttpResponse
from django.shortcuts import render
from .models import professor
def index(request):
professors = professor.objects.all()
return render(request, 'locate/index.html', {'professors': professors})
def Major(request, major):
major_choice = professor.objects.filter(Major = major)
return render(request, 'locate/major.html', {'major_choice': major_choice})
Please update your url path to this:
path('<str:Major>/', views.Major, name='Major')
And in your html:
Accounting
in views:
def Major(request, Major):
....
I am a beginner to Django.
I want to create a form that allow user to store their data to the database, but I face to an issue.
If I add data through Django admin, the data will shown correctly. But if I add data through my form. Data will store into database successfully but they don't shown in my Django admin.
Note: The Django version I used is 1.11.2
The is my Django admin page. There are 8 data in the database but just show the one I added by the Django admin.
views.py
from django.shortcuts import render
from django.views.generic import CreateView
from .forms import ApplyFormCreateForm
from .models import ApplyForm
class ApplyFormCreateView(CreateView):
form_class = ApplyFormCreateForm
template_name = 'form.html'
success_url = "/"
models.py
from django.db import models
from course.models import Semester
DEFAULT_SEMESTER_ID = 1
class ApplyForm(models.Model):
name = models.CharField(max_length=15)
school = models.CharField(max_length=20)
department = models.CharField(max_length=20)
email = models.EmailField(max_length=100)
is_beginner = models.BooleanField(default=False)
introduction = models.TextField(max_length=2000)
motivation = models.TextField(max_length=2000)
comments = models.TextField(max_length=2000, blank=True)
semester = models.ForeignKey(Semester, default=DEFAULT_SEMESTER_ID)
created_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.school + self.department + self.name
def __str__(self):
return self.school + self.department + self.name
form.html
{% extends "base.html" %}
{% block content %}
<form method='POST'> {% csrf_token %}
{{form.as_p}}
<button type='submit'>Save</button>
</form>
{% endblock content %}
form.py
from django import forms
from .models import ApplyForm
class ApplyFormCreateForm(forms.ModelForm):
class Meta:
model = ApplyForm
fields = [
'name',
'school',
'department',
'email',
'is_beginner',
'introduction',
'motivation',
'comments',
]
url.py
from django.conf.urls import url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from myweb.views import HomeView
from course.views import CourseListView
from applyform.views import ApplyFormCreateView
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', HomeView.as_view(), name='home'),
url(r'^course/$', CourseListView.as_view(), name='course'),
url(r'^apply/$', ApplyFormCreateView.as_view(), name='applyform'),
]
I was writing a model online shop django app, wanted to incorporate slug in it. Having trouble in opening a page.
This is my model:
from __future__ import unicode_literals
from django.db import models
from django.db.models.signals import pre_save
from django.utils .text import slugify
class Customer(models.Model):
customer_name = models.CharField(max_length=200)
slug = models.SlugField(unique = True)
def __str__(self):
return self.customer_name
def get_absolute_url(self):
return reverse("OnlineShop:order", kwargs={"slug": self.slug})
def pre_save_customer_receiver(sender, instance, *args, **kwargs):
slug = slugify(instance.customer_name)
exists = Customer.objects.filter(slug = slug).exists()
if exists:
slug = "%s-%s" % (slug,instance.id)
instance.slug=slug
pre_save.connect(pre_save_customer_receiver, sender = Customer)
This is my view:
def customer(request):
customer_list = Customer.objects.all()
template_path = 'OnlineShop/customer.html'
context={
'customer_list':customer_list,
}
return render(request,template_path,context)
def order(request,slug):
Customer = Customer.objects.filter(slug=slug)
''' some code from here '''
And my template customer.html:
<h1>List of Customers:</h1>
<ul>
{% for customer in customer_list %}
<li><a href='{% url 'order' customer.slug %}'>{{ customer.customer_name }}<br></li>
{% endfor %}
</ul>
This is my urls.py
from django.conf.urls import url
from . import views
urlpatterns=[
url(r'^$',views.customer, name='customer'),
url(r'^customer/(?P<slug>[\w-]+)$',views.order, name='order'),
]
Is the problem in the template? What is wrong?
I hope you've defined your urls.py like below,
from django.conf.urls import url, include
from . import views
onlineshop_patterns = [
url(r'^$', views.customer, name='customer'),
url(r'^customer/(?P<slug>[\w-]+)$', views.order, name='order'),
]
urlpatterns = [
# ...
url(r'^OnlineShop/', include(onlineshop_patterns)),
# ...
]
Read Reverse resolution of URLs and Regex for SlugField.