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

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.

Related

get request in django?

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.

Django 2.0 NoReverseMatch: not a registered namespace

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):
....

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

Data not shown in Django admin after adding by my form

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

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.