Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django prefetch_related() on a ManyToManyField with an additional ForeignKey
I have this very standard set of models implementing a ManyToManyField. class Apple(models.Model): oranges = models.ManyToManyField('Orange', through='AppleOrangeMapping') class Orange(models.Model): name = models.CharField(max_length=100) class AppleOrangeMapping(models.Model): apple = models.ForeignKey(Apple) orange = models.ForeignKey(Orange) I'm working on a performance enhancement to ensure that I don't prefetch the related Orange object every time I loop over the Apples. Some research led me to realize I needed prefetch_related and not select_related for this situation: apples = Apple.objects.all().prefetch_related('oranges') But when I run the following, it still re-fetched the Orange each time. for apple in apples: return ', '.join(apple.oranges.values_list('name', flat=True)) All the documentation/StackOverflow questions I've indicates that this should work, and I can see that the query is run to prefetch all the Oranges related to all the objects in the QuerySet apples, and yet this query is re-run each time: SELECT "orange"."abbrev" FROM "orange" INNER JOIN "appleorangemapping" ON ("orange"."id" = "appleorangemapping"."tag_id") WHERE "appleorangemapping"."apple_id" = 267 Any ideas? Thanks! -
Django: saving an instance not object in ForeignKeyField
I am on Django 1.10.1 and trying to save a model instance as a ForeignKey on another model. However when I do, it returns ValueError: Cannot assign "<DataPointModel: DataPointModel object>": "BikeModel.data_point" must be a "DataPointModel" instance. Here is the code which returns a DataPointModel object. data_point = DataPointModel.objects.filter( object_id=bike.reference_model.id, name="Median" ).last() bike.data_point = data_point And on the BikeModel: data_point = models.ForeignKey(DataPointModel, null=True, blank=True) I believe I'm returning an instance with the filter().last() call. Am I missing something? -
How to download multiple pdf files in a zip file in django
I am trying to let the admin in the admin panel in django download the pdf of the user using the following code admin can download single file at a time successfully but when I try to download multiple files the zip file is downloaded but with an error "An error occurred while loading the archive" single pdf : def downloadUserCV(self, request, queryset): for x in queryset: projectUrl = str(x.cv)+'' if projectUrl: with open(projectUrl, 'r') as pdf: response = HttpResponse(pdf,content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="user_cv.pdf"' return response pdf.closed messages.warning(request, "Sorry, The selected users have not uploaded any CV") downloadUserCV.short_description = 'Download this CV' multiple ones : def downloadCV(self, request, queryset): filenames=[] for x in queryset: filenames.append(str(x.cv)) zip_subdir = "User CVs" zip_filename = "%s.zip" % zip_subdir s = StringIO.StringIO() zf = zipfile.ZipFile(s, "w") for fpath in filenames: fdir, fname = os.path.split(fpath) zip_path = os.path.join(zip_subdir, fname) with open(fpath, 'r') as pdf: zf.write(fpath, pdf.read()) pdf.close() resp = HttpResponse(s.getvalue(), content_type = "application/x-zip-compressed") resp['Content-Disposition'] = 'attachment; filename=%s' % zip_filename return resp downloadCV.short_description = 'Download CV' -
Setting a default value in session if key does not exist
I would like to obtain a value from the session and in case that value does not exist I would like to supply a default one. I got my current approach from here. This is what I am doing fav_color = request.session.get('fav_color', 'red') The above works fine however I noticed that if the key variable is placed in settings.py then the output is None.Which I would like to fix. For instance this is in my settings.py VARIABLE_PATIENT_ID_DEFINE="patientID" Now in some other app I am using it like this t = "somevar" s = settings.VARIABLE_PATIENT_ID_DEFINE print(s) # prints patientID fav_color = request.session.get(s, 'red') --->After this line Default is None fav_color = request.session.get(t, 'red') --->After this line Default is red My questions is why does fav_color = request.session.get(s, 'red') fail and return none ? Why does assigning from settings.VARIABLE_PATIENT_ID_DEFINE cause an issue -
How do you create sub-ids in Django Models?
I have a Model that has two main classes. The first is the book model and the second is the page model The pages have a foreign key field to the books which lets me access them but what I am curious about is, how would you implement page numbers such that when creating a new page object, the number is limited only to be within the current length of pages? Furthermore, if it is inserted, how would you shift the following pages down one in number? Right now I just have an integer field that I manually type in the page number but if I want to allow users to add pages themselves later, that won't do. -
Django reversion - Get old model with old model children (get historical object)
I'm trying to get an old version of an object and then also get the old children belonging to that model. I'll try to add an example here: parent_object.teams.count() # => 10 And then after fetching the old model with something like versions[1] old_parent_object.teams.count() # => 8 Is this even possible? The example above is much simplified. In reality i need to get the old parent object with nested children as they where when the old parent object existed. So not just the count, but the whole object. -
Writing an array (or pandas dataframe) to mysql/sqlite database using django orm
I'm wondering what the best way to store an array and/or pandas dataframe into an sqlite or mysql database using the django orm. I have some data in a pandas dataframe, something like this: data = {'a': [[0,0.1,0.2,0.3],[5,10,15,20]], 'b': [[0,10,20,30],[20,30,40,50]]} I'm considering storing it in a database like this: data_name index data --------- ----- ---- a 0 5 a 0.1 10 . . . . . . . . . b 0 20 b 10 30 . . . . . . . . . Is this a logical structure? And if so, how might I build a custom django db class/field in order to input it into the database? I have an object like this def MyClass(models.Model): my_df = SomeCustomField() # how would you implement this part? def __init__(self): self.my_df = pd.DataFrame() Does it make more sense to serialize it and store it in a serialized format in a single db entry? Each of these arrays could be 100 elements, will querying so many related rows have a negative impact on performance? -
Why doesn't Django support websockets?
I'm working on an application that connects to a python Twisted server. The client is written in Javascript and is ran when on a certain view. However, whenever I try running the client, it connects to the server and then immediately closes the connection. I theorize that this is because the javascript is written in one of the templates and it runs the client when a button is pressed. However, since Django reloads code, it doesn't ever hold the connection. My question is whether my theory is correct and if so, what is a possible workaround? I've been trying to solve this for some time right now with little to no luck. Here is my code if it helps. JavaScript Client: <div id="check-status-button"> {% csrf_token %} <button onclick="webClient()"> Check Status </button> </div> <div id="check-status"> <textarea rows="4" columns="50" name="check_status" value = "{{ status_data }}"> </textarea> </div> <script type="text/javascript"> function webClient(){ var ws = new WebSocket("ws://localhost:8080/"); ws.open = function(){ alert("Message is Sent"); }; ws.onmessage = function(event){ var received_msg = event.data; console.log("received: ", received_msg); alert("Message received"); }; ws.onclose = function(){ alert("Connection is Closed"); }; }; </script> Python/Twisted Server: import os from datetime import datetime from twisted.internet.protocol import ServerFactory, Protocol from twisted.internet import task … -
'file' object has no attribute 'startswith' django
I am trying to download multiple pdf files and adding them to a zip folder after opening each one and then write it to the zip but I am getting this error my code is def downloadCV(self, request, queryset): filenames=[] for x in queryset: filenames.append(str(x.cv)) temp = tempfile.TemporaryFile() archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED) for fpath in filenames: with open(fpath, 'r') as pdf: archive.write(fpath, pdf) pdf.closed archive.close() wrapper = FileWrapper(temp) response = HttpResponse(wrapper, content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=test.zip' response['Content-Length'] = temp.tell() temp.seek(0) return response -
What use to develop an app using a Backend Django
I'm going carry out a project, where I will develop a dinamic platfom. The solution that I have in mind is: Develop the backend in pyhton (django). My objective is build a dinamic platform where I need a good backend, that in future allow me build the app. A perfect solution would be develop a natives apps, with ios and android. But, I would like to know that if I will work with frameworks to develop hybrid app it's better option? above all, if I want to use the hardware of the mobile, for example, the gps. What would you recommend me? Thanks in advance. -
Django skips particular migration(No Migrations to apply)
I am working on an app at Django 1.9 I created altered one field from User model (max_length to 120 from 40). I know the migration has not run and i can see that it is skipped obviously. I can't seem to understand why this is happening. Things i tried: 1- Verified that the database does not say it as run(django_migrations table): See there is no 0021_alter_user_lms_user_id 2- i check if django is able to see migration file: I am very surprised with this outcome. I cannot purge my migrations nor the database because this is a deployed app with data. Any help is appreciated Note: I checked all related questions i could find before posting this question. -
javascript function stops processing the button change
I have this toggle button: <form action="" method="POST" > {% csrf_token %} <div id="mark_toggle" class="col-xs-2" data-toggle="buttons"> <label class="btn btn-lg btn-block btn-success" > <input type="radio" value="Mark" autocomplete="off">Mark </label> <label class="btn btn-lg btn-block btn-warning active" > <input type="radio" value="Unmark" autocomplete="off">Unmark </label> </div> </form> That works with this javascript: <script type="text/javascript"> $(document).ready( function () { $("#mark_toggle input:radio").change(function() { var toggle_mark = $(this).val(); $.getJSON("/mark_question/", { quiz_name:{{quiz.id}}, qid:{{ question.id }}, toggle_mark:toggle_mark}, function(json){ });});}); </script> When I click first and second time (check and uncheck), the javascript gets called, then stops being called. Any idea? -
nginx.service: Failed to read PID from file /run/nginx.pid: Invalid argument
I'm working through https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-16-04. I've completed the tut but I'm getting a 502 error. My nginx server block configuration file: server { listen 80; server_name 198..xxx.xxx.xxx mysite.org; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/deploy/mysite3; } location / { include uwsgi_params; uwsgi_pass unix:/run/uwsgi/mysite3.sock; } } deploy@server:/etc/nginx/sites-enabled$ sudo systemctl status nginx ● nginx.service - A high performance web server and a reverse proxy server Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled) Active: active (running) since Mon 2017-02-06 17:30:53 EST; 4s ago Process: 7374 ExecStop=/sbin/start-stop-daemon --quiet --stop --retry QUIT/5 --pidfile /run/nginx.pid (code=exited, status=0/SUCCESS) Process: 7383 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS) Process: 7380 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS) Main PID: 7384 (nginx) CGroup: /system.slice/nginx.service ├─7384 nginx: master process /usr/sbin/nginx -g daemon on; master_process on └─7385 nginx: worker process Feb 06 17:30:53 server systemd[1]: Starting A high performance web server and a reverse proxy server... Feb 06 17:30:53 server systemd[1]: nginx.service: Failed to read PID from file /run/nginx.pid: Invalid argument Feb 06 17:30:53 server systemd[1]: Started A high performance web server and a reverse proxy server. It looks to me that uwsgi is running ok: Feb 06 17:43:42 server uwsgi[7434]: … -
Google AppEngine Python: sys.path discrepancy between dev_appserver and webapp2 handlers
"import django" statement in one of my handlers was failing with ImportError. When looking into this, I found that sys.path in dev_appserver.py and my handler is different. Why the discrepancy? What is the role of dev_appserver.py, especially relative to wsgi.py? I understand that when a page request is being made, wsgi.py is called. sys.path in dev_appserver.py includes django path but not the sys.path in my handler. -
Is it possible to change a queryset using AJAX?
I have querysets for comments which looks like this: comment_list = Comment.objects.filter().order_by('-score__upvotes') new_comments_list = Comment.objects.filter().order_by('-timestamp') Then my template is {% for comment in comment_list %} {{ comment }} ... Is there any way to change {% for comment in comment_list %} to {% for comment in new_comments_list %} using AJAX (no page refresh)? Or possibly changing the value of comment_list to equal Comment.objects.filter().order_by('-timestamp')? -
Django: Setting initial vals of multiplechoicefield only works first time
I'm dynamically generating a form in Django. forms.py class ActiveSignalForm(forms.Form): choices = forms.MultipleChoiceField( label = 'Alter Archiver Registry', choices = ((sig.id, sig.signal) for sig in registry.objects.order_by('first_registered')), widget = forms.CheckboxSelectMultiple, initial = [ sig.id for sig in registry.objects.order_by('first_registered') if sig.archival_active], ) views.py def index(request): latest_signal_list = registry.objects.order_by('first_registered') form = ActiveSignalForm() context = {'latest_signal_list': latest_signal_list, 'form': form} return render(request, 'archiver/index.html', context) When the form is submitted, the view that handles it uses HttpResponseRedirect to send the user back to the page hosting the form. The form does the job that I want it to (that is, it makes the appropriate changes in the database), but the initial values remain stuck at whatever values were grabbed from the database when the server started. Could you please advise on a technique to make sure the initial values on the form match those in the database every time the page is loaded? Thanks. -
How to make an admin action in django to download user's pdf files
I want to create an admin action to download users pdf files The user file would be uploaded in the media directory What and the admin should be able to download any file I tried using pdfkit to let him download the files but I couldn't > import pdfkit > > def downloadCV(self, request, queryset): > projectUrl = str(queryset[0].cv)+'' > pdf = pdfkit.from_url(projectUrl, False) > response = HttpResponse(pdf,content_type='application/pdf') > response['Content-Disposition'] = 'attachment; filename="user_cv.pdf"' So my question is what is the best way to let the admin dowload pdf files -
jQuery - traversing through Json object
I have the following Json object: Object {success: false, errors: "{"email": [{"message": "Enter a valid email address.", "code": "invalid"}]}"} This is response of Django errors.as_jason method. I need to process the error message Enter a valid email address. I'm using jQuery. I tried many ways but with no success. json.errors return this {"email": [{"message": "Enter a valid email address.", "code": "invalid"}]} but then json.errors.message return undefined and I didn't find a way to get it correct. How I can get the message only? -
Django, Security and Settings
From here, we add all database info as text: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydatabase', 'USER': 'mydatabaseuser', 'PASSWORD': 'mypassword', 'HOST': '127.0.0.1', 'PORT': '5432', } } Is it a secure way? Is there any way to save this data as Encrypted data? -
Serializing nested querysets from many-to-one relationships
I have a survey app, where there are surveys, questions, and choices to the questions. Each question has a foreign key to the survey it belongs to, and each choice has a foreign key to the question is belongs to. Cleaned out model code for a multiple choice question is shown below. class Survey(models.Model): # survey attributes, not needed in the query for this question class Question(models.Model): survey = models.ForeignKey(Survey) prompt = models.TextField() class Choice(models.Model): question = models.ForeignKey(Question) letter = models.CharField(max_length=1) text = models.TextField() is_correct = models.BooleanField(default=False) To get all the questions in a survey, I can select all the data I need with the backwards relationship as such, Survey.objects.get(pk=1).question_set\ .select_related('choice__text', 'choice__letter')\ .values('prompt', 'choice__text', 'choice__letter') and It will return, as expected, [{ prompt: str, choice__text: str, choice__letter: char, },] ...but this will duplicate the prompt in every row and ideally the formatting would be closer to [{ prompt: str, choice_set: [{ letter: char, text: str, },] },] I have solved a similar problem before by throwing it in a panda dataframe and grouping the data before serializing, but I can only assume the creators of django made a way to do this Is there any way to easily nest these … -
Call python func from html
im realy new to the web-application programming. I'm trying to setup as simple django web-page that will control some of my features of my "smart home". I want to press a button on the html front end and then execute a python function. def controlPower(status): first = "11010" # DIP switches 1..5 where "1" = on and "0" = off, second = "10000" # DIP switches 6..10 (A..E) where "1" = on and "0" = off switch = pi_switch.RCSwitchA(first, second) switch.enableTransmit(0) # use WiringPi pin 0 <=> GPIO17 if (status == 1): switch.switchOn() print ('ON') elif (status == 0): switch.switchOff() print ('OFF') Also is there a way to pass values into those functions? Im having the same already setup in a simple php page. BR, Numblesix -
How to use multiple pinax apps in a single django project
I am getting started with Pinax and was able to get django-user-accounts up and running. However I now want to add Pinax-blog to this app. I tried the following: pinax start blog blog however this just created a new django project within the existing django project, recreating all the existing templates and static files. -
Django error: Command throws a python window when executing makemigrations command in a Python/Django project
python ´2.7.13´ Django ´1.9.7´ i'm using ´viertualenv´ to manage my project. i tried to run this command and this happends (pyproject-1)xxxxx@xxxx.com python manage.py makemigrations and it open a new window with the pyshell python 2.7.13 (v2.7.13:a06454b1afa1, dec 17 2016, 20:42:59) [MSC v.1500 32 bit<intel> on win 32] type "help", "copyright", "credits" or "license" for more information. >>> Using de ´migrate´ or ´runserver´ command still opens the windows what could be the error? i googled this and i don't fing clear answers -
'Manager' object has no attribute 'get_by_natural_key'
I know there are similar questions like this, and I tried every solution that is adressed in those questions. Here is my problem described; When I execute createsuperuser, I got an error as follows; AttributeError: 'Manager' object has no attribute 'get_by_natural_key' Here is how I define UserAccountManager and UserAccount in my implementation; from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser class UserAccountManager(BaseUserManager): def create_user(self, email, first_name, last_name, password=None): if not email: raise ValueError('Email must be set!') user = self.model(email=email, first_name=first_name, last_name=last_name) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, first_name, last_name, password): user = self.create_user(email, first_name, last_name, password) user.is_admin = True user.save(using=self._db) return user def get_by_natural_key(self, email_): return self.get(code_number=email_) class UserAccount(AbstractBaseUser): email = models.EmailField(unique=True) first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) is_active = models.BooleanField(default=True) # default=False when you are going to implement Activation Mail is_admin = models.BooleanField(default=False) objects = UserAccountManager USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def get_short_name(self): return self.email def get_full_name(self): return self.email def has_perms(self, perm, ob=None): return True def has_module_perms(self, app_label): return True def natural_key(self): return self.email @property def is_staff(self): self.is_admin I set object as follows in UserAccount class : objects = UserAccountManager What do I do wrong? -
How to import application views to urls - django
I have currently started to learn Django and I am trying to create an application. I got stuck at some point. I am using NetBeans Community Edition as IDLE, and I can not import views from posts application despite adding it to the INSTALLED_APPS list from setting.py. What am I doing wrong here?