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)
Related
I was trying to create a django project. Everything was fine until I did a get request using requests.get() in python in my views.py
Following is what my views.py have
from django.http import HttpResponse
from django.shortcuts import render
import re, requests
def codify_data(data_raw):
data = data_raw.json()['data']
if language == 'web':
html_cd = data['sourceCode']
css_cd = data['cssCode']
js_cd = data['jsCode']
def home_page(request):
return render(request,'home/index.html')
def code(request):
link = request.GET.get('link', 'https://code.sololearn.com/c5I5H9T7viyb/?ref=app')
result = re.search(r'https://code.sololearn.com/(.*)/?ref=app',link).group(1)[0:-2]
data_raw = requests.get('https://api2.sololearn.com/v2/codeplayground/usercodes/'+result)
codify_data(data_raw)
The error is shown below:
I have a python django application. I had a view, which I duplicated and changed slightly to create a second view. But they seem to be hooked together and duplicate the page content, when they should be different.
Here is my urls.py
from django.urls import path, include
from django.contrib.auth import views as auth_views
from django.views.generic.base import RedirectView
from . import views
app_name = 'app'
urlpatterns = [
# Journals by Discipline
path('journals-by-discipline/', views.journals_by_discipline, name='journalsByDiscipline'),
path('journals-by-discipline/chart-data/<str:discipline>/', views.journals_by_discipline_chart_data),
path('journals-by-discipline/journals-and-disciplines-map/', views.get_journals_and_disciplines_map),
path('journals-by-discipline/disciplines-list/', views.disciplines_list),
# Journals By Discipline (Elsevier)
path('journals-by-discipline-elsevier/', views.journals_by_discipline_elsevier, name='journalsByDisciplineElsevier'),
path('journals-by-discipline/chart-data/<str:discipline>/', views.journals_by_discipline_chart_data_elsevier),
path('journals-by-discipline/journals-and-disciplines-map/', views.get_journals_and_disciplines_map),
path('journals-by-discipline/disciplines-list/', views.disciplines_list),
]
I have two views, journals_by_discipline and journals_by_discipline_elsevier
Here is my views.py
from django.shortcuts import get_object_or_404, render
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from rest_framework.decorators import api_view
from rest_framework.response import Response
import datetime as datetime
from dateutil.relativedelta import relativedelta
from urllib.parse import unquote
import json
from .onefigr_analysis import Data
# Instantiate Data object to fetch data across all views
data = Data()
# Journals by Discipline Page
def journals_by_discipline(request):
template_name = 'app/journals-by-discipline.html'
return render(request, template_name)
#api_view(['GET'])
def disciplines_list(request):
if request.method == 'GET':
return Response(data.get_disciplines_list())
#api_view(['GET'])
def journals_by_discipline_chart_data(request, discipline):
if request.method == 'GET':
query_discipline = unquote(discipline)
return Response(data.journals_by_discipline_chart_data(discipline))
#api_view(['GET'])
def get_journals_and_disciplines_map(request):
if request.method == 'GET':
return Response(data.journals_and_disciplines_map())
# Journals by Discipline Elsevier Page
def journals_by_discipline_elsevier(request):
template_name = 'app/journals-by-discipline-elsevier.html'
return render(request, template_name)
#api_view(['GET'])
def disciplines_list(request):
if request.method == 'GET':
return Response(data.get_disciplines_list())
#api_view(['GET'])
def journals_by_discipline_chart_data_elsevier(request, discipline):
if request.method == 'GET':
query_discipline = unquote(discipline)
return Response(data.journals_by_discipline_chart_data_elsevier(discipline))
#api_view(['GET'])
def get_journals_and_disciplines_map(request):
if request.method == 'GET':
return Response(data.journals_and_disciplines_map())
In my attempt to create the second view (journals by discipline elsevier), I duplicated the logic used to create the first view. But the result is both pages are the same.
In my Data() class, I have two methods: journals_by_discipline_chart_data and journals_by_discipline_chart_data_elsevier which are similar but not the same. I am trying to call these differently in my views.py file, but it is not working as it should.
How do I unhook these two views?
path('journals-by-discipline/', views.journals_by_discipline),
path('journals-by-discipline/chart-data/<str:discipline>/', views.journals_by_discipline_chart_data),
path('journals-by-discipline-elsevier/', views.journals_by_discipline_elsevier),
path('journals-by-discipline/chart-data/<str:discipline>/', views.journals_by_discipline_chart_data_elsevier),
The first route in each block is different (journals-by-discipline/ != journals-by-discipline-elsevier/). But the second route is the same (both journals-by-discipline/chart-data/<str:discipline>/).
So the route journals-by-discipline/chart-data/<str:discipline>/ will always call the function views.journals_by_discipline_chart_data. It will never reach the second time the route is mentioned.
You could change the second route in the second block to journals-by-discipline-elsevier/chart-data/<str:discipline>/ to be consistant.
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='')
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)
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.