Django import issues not working propely - python

i'm passing this guide: http://www.djangobook.com/en/2.0/chapter04.html
It instruct to do:
We no longer have to import get_template, Template, Context, or
HttpResponse. Instead, we import django.shortcuts.render. The import
datetime remains.
However when I'm doing it in my code:
from django.http import Http404
import datetime
from django.shortcuts.render
def current_datetime(request):
now = datetime.datetime.now()
return render(request, 'current_datetime.html', {'current_date': now})
I get these errors:
on import render line:
Expected:import
on render code line:
Undefined variable: render
if I change the import to :
from django.shortcuts import render
then everything is working.
Why is this happaning?
EDIT:
from django.http import Http404
import datetime
import django.shortcuts.render
def current_datetime(request):
now = datetime.datetime.now()
return render(request, 'current_datetime.html', {'current_date': now})
not working either see print screen:
http://i57.tinypic.com/5cyiz7.png
it tells me that the import is unused and still doesn't recognize render

In first case it should be
import django.shortcuts.render as render
and use
return render(request, 'current_datetime.html', {'current_date': now})
If you use only import django.shortcuts.render instead of import django.shortcuts.render as render. Then, return render(request, 'current_datetime.html', {'current_date': now}) won't work. Use return django.shortcuts.render(request, 'current_datetime.html', {'current_date': now}) instead.

from django.shortcuts.render
except this you need to do import django.shortcuts.render.
Or from django.shortcuts import render as you did last.
In your second edit you did import django.shortcuts.render but calling only render so return like this
return django.shortcuts.render(request, 'current_datetime.html', {'current_date': now})
Your final code should be:-
from django.http import Http404
import datetime
import django.shortcuts.render
def current_datetime(request):
now = datetime.datetime.now()
return django.shortcuts.render(request, 'current_datetime.html', {'current_date': now})

Related

Can't call objects from class in loop Python Django

I an newbee to Django and I realise that it is a very silly question but, when I put objects in a HTML code to call index from data base I recieve just text of what I am calling: List of news(item.title)(item.title)(item.title)(item.title)
views.py:
from django.shortcuts import render
from django.http import HttpResponse
from .models import News
def index(request):
news = News.objects.all()
res = '<hi>List of news</h1>'
for item in news:
res += f'<div><p>(item.title)</p></div>'
return HttpResponse(res)
from django.shortcuts import render
from django.http import HttpResponse
from .models import News
def index(request):
news = News.objects.all()
res = '<hi>List of news</h1>'
for item in news:
res += f'<div><p>{item.title}</p></div>'
return HttpResponse(res)

NameError: name doohickey is not defined

I am having issues importing a function from a module I created into my code. I am getting an error stating that the function is not defined, despite importing the module into my file.
The error message:
something = doohickey()
NameError: name 'doohickey' is not defined
get_random_tweet.py
import twitter
api = twitter.Api(consumer_key='',
consumer_secret='',
access_token_secret='')
timeline = api.GetUserTimeline(screen_name='realDonaldTrump',
include_rts=False,
trim_user=True,
exclude_replies=True,
count=6)
def doohickey():
pprint(timeline)
return {'index': "<i> something </i>"}
My views.py
from django.shortcuts import render
from django.http import HttpResponse
from hello.sampled_stream import okdood
import hello.get_random_tweet
from .models import Greeting
# Create your views here.
def index(request):
# return HttpResponse('Hello from Python!')
# okdood()
something = doohickey()
return render(request, "index.html")
I have also attempted the following:
from django.shortcuts import render
from django.http import HttpResponse
from hello.sampled_stream import okdood
from hello.get_random_tweet import doohickey
from .models import Greeting
# Create your views here.
def index(request):
# return HttpResponse('Hello from Python!')
# okdood()
something = doohickey()
return render(request, "index.html")
Error message:
something = doohickey()
NameError: name 'doohickey' is not defined
and
from django.shortcuts import render
from django.http import HttpResponse
from hello.sampled_stream import okdood
import hello.get_random_tweet
from .models import Greeting
# Create your views here.
def index(request):
# return HttpResponse('Hello from Python!')
# okdood()
something = hello.get_random_tweet.doohickey()
return render(request, "index.html")
Error message:
something = hello.get_random_tweet.doohickey()
NameError: name 'doohickey' is not defined
It looks like the issue is that you are not referring to the doohickey function as part of the hello.get_random_tweet namespace. You can do this in several ways:
from django.shortcuts import render
from django.http import HttpResponse
from hello.sampled_stream import okdood
from hello.get_random_tweet import doohickey
from .models import Greeting
# Create your views here.
def index(request):
# return HttpResponse('Hello from Python!')
# okdood()
something = doohickey()
return render(request, "index.html")
or
from django.shortcuts import render
from django.http import HttpResponse
from hello.sampled_stream import okdood
import hello.get_random_tweet
from .models import Greeting
# Create your views here.
def index(request):
# return HttpResponse('Hello from Python!')
# okdood()
something = hello.get_random_tweet.doohickey()
return render(request, "index.html")
As your code is currently structured, you import the hello.get_random_tweet module, but when you refer to doohickey Python is looking for it in the local namespace. However, it should be looking for it in the hello.get_random_tweet namespace. You can either import the function and add it to the local namespace, as shown in the first snippet, or refer to the function in the imported module's namespace as shown in the second snippet.
Might be a copy/paste error, but you're missing endquotes on a few lines here, and the closing bracket:
api = twitter.Api(consumer_key='',
consumer_secret='',
access_token_secret=''
Should be:
api = twitter.Api(consumer_key='',
consumer_secret=''
access_token_key=''
access_token_secret='')

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.

Sending JSON data from view in Django

I have to store some data in the window object to use it un the frontend rendering. I have a model:
from django.db import models
from tools.various.db import Base
from tools.files.fields import CustomImgField, IMAGES_DIRECTORY_ORIGINAL
from django.conf import settings
class myModel(Base):
myName = models.CharField(max_length=100, verbose_name='myName')
mySurname = models.CharField(max_length=100, verbose_name='mySurname')
I have a view:
from django.http import Http404
from django.views.generic import TemplateView
from django.http import JsonResponse
from json import dumps
from front.models import Language
from front.models import myModel
class BaseView(TemplateView):
def get_context_data(self, **kwargs):
context = super(BaseView, self).get_context_data(**kwargs)
context['myData'] = myModel.objects.value()
return context
And I want to retrieve myData as a JSON object and store it in window object:
window.app = {
data: {},
settings: {
staticUrl: '{{ STATIC_URL }}',
urls: {},
storedData: {{ myData|jsonify|safe }}
}
};
But I get this response:
[{'myName': u'foo', 'mySurname': u'bar', u'id': 1L, 'order': 0L}] is not JSON serializable
Does anyone knows what I'm doing wrong?
Thanks!
EDIT:
I just tried return list(context) as André Laszlo proposes: it returns
Exception Value: list indices must be integers, not str
But if I use:
context['myData'] = list(myModel.objects.values())
return context
It seems to work. I'm going to read the documentation about 'list()'.
You are returning a python dictionary, you need to serialize it to JSON using json.dumps()
You are already importing json but not making use of it.
from django.http import Http404
from django.views.generic import TemplateView
from django.http import JsonResponse
from json import dumps
from front.models import Language
from front.models import myModel
class BaseView(TemplateView):
def get_context_data(self, **kwargs):
context = super(BaseView, self).get_context_data(**kwargs)
context['myData'] = myModel.objects.value()
return dumps(context)
Additionally, you might want to read up on ujson - Faster than the builtin json library.
Preferably, if you are using Django 1.7+ you can do:
from django.http import Http404
from django.views.generic import TemplateView
from django.http import JsonResponse
from json import dumps
from front.models import Language
from front.models import myModel
from django.http import JsonResponse
class BaseView(TemplateView):
def get_context_data(self, **kwargs):
context = super(BaseView, self).get_context_data(**kwargs)
context['myData'] = myModel.objects.value()
return JsonResponse(context)
I think that the problem is that your list is actually not a list, it's a QuerySet that just looks like a list when printed.
Have you tried:
context['myData'] = list(myModel.objects.values())
return context
I think it should return a list with dictionaries, which should be JSON serializeable. Please update your question with your results if it doesn't work.

DRF - Method 'GET' not allowed

I'm trying to setup a class based view in Django Rest Framework.
This is my urls.py -
from django.conf.urls import patterns, include, url
from rest_framework.urlpatterns import format_suffix_patterns
from django.contrib import admin
from TidalDEV import views
admin.autodiscover()
urlpatterns = patterns('',
url(r'^test/(?P<pk>[0-9]+)/$', views.TESTXMLDetail.as_view()),
)
And this is my view -
import os, tempfile, zipfile
from django.shortcuts import render
from django.core import serializers
from django.core.serializers import serialize
from django.core.servers.basehttp import FileWrapper
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer, XMLRenderer
from rest_framework.parsers import JSONParser
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated, AllowAny
from itertools import chain
from TAPI.renderers import *
from TAPI.models import *
from TAPI.serializers import JobdtlSerializer, JobmstSerializer, TrgjobSerializer, JobdepSerializer
class TESTXMLDetail(APIView):
permission_classes = (AllowAny,)
"""
Retrieve, update or delete a snippet instance.
"""
def get_object(self, pk):
try:
mst = Jobmst.objects.db_manager('AdmiralDEV').raw("""
query1""", [pk])
dtl = Jobdtl.objects.db_manager('AdmiralDEV').raw("""
query2""", [pk])
dep = Jobdep.objects.db_manager('AdmiralDEV').raw("""
query3""", [pk])
trg = Trgjob.objects.db_manager('AdmiralDEV').raw("""
query4""", [pk])
except Jobmst.DoesNotExist:
return HttpResponse(status=404)
def get(self, request, pk, format=None):
jobmststring = JobmstSerializer(mst)
jobdtlstring = JobdtlSerializer(dtl)
jobdepstring = JobdepSerializer(dep, many=True)
trgjobstring = TrgjobSerializer(trg, many=True)
jobmst_serialized = {'jobmst': jobmststring.data}
jobdtl_serialized = {'jobdtl': jobdtlstring.data}
jobdep_serialized = [{'jobdep':item} for item in jobdepstring.data]
trgjob_serialized = [{'trgjob':item} for item in trgjobstring.data]
jobgroup = jobmst_serialized, jobdtl_serialized, jobdep_serialized, trgjob_serialized
jobgroupresponse = TESXMLResponse(jobgroup)
return jobgroupresponse
When I run the URL all I get is the XML format but then it says -
<detail>Method 'GET' not allowed.</detail>
I've tried setting the permission class in the view as above and I've also put the following lines in my settings.py what gives?
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
),
You're getting this error because the DRF APIView doesn't have a get method (or a method for any HTTP request type actually).To get your code working you can either rename your get_object method to get (making sure you add the expected parameters request and format), or you can write a get method to return your response:
class TESTXMLDetail(APIView):
def get(self, request, pk, format=None):
return self.get_object(pk)
def get_object(self, pk):
...
...

Categories