Data not shown in Django admin after adding by my form - django

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'),
]

Related

Django Models not showing in template

I am finding it quite difficult to display django models in template. The Model does not show at all in the template. Any help will indeed be appreciated.
models.py
from django.db import models
from django.urls import reverse
from datetime import datetime
class Blog(models.Model):
name= models.CharField(max_length = 200)
company= models.CharField(max_length = 200)
post = models.CharField(max_length = 200)
author= models.ForeignKey('auth.User', on_delete = models.PROTECT)
mantra= models.CharField(max_length = 200, help_text='make it short and precise')
photo= models.ImageField(upload_to='photos/jobs/%Y/%m/%d/', blank=False, null=False)
publish = models.BooleanField(default =True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('index')
views.py
from django.shortcuts import render
from django.views.generic import TemplateView,ListView
from django.views.generic.edit import CreateView
from .models import Blog
class Home(ListView):
model = Blog
context_object_name = 'test'
template_name='test.html'
fields = ['name', 'company', 'post', 'author', 'mantra', 'continent', 'photo']
urls.py
from django.urls import path
from .views import Home
urlpatterns=[
path('', Home.as_view(), name='index'),
]
Template
<p>{{test.name}}</p>
<p>{{test.author}}</p>
<p>{{test.post}}</p>
You should loop on the queryset:
{% for object in test %}
<p>{{object.name}}</p>
<p>{{object.author}}</p>
<p>{{object.post}}</p>
{% endfor %}

Error: 'User' object has no attribute 'get' in django-tables

My aim is to print data from database as a table. Can i do it with simple forms?
views.py
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from django.shortcuts import render
from .models import *
class IndexView(ListView):
template_name = 'Dashboard/index.html'
def get_queryset(self):
return ccc
class CourseView(DetailView):
model = Course
template_name = 'Dashboard/course.html'
class TeacherView():
def teacher(request):
return render(request, 'Dashboard/teacher.html', {'table' : User.objects.all()})
teacher.html
{% load render_table from django_tables2 %}
<!doctype html>
<html>
<head>
<title>All Teachers</title>
</head>
<body>
{% render_table table %}
</body>
</html>
urls.py
from django.urls import path
from . import views
app_name = 'Dashboard'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.CourseView.as_view(), name='detail'),
path('teacher/', views.User, name='teacher'),
]
models.py
from django.db import models
class User(models.Model):
unam = models.CharField(max_length=200)
uid = models.AutoField(primary_key=True)
umob = models.IntegerField()
umail = models.EmailField()
uimg = models.CharField(max_length=1000, default='null')
def __str__(self):
return self.unam
settings.py
INSTALLED_APPS = [
'django_tables2',
'Dashboard.apps.DashboardConfig',
My aim is to print data from database as a table. Can i do it with simple forms?
You do not have a "User" view inside your views.py.
path('teacher/', views.User, name='teacher')
But a TeacherView. I suggest you use a Template View and define your Users Context
https://docs.djangoproject.com/en/2.0/ref/class-based-views/base/#templateview
And if I might suggest, do not prefix Model Attributes with "u". You User Model already speaks for itself. Even though naming it "User" might clash at a certain point of time with the Auth User Model from Django.
And last but not least try to avoid * imports if you can
change the views.py as follows
from django.views import View
class TeacherView(View):
def get(self, request):
return render(request, 'Dashboard/teacher.html', {'table' : User.objects.all()})
Now also change the urlpatterns as follows
path('teacher/', views.TeacherView.as_view(), name='teacher')
I hope this works for you.

How to use {{ post.title }} from blog.models into home_app template

I want to use the {{ post.title }} and {{ for post in object_list }}
into my home template to show the latest 4 posts, I tried to import from blog.models import Post, but it doesn't work. I guess I'm putting it in the wrong place.
blog.models
from django.db import models
from ckeditor.fields import RichTextField
class Post(models.Model):
title = models.CharField(max_length = 140)
image = models.ImageField(upload_to="media", blank=True)
body = RichTextField(config_name='default')
date = models.DateField()
def __str__(self):
return self.title
home.urls
from django.urls import path
from . import views
urlpatterns = [
path('', views.HomePageView.as_view(), name='home'),
]
home.views
from django.views.generic import TemplateView
from allauth.account.forms import LoginForm
class HomePageView(TemplateView):
template_name = 'home/index.html'
mysite tree look like this
mysite
home
admin
app
models
tests
urls
views
blog
admin
app
models
tests
urls
views
You can override get_context_data and add the latest blog posts to the template context.
from blog.models import Post
class HomePageView(TemplateView):
template_name = 'home/index.html'
def get_context_data(self, **kwargs):
context = super(HomePageView, self).get_context_data(**kwargs)
context['object_list'] = Post.objects.order_by('-date')[:4]
return context

Having trouble with slug

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.

Django App Display No Result

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 %}