Variable import does not work in views.py - python

Why doesn't the import of a variable outside of a function work in views.py? (ms_fields.py is a file in the same folder)
==== This works: the variable "MS_FIELDS" is imported properly =============
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, RequestContext, get_object_or_404
def current_quote(request):
from .ms_fields import MS_FIELDS #import within the function
return render_to_response('mis/current_quote.html', locals(), context_instance=RequestContext(request))
=== This doesnt work: "local variable 'MS_FIELDS' referenced before assignment"=====
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, RequestContext, get_object_or_404
from .ms_fields import MS_FIELDS # import at the beginning of the file
def current_quote(request):
MS_FIELDS = MS_FIELDS
return render_to_response('mis/current_quote.html', locals(), context_instance=RequestContext(request))
Why is that? Shouldn't the import function make a variable available inside the entire file?
Thanks a lot!

It's not the import that doesn't work, it's the assignment. By assigning to MS_FIELDS within the function, you are telling Python it's a local var, which overrides the global name from the import.
I don't understand why you'd do that anyway. Just pass MS_FIELDS to the context explicitly. Using locals() is a hack, and not a very nice one.

Related

ImportError: cannot import name 'forms' from 'basicapp'

form.py:
from django import forms
class FormName(forms.Form):
name=forms.CharField()
email=forms.EmailField()
text=forms.CharField(widget=forms.Textarea)
views.py:
from django.shortcuts import render
from .forms import forms
def index(request):
return render(request,'basicapp/index.html')
def form_page(request):
Form = forms.FormName()
return render(request,'basicapp/form_page.html',{'form':Form})
I dont know what is wrong here! when I run server, it makes an error, saying ImportError : cannot import name 'forms' from 'basicapp'.
First of all, it looks like you have named your forms file, form.py and you are trying to access a module called forms. Rename form.py file to forms.py.
Second, you are trying to import forms from your forms file. This is actually referencing forms you imported via from django import forms. You have a couple options here. In your view file you can either import .forms or from .forms import FormName I prefer the latter.
So, after you rename form.py to forms.py I would rewrite views.py to look like this:
from django.shortcuts import render
from .forms import FormName
def index(request):
return render(request,'basicapp/index.html')
def form_page(request):
this_form = FormName()
return render(request,'basicapp/form_page.html',{'form':this_form})
You made two mistakes in your code
1) Your form file should be named forms.py and not form.pY
2) your views.py import code should be
from django.shortcuts import render
from basicapp import forms
There is an issue in your view.py
replace
below line
from .forms import forms
with
from <your app name>.forms import forms
You are getting this error because django is trying to find it in root folder where your manage.py exist.

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='')

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.

Django Tutorial: name 'HttpResponse' is not defined

I am learning Django via their tutorial for getting started. I have looked at other Django Tutorial errors and did not see this one (although I did not search every listing).
I have made the changes to mysite/urls.py and polls/urls.py exactly as they demonstrate and I have run the server command:
python manage.py runserver
I get the following error:
Since I am new to Django, I do not know what is going on. Please help.
from django.http import HttpResponse
in your views file at the top
Put this import in your poll/views.py before using HttpResponse.
from django.http import HttpResponse
from django.http import HttpResponse
add this line on the top of polls/views.py file. I am new too, and had the same error. good Luck and i see u around.
in your polls/views.py
By default is :
from django.shortcuts import render
change to:
from django.shortcuts import render,HttpResponse
this will call the HttpResponse class
In my case the import was there, but when I called HttpsResponse I called it with small h as a typo instead of the capital H
from django.http import HttpResponse
def home(request):
return HttpResponse("Hello!") #==> This one was with httpResponse so the same error been received.
I had imported HttpResponse and still got this error.
If you use Apache server as your primary server for web, try restarting Apache and reloading the page.
For me it was because I used singe quotes (') instead of double quotes (")
Check your import statement.
Check your function. I had "HttpsResponse" instead of "HttpResponse"
Good luck.

Django import issues not working propely

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

Categories