Django get resource in Json - django-views

import json
from django.core import serializers
from django.http import HttpResponse, Http404
from menu.models import *
def Database(request):
if request.method == 'GET':
menus = Menu.objects.all()
return toJSON(serialize(menus))
def serialize(menus):
serialized = []
for obj in menus:
serialized.append(obj.serializer())
return serialized
def toJSON(menus, status=200):
j = json.dumps(menus, ensure_ascii=False)
return HttpResponse(j, status=status, content_type='application/json; charset=utf-8')
I make my views.py like this, but it returns just [], How can I solve this?

did you mean you don't get key-value pair, instead you get just list ?
use
j = json.dumps({"menus":menus}, ensure_ascii=False)
instead of
j = json.dumps(menus, ensure_ascii=False)

Related

program connecting through postman is not working( get the data through POST then filter it accordingly)

from django.core.mail.backends import console
from home.models import Flights
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def status(request):
if request.method == 'POST':
value1 = request.POST.get('status')
if (value1 == "Arrival"):
arr = list(Flights.objects.filter(status="Arrival").values())
return JsonResponse(arr, safe=False)
elif (value1 == "Departure"):
dep = list(Flights.objects.filter(status="Departure").values())
return JsonResponse(dep, safe=False)
else:
results = list(Flights.objects.values())
return JsonResponse(results, safe=False)
return
i tried to give json input through postman then the loop is not executing is it the problem with code or jason data given in postman?

forking django-oscar views shows an error

I forked customer app , to add a tab in http://oscar/accounts/...(example products)
to edit/show catalogue Views (Dashboard>Catalogue)
Error that I get to use that view is
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
I used views with the same method for payment checkout, but this one runs into errors.
# yourappsfolder.customer.apps.py
import oscar.apps.customer.apps as apps
from oscar.apps.dashboard.catalogue import apps as dapps
from django.views import generic
from django.conf.urls import url
from oscar.core.loading import get_class
from .views import ProductListView
class CustomerConfig(apps.CustomerConfig):
name = 'yourappsfolder.customer'
def ready(self):
super().ready()
self.extra_view =ProductListView
def get_urls(self):
urls = super().get_urls()
urls += [
url(r'products/',self.extra_view.as_view(),name='Products'),
]
return self.post_process_urls(urls)
This is the view I copied from oscar.apps.dashboard.catalogue
# yourappsfolder.customer.views
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
from django.views import generic
from oscar.apps.dashboard.catalogue.views import ProductListView as UserProductListView
class ProductListView(UserProductListView):
def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
ctx['form'] = self.form
ctx['productclass_form'] = self.productclass_form_class()
return ctx
def get_description(self, form):
if form.is_valid() and any(form.cleaned_data.values()):
return _('Product search results')
return _('Products')
def get_table(self, **kwargs):
if 'recently_edited' in self.request.GET:
kwargs.update(dict(orderable=False))
table = super().get_table(**kwargs)
table.caption = self.get_description(self.form)
return table
def get_table_pagination(self, table):
return dict(per_page=20)
def filter_queryset(self, queryset):
"""
Apply any filters to restrict the products that appear on the list
"""
return filter_products(queryset, self.request.user)
def get_queryset(self):
"""
Build the queryset for this list
"""
queryset = Product.objects.browsable_dashboard().base_queryset()
queryset = self.filter_queryset(queryset)
queryset = self.apply_search(queryset)
return queryset
def apply_search(self, queryset):
"""
Search through the filtered queryset.
We must make sure that we don't return search results that the user is not allowed
to see (see filter_queryset).
"""
self.form = self.form_class(self.request.GET)
if not self.form.is_valid():
return queryset
data = self.form.cleaned_data
if data.get('upc'):
# Filter the queryset by upc
# For usability reasons, we first look at exact matches and only return
# them if there are any. Otherwise we return all results
# that contain the UPC.
# Look up all matches (child products, products not allowed to access) ...
matches_upc = Product.objects.filter(upc__iexact=data['upc'])
# ... and use that to pick all standalone or parent products that the user is
# allowed to access.
qs_match = queryset.filter(
Q(id__in=matches_upc.values('id')) | Q(id__in=matches_upc.values('parent_id')))
if qs_match.exists():
# If there's a direct UPC match, return just that.
queryset = qs_match
else:
# No direct UPC match. Let's try the same with an icontains search.
matches_upc = Product.objects.filter(upc__icontains=data['upc'])
queryset = queryset.filter(
Q(id__in=matches_upc.values('id')) | Q(id__in=matches_upc.values('parent_id')))
if data.get('title'):
queryset = queryset.filter(title__icontains=data['title'])
return queryset
You have a circular import - move the import of the list view into the ready() method of the app config:
class CustomerConfig(apps.CustomerConfig):
name = 'yourappsfolder.customer'
def ready(self):
super().ready()
from .views import ProductListView
self.extra_view =ProductListView

Serving a django model containing objects

I have following django model:
class Weather(models.Model):
lat_lng = gis_models.PointField()
raw_data = psql_fields.JSONField(null=True)
I have following view:
def weather(request):
data = WeatherModel.objects.all()
js_data = serializers.serialize('json', data)
return HttpResponse(js_data, content_type='application/json')
It throws error saying 'Point object is not json serializable.'
I want this function to return json.
Please help.
The default JSON serializer doesn't know how to serialize Point objects.
Derive your own from Django's encoder. You can also use JsonResponse for shorter code:
from django.contrib.gis.geos import Point
from django.core.serializers.json import DjangoJSONEncoder
from django.http import JsonResponse
class GeoJSONEncoder(DjangoJSONEncoder):
def default(self, obj):
if isinstance(obj, Point):
return obj.coords
return super().default(obj)
def weather(request):
data = WeatherModel.objects.all()
return JsonResponse(data, encoder=GeoJSONEncoder)
You can use JsonResponse with values.
from django.http import JsonResponse
def weather(request):
data = list(WeatherModel.objects.all())
js_data = serializers.serialize('json', data)
return JsonResponse(data, safe=False) # or JsonResponse({'data': data})
Modifed answer from here.

django add() takes exactly 2 arguments (3 given)

models.py
#!/usr/bin/env python
from django.db import models
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import os
import json
import sys
import tempfile
import traceback
import re
import psycopg2
SUCCESS = 1
ERR_BAD_CREDENTIALS = -1
ERR_USER_EXISTS = -2
ERR_BAD_USERNAME = -3
ERR_BAD_PASSWORD = -4
class UsersModel(models.Model):
user = models.CharField(primary_key=True, max_length=128)
password = models.CharField(max_length=128)
count = models.IntegerField()
def login(user1, password1):
try:
con = psycopg2.connect(database='test', user='jeffrey')
cur = con.cursor()
cur.execute('SELECT user FROM UsersModel WHERE user1=user AND password1=password;')
rows = cur.fetchall()
print rows
if len(rows) == 1:
#on success update the count and return the count
cur.execute('UPDATE UsersModel SET count=count+1 WHERE user1=user AND password1=password;')
cur.execute('SELECT count FROM UsersModel WHERE user1=user AND password1=password;')
return cur.fetchone()[0]
else:
return ERR_BAD_CREDENTIALS
except psycopg2.DatabaseError, e:
print 'Error %s' % e
sys.exit(1)
def add(user1, password1):
try:
if user1=='' or len(user1)>128:
return ERR_BAD_USERNAME
elif len(password1)>128:
return ERR_BAD_PASSWORD
con = psycopg2.connect(database='test', user='jeffrey')
cur = con.cursor()
cur.execute('SELECT user FROM login_UsersModel WHERE user1=user;')
rows = cur.fetchall()
if len(row) == 1:
return ERR_USER_EXIST
else:
cur.execute('INSERT INTO login_UsersModel VALUES (user1, password1, 1);')
cur.execute('SELECT count FROM login_UsersModel WHERE user1=user AND password1=password;')
return cur.fetchone()[0]
except psycopg2.DatabaseError, e:
print 'Error %s' % e
sys.exit(1)
def TESTAPI_resetFixture(request):
con = psycopg2.connect(database='test', user='jeffrey')
cur = con.cursor()
cur.execute('DELETE FROM login_UsersModel')
return SUCCESS
views.py
from django.shortcuts import render
from django.http import HttpResponse
from login.models import UsersModel
from django.utils import simplejson
import os
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def loginx(request):
data = simplejson.loads(request.body)
name = data['user']
pw = data['password']
x = UsersModel()
code = x.login(name, pw)
if code > 0:
response_data = {'errCode':1, 'count':code}
return HttpResponse(simplejson.dumps(response_data), content_type="application/json")
else:
response_data = {'errCode':code}
return HttpResponse(simplejson.dumps(response_data), content_type="application/json")
#csrf_exempt
def addx(request):
data = simplejson.loads(request.body)
name = data['user']
pw = data['password']
x = UsersModel()
code = x.add(name, pw)
if code > 0:
response_data = {'errCode':1, 'count':code}
return HttpResponse(simplejson.dumps(response_data), content_type="application/json")
else:
response_data = {'errCode':code}
return HttpResponse(simplejson.dumps(response_data), content_type="application/json")
#csrf_exempt
def TESTAPI_resetFixturex(request):
x = UsersModel()
code = x.TESTAPI_resetFixture()
response_data = {'errCode': code}
return HttpResponse(simplejson.dumps(response_data), content_type="application/json")
#csrf_exempt
def unitTests(request):
os.system("make func_tests TEST_SERVER=localhost:8000")
return
url.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from login.views import loginx
from login.views import addx
from login.views import TESTAPI_resetFixturex
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
#url(r'^admin/', include(admin.site.urls)),rs
url(r'^users/login', loginx),
url(r'^users/add', addx),
url(r'^TESTAPI/resetFixture', TESTAPI_resetFixturex)
#url(r'^TESTAPI/unitTests', unitTests)
)
ive seen similar questions been asked before on stackoverflow, but their solutions were not able to help me and lead me to other errors. so yea i dont understand how 3 arguments can be given to add when i only put users and password as my argument in view. can someone help me. btw i am only testing the add function right now in view using:
curl -H "Content-Type: application/json" -H "Accept: application/json" -X POST -d '{"user":"test", "password":"test"}' localhost:8000/users/add -o test.html
The instance (conventionally referenced by self) is passed to each instance method of a class. This question explains some more about what self is and repreesnts. In addition there are a great number of high quality oop python tutorials.
I am assuming add is method of UsersModel (if it is please correct indentation, as it matters immensely`)
in which case your function definition should look like:
def add(self, user1, password1):
Additionally, i think it would be a great help to do the django tutorial. Django has created an ORM to allow you to interact with a database without writing any sql!:) It is extremely easy to use. Also django has a built in User model that provides authentication and user creation out of the box

Removing fields from json

I have a view function which renders json. I am able to specify which columns I want in my json but I don't know how to change the name of the key fields. Like the field "pk" should be "id".
I am using this autocomplete control (http://loopj.com/2009/04/25/jquery-plugin-tokenizing-autocomplete-text-entry/) and it requires the json to have certain fields.
from django.http import HttpResponse
from django.shortcuts import render_to_response
from iCookItThisWay.recipes import models
from django.core import serializers
from django.utils import simplejson
def index(request, template_name):
meal_types = []
q = ''
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
if len(q) > 0:
meal_types = models.MealType.objects.filter(name__istartswith=q)
json_serializer = serializers.get_serializer("json")()
sdata = json_serializer.serialize(meal_types, ensure_ascii=False, fields = ('id', 'name'))
return HttpResponse(simplejson.dumps(sdata), mimetype='application/json')
Could you also please point me to some documentation. I feel that I am crap at finding documentation.
Instead of using the serializer, you can build a dict manually and convert it to json via .dumps()
meal_types = models.MealType.objects.filter(name__istartswith=q)
results = []
for meal_type in meal_types:
results.append(
{'id': meal_type.id,
'name': meal_type.name})
return HttpResponse(simplejson.dumps(results), mimetype='application/json')
You could also build the results with a list comprehension, since there are only a couple
of fields:
results = [{'id': mt.id, 'name': mt.name} for mt in meal_types]