Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: os.environ.get vs import settings
In a views.py would you rather do: from django.conf import settings stripe.api_key = settings.STRIPE_SECRET_KEY or import os stripe.api_key = os.environ.get('SECRET_KEY') Thank you for your help. In my settings I am also using the os.environ.get import. -
Django Push Notification for IOS safari
I used django-push-notifications for implementing push notifications in Django server I have implemented GCM for my AngularJS webapp and its working great on chrome. For safari I'm following this post for implementing APNS part but I get "POST /v1/pushPackages/web.com.example {u'logs': [u'downloading push notification package failed']} on my server log This is my views.py @api_view(['POST','GET']) def getPushPackage(request): try: print "Here -- > Hello" filename = '/pushNotifications/static/pushPackage.zip' zipfile = open(settings.BASE_DIR+filename, 'rb') response = HttpResponse(content=zipfile) response['Content-Type'] = 'application/zip' response['Content-Disposition'] = 'attachment; filename="%s"'%(settings.BASE_DIR+filename) print "Here -- > Done" return response # return HttpResponse(content=zipfile, content_type='application/force-download') except Exception as e: print str(e) return Response(str(e)) This is my urls.py url(r'^v2/pushPackages/web.com.example', views.getPushPackage), url(r'^v1/log', views.printPushError), This is my Controller var checkRemotePermission = function (permissionData) { console.log(permissionData.permission); if (permissionData.permission === 'default') { // This is a new web service URL and its validity is unknown. window.safari.pushNotification.requestPermission( 'https://x.x.x.x:1234', // The web service URL. 'web.com.example', {}, // Data that you choose to send to your server to help you identify the user. checkRemotePermission // The callback function. ); } else if (permissionData.permission === 'denied') { console.log("here user denial"); // The user said no. } else if (permissionData.permission === 'granted') { // The web service URL is a valid push provider, and the … -
How is session initialized in Django?
I'm still confused about what happens after we enable session on Django. The documentation says each Request will have a session dictionary associated with it. Does that mean a default session will be initialized with the only key being the session ID? And if sessions are unique per browser, do all the request have access to the same session when a user logs in? -
How to properly catch and nest ValidationErrors
I would like to nest validation errors in order to allow the exact causes of an error to be pinpointed, but it appears that Django's ValidationError does not allow nesting of nested errors. Here is a toy example: def not_nested(): raise ValidationError(_('invalid')) def nested(): errors = dict() for x in ['a', 'b', 'c']: try: not_nested() except ValidationError as e: errors[x] = e if errors: raise ValidationError(errors) def nested_again(): errors = dict() for x in ['1', '2', '3']: try: nested() except ValidationError as e: errors[x] = e if errors: raise ValidationError(errors) Single nesting works fine: nested() # raises: ValidationError: {'a': ['invalid'], 'b': ['invalid'], 'c': ['invalid']} But nesting twice does not: nested_again() # raises AttributeError: 'ValidationError' object has no attribute 'error_list' Is this intended or a bug? Is there another way to accomplish this? -
Django static files not loading or not working?
I have been trying to implement a way to upload multiple images using JQuery. For some reason, my js file is not being called when I click the upload photos button. Whenever I click the upload photos button nothing happens. My codes are below: I am not sure if am doing something wrong with my create_posts function in the views or.. views.py from django.shortcuts import render, redirect, get_object_or_404 from django.utils import timezone from django.core.files.base import ContentFile from django.forms import modelformset_factory from django.http import JsonResponse from .models import Projects, P_Images from .forms import ProjectsForm, P_ImageForm from PIL import Image from io import BytesIO # Create your views here. # Function to create projects def create_projects(request): #P_ImageFormSet = modelformset_factory(P_Images,form=P_ImageForm, extra=3) # Special case if the request method is not POST #if request.method == 'POST': project_form = ProjectsForm(request.POST, request.FILES) p_photos = P_ImageForm(request.POST, request.FILES) # Checks if the form is valid before save if project_form.is_valid() and p_formset.is_valid(): instance = project_form.save(commit=False) instance.user = request.user instance.save() p_photos.save() data = {'is_valid': True, 'name': p_photos.file.name, 'url': p_photos.file.url} else: data = {'is_valid': False} # print(project_form.errors, p_formset.errors) #return JsonResponse(data) context = { 'project_form': project_form, 'p_photos': p_photos, } return render(request, 'projects/test2.html', context) # Function to retrieve all different projects def retrieve_projects(request): … -
django get orginal object after values_list
I got some fields of objects with values_list() method.But I need orginal object after query.How can ı do this? Student.objects.values('name', 'father', 'mother').annotate(Count('name')).order_by().filter(name__count__gt=1) After this query ı need id of student object. -
Django performance issue with exclude
I have word model and phrase model class Word(models.Model): checked = models.BooleanField(default=False) class Phrase(models.Model): words = models.ManyToManyField(Word, null=True,related_name = "phrases") Word model has attribute checked and many to many connection to phrase I have a query, something like this: Phrase.objects.exclude(words__checked=True).filter(words__group__pk__in = groups_ids) But it works really really slow on big datasets, and the problem is in exclude section, cause without it - it works fast enough So I found a suggestion that I should use raw sql here, Performance issue with django exclude So, how can rewrite this sentence with raw sql ? (I need this query to both work postgres and mysql due to requirements, or I will need two queries if one query can't achieve this) So far I 've tried to use .extra syntax,but it didn't work, so asking it here. -
OSError: [WinError 126] The specified module could not be found. Trying to install GeoDjango on Windows 10
I am trying to install GeoDjango on my windows10 using Django 1.11.5 and Postgres SQL 10.4-1 I have downloaded the PostGis files. Created the Spatial DataBase. and followed the instructions on the install document. I am trying to follow the Django tutorial. I have made the models. When I try to run migrations. I get the error django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal201", "gdal20", "gdal111", "gdal110", "gdal19"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. I tried following a similar StackOverflowQuestion. It did not work So I did exactly what the error told me to do. In my settings file I added GDAL_LIBRARY_PATH = 'C:\OSGeo4W64\share\gdal' Now I get the error: OSError: [WinError 126] The specified module could not be found Any ideas on how I can get this to work I have been at this for almost 3 days uninstalling and installing POstgresSQL. Resetting my Laptop nothing seems to be working -
Model instance validation with serializer
Django rest framework encourages to perform validation in serializers and not in django models... Well, why not. How do I validate an instance of a model? How do I perform a particular validation when deleting an object? I have the impression that I have to move part of the logic in the serializer and the other part in the model. I don't like it. Is there a solution? More information to understand: https://github.com/encode/django-rest-framework/issues/3144 -
When does ajax success function get called?
I'm using Ajax in Django and was wondering when the success method of an ajax get's called in a post request. Say I have this code on the server: if request.method == 'POST': print(request.body) # Do do something here return redirect("/files") So, is ajax success function in my html called only after successful execution of (# Do something here) or it is called immediately once the data reaches the server and the execution of (# Do something here) has no effect? Thanks. -
Does django-allauth manages session ID? or how should I make a request with an already opened facebook session?
I'm trying to do two GET requests to be able to obtain an User Access Token for the Facebook Graph API. But my problem is just with the first request, from which the URL is: https://www.facebook.com/v3.1/dialog/oauth?client_id=FB_APP_ID&redirect_uri=REDIRECT_URL If I already logged in a typical browser, after manually doing that request I'm redirected to my main page (hence the REDIRECT_URL parameter) and the URL in the URL bar contains a "code" parameter. I need a library that allows me to check that URL after the GET request. Obtaining the code once I have the URL isn't that hard. I already know how to do it with the urllib library. I tried doing it with Selenium in a headless browser, but Selenium creates a new session with each browser opened. So I had set the browsers' session_id variable with django's request.session.session_key variable, but that throws an InvalidSessionIdException. So my question is: Is request.session.session_key not the session ID django-allauth is using to maintain the Facebook session? -
Understanding decorators in Django
I'm currently trying to build my own decorator for function based views. I understood the basic concept behind decorators but I'm still struggling to fully understand whats happening "behind the scenes". I've this example decorator. Could someone explain me what happens here or how it works? And why do we need so many functions here? def active_user_required(): def decorator(function): def wrapper(request, *args, **kw): if request.user.is_active: return function(request, *args, **kw) else: raise PermissionDenied() return wrapper return decorator -
Display content based on multiple choices
Please forgive the beginner question, your help is very much appreciated. Could anyone point me in the right direction on how to build a website with the following functionality? I am not looking for the code itself, but rather some general guidance on where to start, for instance which technology would it be easier to build with? Should I try to do it all with some javascript/jquery, or build something more complex on the backend? Functionality: -The user is asked a few questions on their preferred living environment (for instance multiple choice between "large metropolis," "small town," or "rural" or asked to rank the importance of different factors like cost-of-living, "entertainment options," "distance from current locations"). -The website then display different content based on the selected choices. For instance the site could recommend a city to study-in based on the selected choices, or present in a ranked fashion a number of cities presented in a tile-format. I have been able to do a basic version of this using javascript and simple If this and this rules but I am thinking it might be better not to do it all in the front-end if I want to make the site larger … -
Django (2.0.7) Wagtail (2.1.1) serialize image field
I have a snippet @register_snippet class TripStopItem(models.Model, index.Indexed): DISPLAYED = 'DSP' NOTDISPLAYED = 'NDSP' UNKNOWN = 'UNK' DISPLAY_STATUS_CHOICES = ( (DISPLAYED, 'DISPLAYED'), (NOTDISPLAYED, 'NOTDISPLAYED'), (UNKNOWN, 'Unknow'), ) status = models.CharField( max_length=4, choices=DISPLAY_STATUS_CHOICES, default=UNKNOWN, ) entered_at = models.DateTimeField(default=datetime.datetime.now()) image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) from rest_framework import serializers as rest_serializers class TripStopItemSerializer(rest_serializers.ModelSerializer): image_url = rest_serializers.SerializerMethodField() _image = rest_serializers.Field('image.url') class Meta: model = TripStopItem fields = ('id','status','tripstop','entered_at','image','campaign','notes') I am wondering how i can retrieve the entire object including the image. Either by getting the url or a base64 option. I am not using the API as it seems to always return the id number only, so im using what is basically a form endpoint. def getDataEndpoint(request): _id = request.POST.get('id').strip() if (_rider is not None): try: b_qs = TripStopItemSerializer.objects.get(id=_id) pprint(b_qs) if (results): data = {'response': 200,'data':data} else: data = {'response': 400,'message':'No Open rides for Rider'} except Exception as e: data = {'response': 401,'message':e} else: data = {'response': 402,'message':'Invalid username or password. Kindly try again.'} return JsonResponse(data) -
django.db.utils.OperationalError: no such table: IEL_user_groups
I have a error which I am unable to detect, I am learning Django, at start I was working with Django default user model, but then I need to have a custom user model,So I make following changes in my model.py file: class User(AbstractUser): is_student=models.BooleanField(default=False) is_teacher=models.BooleanField(default=False) class Teacher(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) name=models.CharField(max_length=20) class Student(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) name=models.CharField(max_length=30) Before doing this,I deleted 0001,0002,0003 files in migration folder and then after adding User,teacher,student in models.py,i run below commands: 1)python manage.py makemigrations IEL 2)manage.py sqlmigrate IEL 0001 3)python manage.py migrate At third command I got following error: Operations to perform: Apply all migrations: IEL, admin, auth, contenttypes, sessions Running migrations: Applying IEL.0002_auto_20180808_0806...Traceback (most recent call last): File "C:\Users\Nabeel Ayub\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\Nabeel Ayub\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 303, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: IEL_user_groups IMPORTANT: when i remove all my models i.e remain model.py file empty and simply run server, it works and the admin page opens! I have been stuck in this for a very long time and can't resolve.Highly Appreciated for your solutions. -
How to dynamically output python dictionary to html in django?
This is the data I get from socket dynamically and I would like to show it in a table like keys and values in html with django. Received: {'power': 'ON', 'mode': 'AUTOMATIC', 'execution': 'ACTIVE', 'Xact': '235.70', 'Yact': '1468.86', 'Zact': '1.27', 'Xcom': '0.00', 'Ycom': '0.00', 'Zcom': '0.00', 'path_feedrate': '0.00', 'line': '1136849', 'Block': '1136849', 'program': '37262 S1 - .75 JET_imported_CNC.ORD\n'} {'comms': 'NORMAL', '': '\n2018-08-08T17:11:51.0384', 'Sspeed': '60000.00\n'} {'line': '1136860', 'Block': '1136860\n'} {'Xact': '236.17', 'Xcom': '909.70', 'path_feedrate': '909.70\n'} {'Xcom': '0.00', 'path_feedrate': '0.00', 'line': '1136872', 'Block': '1136872\n'} {'line': '1136883', 'Block': '1136883\n'} {'line': '1136895', 'Block': '1136895\n'} {'line': '1136906', 'Block': '1136906\n'} {'Xact': '236.52', 'Xcom': '677.44', 'path_feedrate': '677.44\n'} {'Xcom': '0.00', 'path_feedrate': '0.00', 'line': '1136918', 'Block': '1136918\n'} {'line': '1136929', 'Block': '1136929\n'} {'line': '1136941', 'Block': '1136941\n'} I tried to use this, but it did not work. <table> {% for key, value in devDict.items %} <tr> <td>{{ key }}</td> <td>{{ value }}</td> </tr> {% endfor %} </table> And this is my python script, this is how i get the data: import socket HOST = "myHOST" PORT = myPORT with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, PORT)) buffer_size = 2048 print("Received: ") while True: devData = s.recv(buffer_size).decode("utf-8").split("|") timeStamp = devData.pop(0) devDict = dict(zip(*([iter(devData)]*2))) print(devDict) s.close() -
Python prefetch_related doesn't cache data
Here is my problem : I have two tables on a foreign database who look like this : class cell(models.Model): reference = models.CharField(max_length=36) class specs(models.Model): value_str = models.CharField(max_length=255, blank=True, null=True) name = models.CharField(max_length=255) linked = models.ForeignKey(cell, models.DO_NOTHING) So cell has multiple specs pointing at him. I'm running a query to get some cells with their specs : cells = cell.objects.using('db_name').prefetch_related('specs_set').all() After this query I have a "for" for each cell where I need to use some specs object : for cell in cells : print(cell.reference) spec = cell.specs_set.filter(name='spec_name').first() print(spec.value_str) By my understanding of prefetch_related, the specs objects should be cached thanks to the first query and therefore I should not have to make another query at each iteration to get my "spec_name". Just to be sure, I ran a Wireshark on my laptop and ... surprise ... a query is made on each iteration :( My question : What have I done wrong ? Thanks in advance for your help ! -
How to deserialize a GeoServer WFS GeoJSON?
TL:DR I want to deserialize a GeoServer WFS FeatureCollection in GeoJSON format into a GeometryField/GeometryCollection. Let's start with the model: class Layer(models.Model): name = models.CharField(max_length=50) layer = GeometryCollectionField(null=True) and the serializer: class LayerSerializer(GeoFeatureModelSerializer): class Meta: model = Layer geo_field = 'layer' fields = ('id', 'name', 'layer') Now a sample WFS GeoJSON looks like this: { "type": "FeatureCollection", "totalFeatures": 1, "features": [ { "type": "Feature", "id": "some_id", "geometry": { "type": "MultiLineString", "coordinates": [ [ [4.538638998513776, 50.4674721021459], [4.5436667765043754, 50.47258379613634], [4.548444318495443, 50.47744374212726], ... }, "geometry_name": "the_geom", "properties": { ... } } ], "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:EPSG::4326" } } } } On trying to deserialize the above I get the following error: "layer": [ "Unable to convert to python object: Invalid geometry pointer returned from \"OGR_G_CreateGeometryFromJson\"." ] PS: I prefer a solution (if one exists) that doesn't need to modify the GeoJSON in order to transform it into a GeometryCollection, as I have done that with success. -
Many to many query: find words that have only checked phrases
I have word model and phrase model Class Word(models.Model): checked = models.BooleanField(default=False) class Phrase(models.Model): words = models.ManyToManyField(Word, null=True,related_name = "phrases") Word model has attribute checked and many to many connection to phrase I need to perfom a difficult for me query: We are considering that phrase is checked if it has at least one checked word. How do I find all words that has only checked phrases and doesn't have unchecked phrases? Right now I am doing using cycle through all words in db, but this is not very effective, so I am looking for more efficient way to do this. -
NoReverseMatch Exception using mezzanine.mobile
I'm pretty new to Mezzanine and I'm having some difficulty getting the option View Mobile Site available in my index.html. SETUP In the settings.py, I specified the following INSTALLED_APPS: INSTALLED_APPS = ( "newsletters", "django.contrib.admin", "django.contrib.auth", "django.contrib.messages", "django.contrib.contenttypes", "django.contrib.redirects", "django.contrib.sessions", "django.contrib.sites", "django.contrib.sitemaps", "django.contrib.staticfiles", "mezzanine.boot", "mezzanine.conf", "mezzanine.core", "mezzanine.generic", "mezzanine.pages", "mezzanine.blog", "mezzanine.forms", "mezzanine.accounts", "mezzanine.mobile", ) And I specified the following MIDDLEWARE_CLASSES: MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', "mezzanine.core.middleware.UpdateCacheMiddleware", "mezzanine.core.request.CurrentRequestMiddleware", "mezzanine.core.middleware.RedirectFallbackMiddleware", "mezzanine.core.middleware.TemplateForDeviceMiddleware", "mezzanine.core.middleware.TemplateForHostMiddleware", "mezzanine.core.middleware.AdminLoginInterfaceSelectorMiddleware", "mezzanine.core.middleware.SitePermissionMiddleware", "mezzanine.pages.middleware.PageMiddleware", "mezzanine.core.middleware.FetchFromCacheMiddleware", ) In my index.html {% ifinstalled mezzanine.mobile %} <span class="separator">|</span> <a href="{% url "set_device" "mobile" %}?next={{ request.path }}">{% trans "View Mobile Site" %}</a> {% endifinstalled %} Error When I access my index.html, I'm getting the following NoReverseMatch Exception: Reverse for 'set_device' with arguments '('mobile',)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] Any ideas why I'm getting this exception? -
Django Admin: readonly_fields not showing on admin. interface
This should be a pretty straight-forward thing, but it's not working as it should. model class Lesson(models.Model): lesson_name = models.CharField(max_length=150, primary_key=True) json_name = models.CharField(max_length=150, default="", null=True) activity_type = models.CharField(max_length=20) learning_language = models.CharField(max_length=50) known_language = models.CharField(max_length=50) admin from .models import Lesson class LessonAdmin(admin.ModelAdmin): fields = ['lesson_name'] readonly_fields = ['json_name', 'activity_type', 'learning_language', 'known_language'] admin.site.register(Lesson, LessonAdmin) But, when I log into the admin site, the fields specified in readonly_fields don't show up at all. I've also tried including the field names in a tuple instead of a list (as the documentation specifies), but that gives me an error even. -
A POST API django-rest-framework. After storing to model, call postgres function and send an email
I'm a newbie regarding python and django and I do not fully understand differences between class and def. (Sorry) My API call works and stores the data to a table. After this is done I want it to run a stored procedure/function in postgres. After this I want a sendgrid email to be sent. My thoughts are that I'm screwing it up in the view.py class. Code is as follows: urls.py urlpatterns = [ url( r'^$', views.ProcList.as_view(), name='proc-list' ), ... ] views.py class ProcList(generics.ListCreateAPIView): queryset = Proc.objects.all() serializer_class = ProcSerializer #permission_classes = (IsAdminOrReadOnly,) lookup_url_kwarg = 'proc_id' q = Proc.store() if isNum(q[0][0]): trans_id = int(q[0][0]) trans = Transaction.objects.get(trans_id=trans_id) proc_id = trans.proc_id proc = Proc.objects.get(proc_id=proc_id) first_name = proc.first_name pdf_name = str(proc.proc_u_id) email = proc.email if Event.objects.filter(channel='EMAIL', trans_id=trans_id).exists(): sendemail2(first_name, pdf_name, email) Proc.Store() is a model containing the postgres function. sendemail2(first_name, pdf_name, email) is the function that sends the sendgrid email My issue is that Proc.Store() works if run separately or in the python console. The sendemail2(first_name, pdf_name, email) also works separately if run in e.g. the python console. But somehow my class is wrongly build so it does not execute the Proc.Store and sendemail(...). A weird effect is that when I save something … -
How to execute script python when i click button in form html?
hello how can i run script that i build on python when i click button on form html i saw examples like this but i dont get it: Html code: index.html <form action="{% url my_view_name %}" methond="post"> <input type="submit" value="Ok"> </form> views.py import django.shortcuts import render def my_view(request): if request.method == 'POST': import set_gpio #my url is "templates/load.py" return #How can i return? -
Multiple optional URL arguments in Django 2+
I am trying to implement multiple URL patterns pointing to one Class Based View in my django 2+ app. My urls: path('<slug:slug>', views.OfferDetailView.as_view(), name='show'), path('<slug:slug>/<str:status>', views.OfferDetailView.as_view(), name='show'), path('<slug:slug>/<str:status>/<uuid:application>', views.OfferDetailView.as_view(), name='show'), path('<slug:slug>/<uuid:application>', views.OfferDetailView.as_view(), name='show'), Let's say that "ABC12" is my slug here. What is my expected behaviour: when user enters /ABC12: view's kwargs status and application are Nones, slug is ABC12 when user enters /ABC12/new: view's kwargs status is "new" and application is None, slug is ABC12 when user enters /ABC12/new/6eba5dbf-220b-4913-a359-f93fab3153d1: view's kwargs status is "new" and application kwarg is "6eba5dbf-220b-4913-a359-f93fab3153d1", slug is ABC12 when user enters /ABC12/6eba5dbf-220b-4913-a359-f93fab3153d1: view's kwargs status is None and application kwarg is "6eba5dbf-220b-4913-a359-f93fab3153d1", slug is ABC12 however, when I type url: /ABC12/6eba5dbf-220b-4913-a359-f93fab3153d1 kwargs are: {'slug': 'ABC12', 'status': '6eba5dbf-220b-4913-a359-f93fab3153d1'} (I've expected that there should be not status kwarg, and 'application' kwarg should be "6eba5dbf-220b-4913-a359-f93fab3153d1"). How can I achieve this? I don't want to end up with multiple views. -
Django queryset How to retrieve related fields with annotate()
I have this table: id - supply ---- event_date ---- value_average 1 - a ---- 01-01-2018 ---- 5 2 - b ---- 02-01-2018 ---- 6 3 - a ---- 02-01-2018 ---- 7 4 - b ---- 03-01-2018 ---- 8 5 - c ---- 03-01-2018 ---- 9 I am trying to get the latest value for each supply based on event_date collumn. I can get the latest event, but I did not found a way to return the value_average aswell. values_average = Purchase.objects \ .values('supply') \ .annotate(last=Max('event_date')) \ .order_by() current return: a 02-01-2018 b 03-01-2018 c 03-01-2018 expected return: a 02-01-2018 7 b 03-01-2018 8 c 03-01-2018 9