I was wondering if there is a way to pass view variables directly to dajaxice?
Actually I convert the id to a json string and load them via the dajaxice function.
I like to avoid passing the id this way and have to handle it as user manipulated input.
view.py
from django.shortcuts import render_to_response, redirect
from django.shortcuts import get_object_or_404
from django.template import RequestContext
from django.utils import simplejson
def site(request, slug, number):
collection = get_object_or_404(Collection, slug=slug)
site = get_object_or_404(Site, collection=collection, number=number)
json_id = simplejson.dumps(site.pk)
return render_to_response('base/site.html',
{
'site': site,
'json_id': json_id,
},
context_instance=RequestContext(request))
site.html
...
var id = {{ json_id|safe }};
var user_changes = "";
...
Dajaxice.base.submit_changes(callback, {'id': id, 'user_changes': user_changes});
ajax.py
from django.utils import simplejson
from dajaxice.decorators import dajaxice_register
#dajaxice_register
def submit_changes(request, id, user_changes):
...
return simplejson.dumps({'message':'You changed:%s in Site #%s!' % (user_changes, id)})
The best way is probably to store such information in the session to prevent manipulation
view.py
...
request.session['id'] = site.pk
...
ajax.py
...
id = request.session['id']
...
Related
the following code throws attribute error
''Database' object has no attribute 'exists''.
from django.shortcuts import render
from django.views import View
from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_protect
import pyrebase
from django.contrib import auth
import json
import requests
from . import services
from .models import Product
authe = services.firebase_key().auth()
database = services.firebase_key().database()
def Login(request):
return render(request, "Login.html")
def postsign(request):
data = services.get_products()
print(data)
context = {'data': data}
number = request.POST.get('number')
password = request.POST.get("password")
if database.child("users").child(number).exists():
user = database.child("users").child(number).get().val()
if user['number'] == number:
if user['password'] == password:
return render(request,"Welcome.html",context)
I need to check if the number exists in the database or not since I want the existing users to log in using numbers and passwords.
Check if child exist in Python using Pyrebase, should be something similar, see official docs here
if not database.child('users').shallow().get().val():
print("users does not exist")
else:
print("users exist")
You can try below.
if database.child('users').child(number).shallow().get().val():
print("user exists")
else:
print("user does not exist")
I am trying to use REST API in django for retrieve some data in json format.
When i hit this url:
http://192.168.2.87:8000/locker/123/
It gives me output like this (from Database)
{"id": 1, "locker_id": 123, "locker_user_name": "taimur"}
But if i want to get the output by passing the parameters like this
http://192.168.2.87:8000/locker/?locker_id=123&locker_user_name=taimur&id=1
views.py
from postman, How can i do this??
from django.shortcuts import render, HttpResponse, get_object_or_404
from django.http import JsonResponse
from .models import Locker
from .serializers import LockerSerializer
from rest_framework.response import Response
from rest_framework import status
from rest_framework.views import APIView
def locker_data_response(request, locker_id):
if request.method == 'GET':
locker_information = get_object_or_404(Locker, locker_id = locker_id)
print(locker_information)
locker_information_serialize = LockerSerializer(locker_information)
print(locker_information_serialize)
return JsonResponse(locker_information_serialize.data)
urls.py
from django.urls import path, re_path
from . import views
urlpatterns = [
re_path('(?P<locker_id>[0-9]+)/$', views.locker_data_response, name='locker_data_response'),
]
You get them from the request object:
def locker_data_response(request):
if request.method == 'GET':
locker_id = request.data.get('locker_id') # this will return None if not found
locker_user_name = request.data.get('locker_user_name')
locker_information = get_object_or_404(Locker, locker_id=locker_id)
print(locker_information)
locker_information_serialize = LockerSerializer(locker_information)
print(locker_information_serialize)
return JsonResponse(locker_information_serialize.data)
And the url will change to:
locker/$
[EDIT: Sorry, if you are using drf you should use data rather than GET]
[EDIT 2: If you want to use it like this, you will also need to change the url and signature of the view]
[EDIT 3: Added the code in the correct place in view]
If your url is something like domain/search/?q=haha, Then you would use request.GET.get('q', '').
q is the parameter you want, And '' is the default value if q isn't found.
If you are instead just configuring your URLconf, Then your captures from the regex are passed to the function as arguments (or named arguments).
Such as:
(r'^user/(?P<username>\w{0,50})/$', views.profile_page,),
Then in your views.py you would have
def profile_page(request, username):
# Rest of the method
I can't work out how to test that a Django class-based view receives the expected kwargs from a URL pattern.
If I have my urls.py:
from django.conf.urls import url
from myapp import views
urlpatterns = [
# ...
url(
regex=r"^people/(?P<pk>\d+)/$",
view=views.PersonDetailView.as_view(),
name='person_detail'
),
]
And my views.py:
from django.views.generic import DetailView
from myapp.models import Person
class PersonDetailView(DetailView):
model = Person
I can test that a request to the URL calls the correct view like this:
from django.test import TestCase
from django.urls import resolve
from myapp import views
from myapp.factories import PersonFactory
class UrlsTestCase(TestCase):
def test_person_detail_view(self):
PersonFactory(pk=3)
self.assertEqual(resolve('/people/3/').func.__name__,
views.PersonDetailView.__name__)
But I'd also like to test that a request to /people/3/ results in {'pk': '3'} being passed to PersonDetailView, and I can't work out where in a class-based view receives the kwargs in order to test it (by patching the receiving method, I guess).
Here's how I checked the id or pk on my views (I'm using Django1.11):
from menus.models import Item
from menus.views import ItemListView
from django.test import RequestFactory
from django.contrib.auth.models import User
person = User.objects.get(username='ryan')
factory = RequestFactory()
request = factory.get('/items/')
request.user = person
response = ItemListView.as_view()(request)
#prints the id or pk of the requesting user
response._request.user.pk
response._request.user.id
I want to do some image manipulation, but before I do I want to render the image. This is what I've tried, but it does not work. The page is blank, no errors, why?
class ImgThumbnail(DetailView):
queryset = Images.objects.all()
def render_to_response(self, context, **response_kwargs):
from PIL import Image
import requests
from io import BytesIO
response = requests.get('http://example.com/media/images/{}.jpg'.format(self.pk))
img = Image.open(BytesIO(response.content))
return HttpResponse(img, content_type='image/jpg')
You should use StreamingHttpResponse. In a way like:
(dynamic content type and content length as bonus)
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
from wsgiref.util import FileWrapper
from django.http import HttpResponse, StreamingHttpResponse
class ImgThumbnail(DetailView):
queryset = Images.objects.all()
def get(self, request, *args, **kwargs):
r = requests.get('http://example.com/media/images/{}.jpg'.format(self.pk))
if not r.status_code == 200:
return HttpResponse('', status=r.status_code)
wrapper = FileWrapper(StringIO(r.content))
response = StreamingHttpResponse(wrapper, content_type=r.headers.get('Content-Type'))
response['Content-Length'] = r.headers.get('Content-Length')
return response
DetailView doesn't have a render_to_response method, so there is no point in defining your own.
You're not using any of the functionality of DetailView here anyway. You should inherit from the base View class, and put your code in the get method.
hi recently I have implemented a temp django model and I want this to get populate when the user clicks it from django admin
this is the implementation in django admin
from django.contrib import admin
from polls.models import Poll
from polls.models import TempModel
from django.conf.urls import patterns
from django.http import HttpResponse
from test_data import TestData
from django.http import HttpResponse
from django.template import RequestContext, loader
from test_data import TestData
class TempModelAdmin(admin.ModelAdmin):
fields = ('permalink', )
def test(self):
x = TestData.get_test_data()
admin.site.register(Poll)
admin.site.register(TempModel, TempModelAdmin)
and this is the temporary class which I used to populate data
from models import TempModel
class TestData(object):
#classmethod
def get_test_data(self):
print "**********************************************"
print "get test data"
print "**********************************************"
list = []
for x in range(0,50):
str_val = str(x) + "djdj;djfhdfjiosdifj";
list.append(str_val)
temp_model = TempModel()
temp_model.permalink = str_val
temp_model.save()
print "=============================================="
print "Object Count"
print TempModel.objects.count()
print "=============================================="
return list
this is not getting called . Can anyone know the reason for this ?
Thank you in advace
You're making a class method with self, it takes an instance of type. Try changing method signature:
def get_test_data(cls):
I figured it out by doing this approach and it worked
class TempModelAdmin(admin.ModelAdmin):
fields = ('permalink', )
def __init__(self, *args, **kwargs):
super(TempModelAdmin, self).__init__(*args, **kwargs)
self.my_method()
def my_method(self):
print "*************----------------------------"
TestData.get_test_data()