How to pass a query set to the context class in Django? - python

I am trying to pass a queryset object to django context class, but doing so results in the following error: TypeError('context must be a dict rather than %s.' % context.__class__.__name__)
Now i understand that the context accepts only a dictionary but i am following an example from a book called django_unleashed which uses Django version 1.8 and i am using django 2.0. and i guess it was done like that in previous versions.
So my question is how should i do this step correctly using django 2.0
from django.shortcuts import render
from django.http import HttpResponse
from .models import Tag
from django.template import Context, loader
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template('organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(context)
return HttpResponse(output)

As the error suggests, you should use a regular dictionary for the context:
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template('organizer/tag_list.html')
context = {'tag_list': tag_list}
output = template.render(context)
return HttpResponse(output)
In practice, you would usually use the render shortcut rather than manually rendering the template:
from django.shortcuts import render
def homepage(request):
tag_list = Tag.objects.all()
context = {'tag_list': tag_list}
return render(request, 'organizer/tag_list.html', context)

'''you have a model class named 'Tag',
wish your template is on ' Project directory/ app directory/ template/ same name of app directory'
example: let your project name is 'Website' and app name is 'organizer' then the template will be on: 'Website/ organizer/ templates/ organizer/ tag_list.html' Confirm your TEMPLATES setting is default on setting.py file."'
from django.shortcuts import render
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
context = { 'tag_list' : tag_list}
return render ( request, 'organizer/tag_list.html', context)

Related

Python Error: object has no attribute 'META'

I have a bit of a problem with my view here as it is returning an error on django but I don't know what I have done wrong. My code is as follows in my view:
from django.views.generic import TemplateView
from django.shortcuts import render
from community.models import Community
class CommunityLanding(TemplateView):
def get_context_data(request):
template_name = 'community/landing.html'
objects = Community.objects.all()
context = {
'object': objects
}
return render(request, template_name, context)
Can anyone point me in the right direction?
Almost everything about your code is wrong. The template_name attribute is defined inside the class not inside the get_context_data method. The get_context_data method only takes one parameter and it is the 'self' variable, and should only return the context. You don't need to render your template manually, other methods take care of that as long as you have the template_name defined.
from django.views.generic import TemplateView
from community.models import Community
class CommunityLanding(TemplateView):
template_name = 'community/landing.html'
def get_context_data(self):
context = super().get_context_data()
objects = Community.objects.all()
context['object'] = objects
return context
You should read more about subclassing the generic views

How do I import and use the python files in a view in django?

What I want to do is I'd like to call the module( RSAtest ) already created in view in Django. I am calling a function in RSAtest module from AboutPageView. But for some reason, it shows the following error: ModuleNotFoundError: No module named 'webapp.functional' Could you give me an idea how to use modules in Django?
# howdy/views.py
from django.shortcuts import render
from django.views.generic import TemplateView
from webapp.functional import RSAtest
class HomePageView(TemplateView):
def get(self, request, **kwargs):
return render(request, 'index.html', context=None)
# Add this view
class AboutPageView(TemplateView):
RSAtest.main()
#os.system('python3 howdy/RSAtest.py')
template_name = "about.html"
Thanks for the any help.

How to retrieve data from an existing db file and display it on webpage using Django?

This is the views.py file:
from django.shortcuts import render
from django.views.generic import TemplateView
from .models import Report
import random
class HomePageView(TemplateView):
def get(self, request, **kwargs):
args = {}
data = Report.objects.all()
args['data'] = data
return render(request, 'index.html',args)
I'm finding it difficult to understand the framework since I'm a beginner. So please help me.
You are trying to use class base view which will be different from function base view, to pass context data to template in class base view you need to override get_context_data method as below:
class HomePageView(TemplateView):
""" Home page view """
template_name = "index.html"
def get_context_data(self, **kwargs):
# first of all calling it's parent class method to get context (if any)
context = super(HomePageView, self).get_context_data(**kwargs)
# now you can update context dictionary as below:
context['data'] = Report.objects.all()
return context
Now you can access data in your template using {{ data }}
You can display the FileField content by passing the following
{{ context_obj.file_field_name.url }} in the template.

Django 1.9 : Passing arguments from urls.py to a class view

I am creating a small web application as a mini project of mine to learn the Django framework. I'm on Version 1.9.4, on OS X. I'm trying to pass a string in the URL that will be sent to a class-based view, and it will return a different template based on the URL. To my knowledge, doing (?P) will allow the input of dynamic text. \w is for characters, and writing <name> will pass it as a variable. Is this configured right, or is this is not the correct way to do it?
The reason I'm concerned is that the Django documentation uses method views, while I am using class-based views.
urls.py
from django.conf.urls import url
from . import views
app_name = 'xyz'
urlpatterns = [
url(r'^create/(?P<ty>\w+)$', views.ArticleView.as_view(), name='article-form'), #.as_view() to turn Class into View
]
views.py
class ArticleCreate(View):
l = {
'weapon': WeaponForm,
'map': MapForm,
'operator': OperatorForm,
'gadget': GadgetForm,
'skin': SkinForm
}
ty = ty.lower()
template_name = 'xyz/create_article_form.html'
def get(self, request):
return render(request, self.template_name)
def post(self, request):
pass
The arguments that are being passed to the url should be "catched" within the view inside the relevant function, for example:
def get(self, request, ty):
ty = ty.lower()
return render(request, self.template_name)

RemovedInDjango18Warning: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is deprecated

I am doing a Django project and when I tried to access 127.0.0.1:8000/articles/create, I got the following error in my Ubuntu terminal:
/home/(my name)/django_test/article/forms.py:4: RemovedInDjango18Warning: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is deprecated - form ArticleForm needs updating
class ArticleForm(forms.ModelForm):
In addition, I also got the following error when visiting my actual localhost site:
ValueError at /articles/create/
The view article.views.create didn't return an HttpResponse object. It returned None instead.
Here is my forms.py file:
from django import forms
from models import Article
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
And here is my views.py file:
from django.shortcuts import render_to_response
from article.models import Article
from django.http import HttpResponse
from forms import ArticleForm
from django.http import HttpResponseRedirect
from django.core.context_processors import csrf
#import pdb; pdb.set_trace()
# Create your views here.
def articles(request):
language = 'en-us'
session_language = 'en-us'
if 'lang' in request.COOKIES:
language = request.COOKIES['lang']
if 'lang' in request.session:
session_language = request.session['lang']
return render_to_response('articles.html',
{'articles':
Article.objects.all(), 'language' : language,
'session_language' : session_language})
def article(request, article_id=1):
return render_to_response('article.html', {'article':
Article.objects.get(id=article_id) })
def language(request, language='en-us'):
response = HttpResponse("setting language to %s" %
language)
response.set_cookie('lang', language)
response.session['lang'] = language
return response
def create(request):
if request.POST:
form = ArticleForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/articles/all')
else:
form = ArticleForm()
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('create_article.html', args)
I'm not sure how to fix this problem. I looked at the Django documentation but I couldn't find a solution to my problem so any help would be appreciated.
For your form, it's a warning, not an error, telling you that in django 1.8, you will need to change your form to
from django import forms
from models import Article
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = '__all__' # Or a list of the fields that you want to include in your form
Or add an exclude to list fields to exclude instead
Which wasn't required up till 1.8
https://docs.djangoproject.com/en/1.8/topics/forms/modelforms/#selecting-the-fields-to-use
As for the error with your views, your return is inside of an if statement: if request.POST: so when it receives a get request, nothing is returned.
def create(request):
if request.POST:
form = ArticleForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/articles/all')
else:
form = ArticleForm()
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('create_article.html', args)
Just dedent the else block so that it's applying to the correct if statement.
You just need...
from django import forms
from models import Article
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
exclude = ()
...to fix your form. You'll need to post your view code to see what's up with that.
if you use fields = __all__ as Ngenator suggested, and if it's a project that might have to run under various versions of Django, the following conditional will be needed:
if django.VERSION >= (1, 6):
fields = '__all__' # eliminate RemovedInDjango18Warning
otherwise you get the error django.core.exceptions.FieldError: Unknown field(s) (a, l, _) specified for CrispyTestModel, as seen here: https://travis-ci.org/maraujop/django-crispy-forms/jobs/56996180
In your view, you don't return anything if the request is not a POST. You should move everything from the else statement onwards back one indent.

Categories