Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Sorting by many to one fields that might be missing in some rows
I have something similar to the following example - I've rewritten it below to simplify it. Each Measurement can have an arbitrary number of Samples. Not every Sample is required - some are missing. I want to sort my Measurements by a specific SampleDefinition, but I don't want to exclude the Measurements that are missing the specific Sample. class Measurement(model): timestamp = DateTimeField() class SampleDefinition(model): name = CharString() class Sample(model): value = IntegerField() measurement = ForeignKey(Measurement) definition = ForeignKey(SampleDefinition) Here is how I do it now, first by filtering for the definition we're sorting by, and the sorting by it: measurements = Measurement.objects.\ filter(sample__definition=id_to_sort_by).\ order_by('sample__value', 'timestamp') Then, grabbing the rest... others = Measurement.objects.\ exclude(id__in=list([s.id for s in measurements]).\ order_by('timestamp') And finally combining using lists to preserve the sort: final = list(measurements) + list(others) It seems like this could be done in a single query in Django and I suspect I could do it using Django's When by interpreting the missing sample as NULL. The problem is the underlying join will still give me multiple rows per Measurement. Here's an attempt that I think is close but returns duplicate rows: Measurement.objects.\ annotate(sort_field=Case(When(sample__definition=13, then=F('sample__value')), default=Value(None), output_field=IntegerField())).\ distinct().\ order_by(F('sort_field').asc(nulls_last=True), 'timestamp') Is this possible … -
Django 1.11: totally weird HTML-escape problem
I'm moving a codebase to Django 1.11, and some of my widgets now display HTML as if they are being HTML-escaped: <h2>Hello from Foo</h2> I've been through the docs about autoescape and safe, with no joy. So I thought I would go back to basics of templates. This is literally the only text in my template file: <h2>Hello from Foo</h2> And yet the browser renders the tag as ascii text, and not as a formatting command to the browser. How can this be happening? There is no variable-expansion or autoescape anywhere near this, and no simple_tag that now defaults to autoescape. But some agent is applying an HTML-escape to this code. I'm baffled. -
Django: resize images with different width/height ratios
For a page showing many pictures I use something like <img src='{{ instance.piece_image.url }}' hspace='40' vspace='40' style='width:16%;height:16%;'/> or <img src='{{ instance.piece_image.url }}' hspace='40' vspace='40' width='250px' height='250px'/> However, my images have different width/height ratios and differ in absolute size (allowing more flexibility for the user uploading the image). Now the first method keeps the aspect ratio while not respecting the absolute size of the image whereas the second method fixes the absolute size but does not accommodate for different aspect ratios. What would be the preferred way to resize my images keeping the aspect ratio and and providing a fixed absolute size (of the greater of width or height)? E.g. it could be achieved by recalculating the width and height with basic math but I did not find a convenient way to do this in a template yet. -
redis.exceptions.LockError: Cannot release an unlocked lock after restarting celerybeat
sometimes after restarting celerybeat , I get the following error, I have setup celerybeat as a service with redis, sude service celerybeat restart Below is the exception trace Traceback (most recent call last): File "/home/ec2-user/pyenv/local/lib/python3.4/site-packages/celery/beat.py", line 484, in start time.sleep(interval) File "/home/ec2-user/pyenv/local/lib/python3.4/site-packages/celery/apps/beat.py", line 148, in _sync beat.sync() File "/home/ec2-user/pyenv/local/lib/python3.4/site-packages/celery/beat.py", line 493, in sync self.scheduler.close() File "/home/ec2-user/pyenv/local/lib/python3.4/site-packages/redbeat/schedulers.py", line 272, in close self.lock.release() File "/home/ec2-user/pyenv/local/lib/python3.4/site-packages/redis/lock.py", line 135, in release self.do_release(expected_token) File "/home/ec2-user/pyenv/local/lib/python3.4/site-packages/redis/lock.py", line 264, in do_release raise LockError("Cannot release a lock that's no longer owned") redis.exceptions.LockError: Cannot release a lock that's no longer owned During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/ec2-user/pyenv/local/lib/python3.4/site-packages/celery/apps/beat.py", line 112, in start_scheduler beat.start() File "/home/ec2-user/pyenv/local/lib/python3.4/site-packages/celery/beat.py", line 490, in start self.sync() File "/home/ec2-user/pyenv/local/lib/python3.4/site-packages/celery/beat.py", line 493, in sync self.scheduler.close() File "/home/ec2-user/pyenv/local/lib/python3.4/site-packages/redbeat/schedulers.py", line 272, in close self.lock.release() File "/home/ec2-user/pyenv/local/lib/python3.4/site-packages/redis/lock.py", line 133, in release raise LockError("Cannot release an unlocked lock") redis.exceptions.LockError: Cannot release an unlocked lock The exception does not happen every time and I have not noticed any issues caused by this, celerybeat works fine even after this exception. Since it is the production environment, I want to handle it safely. -
How to implement Remember me functionality with DRF JWT?
I am trying to implement a way for users to stay logged in my website using the JWT DRF implementation. From the documentation it's suggested that as soon as a token is expired there is no way to refresh them. Given that a user might close their browser, my only two options are either having long-lived tokens or storing the username/password in localStorage, and both options seem insecure. Is there a different way to achieve this? Alternatively is there a way to only have long-lived tokens depending on what a user wants (i.e chooses the remember me option) -
django controlcenter display line chart with multiple items coming from model file field
I have a series of model entries containing pandas dataframe stored in a h5py file. Each entry file is structured as is: index - date - rate - active I would like to plot the evolution of the rate column over time (date) for each one of them. so I have started to create the following LineChart class with django controlcenter: import datetime from django.utils import timezone from controlcenter import Dashboard, widgets from .models import Currency import pandas as pd class CurrencyPriceLineChart(widgets.LineChart): title = 'Currency Price (EUR)' width = 3 height = 550 model = Currency the_data = model.objects.all() limit_to = None class Chartist: options={ 'axisX':{ 'labelOffset':{ 'x':-24, 'y':0 }, }, 'chartPadding':{ 'top':24, 'right':24, } } def legend(self): the_vals = [f.symbol for f in self.the_data] return the_vals def labels(self): today = timezone.now().date() labels = [(today-datetime.timedelta(days=x)).strftime('%d.%m') for x in range(self.limit_to)] return labels def series(self): series = [] for sym in self.legend: item = self.values.get(sym,{}) series.append([item.get(label,0) for label in self.labels]) return series def values(self): queryset = [] for currency in self.the_data: the_file = currency.historical_data.file df = pd.read_hdf('{}'.format(the_file),'Currency') queryset.append([df]) return queryset the basic documentation there : https://django-controlcenter.readthedocs.io/en/latest/examples.html#displaying-series-in-legend is a bit confusing to me since the question is about plotting data from an entry … -
How to link up to pages in django
What I need to do is, I need to go to a list view to another list view. But I need to filter the later list view with the clicked link. What is the filter attribute then? I have a student model with batch (sbtc), I need to pass the later list view with a filter of selected batch. @method_decorator(login_required, name='dispatch') class FindStudent(ListView): template_name = 'Dashboard/findStudent.html' model = Student fields = ['sbtc'] def get_queryset(self): batch = Student.objects.values_list('sbtc').distinct() return batch @method_decorator(login_required, name='dispatch') class FindStudentdetail(ListView): template_name = 'Dashboard/findStudentdetail.html' model = Student fields = ['all'] def get_queryset(self): student = Student.objects.filter(sbtc=#here what will be) return student -
How to make my request.method==post work? my code goes to else code and logs me out to home screen.I am unable to take users information
when create page opens up, even if i don't fill any information ,it does'nt gives me the error all fields are required , rather every time it logs me out and goes to home page. I think my if(request.method==post) block is not processing. from django.shortcuts import render,redirect from django.contrib.auth.decorators import login_required from .models import Product from django.utils import timezone def home(request): return render(request,'products/home.html') @login_required def create(request): if request.method == 'POST': if request.POST['title'] and request.POST['body'] and request.POST['url'] and request.FILES['icon'] and request.FILES['image']: product = Product() product.title=request.POST['title'] product.body=request.POST['body'] if request.POST['url'].startswith('http://') or request.POST['url'].startswith('https://'): product.url=request.POST['url'] else: product.url= 'http://'+ request.POST['url'] product.icon=request.FILES['icon'] product.image=request.FILES['image'] product.pub_date= timezone.datetime.now() product.hunter=request.user product.save() return redirect('create') else: return render(request,'products/create.html',{'error':'All fields are required'}) else: return render(request,'products/create.html') -
Django-allauth use for facebook login signup as json api
I'm evaluating django-allauth for my api. This api must support user signup via json over http as it's powering a phone app. Reviewing the example demonstrates usage with django templates, i.e. html pages via traditional request-response cycle in a browser. Is it possible to use django-allauth views to power an app signup on a json api? If not how would you solve this in django? (I've been avoiding django rest framework on this project btw) -
How can i construct a Docker for a Django Web App + Java?
I have a web app developed with Django and some libraries are written in Java. (For ex : Stanford POS Tagger). I would like to know what can i do to dockerize my app. I find many tutorials about how to dockerize a Django App, but i don't know how to do it if some libraries need to use the JVM. Thank you so much. -
Any way to fetch the through fields for an object linked via Many2Many field without knowing the column name in advance?
I am trying to write a generic method that can take any Django Model and returns it in a dictionary form. So for example, if my models are defined thus (very generic): class A(models.Model): somefieldA = models.TextField() m2mfield = models.ManyToManyField(B, through='AandB') def __unicode__(self): return self.somefieldA class B(models.Model): somefieldB = models.TextField() def __unicode__(self): return self.somefieldB class AandB(models.Model): a = models.ForeignKey(A) b = models.ForeignKey(B) field1 = models.DecimalField() field2 = models.TextField() field3 = models.DateField() Now, assume we have an instance of the object A a_obj. I can get all the related B objects using: # This loop is there because I am working with other fields as well. def instance_to_dict(instance) for field in instance._meta.get_fields(): if field.many_to_many: m2m_mgr = getattr(instance, field.name) for idx, assoc_obj in enumerate(m2m_mgr.all()): assoc_obj_str = str(assoc_obj) # How to obtain the related through field values? # m2m_mgr.through.objects.get() would need prior knowlegde # of field name # m2m_mgr.through.objects.all() fetches all the objects # in the Many to Many manager. Ideally, I would like to create a dict of the obj and related "through" fields for any object. Is this possible to do? -
Gunicorn spiking CPU to 100% on certain pages...killing performance
I have a Django app that is being served through Nginx / Gunicorn. When loading certain pages, Gunicorn is spiking in CPU usage to 100% and totally killing performance, causing the page to take 10 seconds to load. I am not making any DB calls - I have all the results loaded into memcached already. It should be very fast so this insane slow down is wild. gunicorn_start: NAME="name" # Name of the application MAINDIR=/opt/name/ DJANGODIR=/opt/name/path # Django project directory SOCKFILE=/opt/name/run/gunicorn.sock # we will communicte using this unix socket USER=nginx # the user to run as GROUP=nginx # the group to run as NUM_WORKERS=3 # how many worker processes should Gunicorn spawn DJANGO_SETTINGS_MODULE=name.settings # which settings file should Django use DJANGO_WSGI_MODULE=name.wsgi # WSGI module name lscpu: Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Byte Order: Little Endian CPU(s): 8 On-line CPU(s) list: 0-7 Thread(s) per core: 1 Core(s) per socket: 1 Socket(s): 8 NUMA node(s): 1 Vendor ID: GenuineIntel CPU family: 6 Model: 63 Model name: Intel(R) Xeon(R) CPU E5-2660 v3 @ 2.60GHz Stepping: 2 CPU MHz: 2593.993 BogoMIPS: 5187.98 Hypervisor vendor: VMware Virtualization type: full L1d cache: 32K L1i cache: 32K L2 cache: 256K L3 cache: 25600K NUMA node0 CPU(s): … -
Django User Created Alerts
So I'm looking to add alerts to my current system based on post requests. The whole project is using Django and MySql. Basically the project works by sending a post request to the server and enters the JSON data into the database. I am easily able to create alerts for this use Django Alert That part is all good. My dilemma lies on how would I allow a user to customize the alerts in a form based on templates I've previously created. How would I store these alerts? Is there an existing framework I'm unaware of? If my question doesn't make sense please ask for further clarification and I will provide it. Thanks in advanced. -
name_file/Scripts/activate 'name_file' is not recognized as an internal or external command, operable program or batch file windows 10
I Uploaded virtualenv in my computer by cmd and when I activated it by this code "name_file/Scripts/activate" diden't work and appeared to me this message : " 'name_file' is not recognized as an internal or external command, operable program or batch file " -
Why would I want to integrate CSS into JavaScript?
I've been tasked with converting the static asset management for a Django project to webpack (it currently uses django pipeline). I got the JavaScript done no problem, then moved onto the SASS files, using sass-loader, which to my horror seems to want to convert the CSS into JavaScript, which is apparently a thing these days. Questions: Why would I want to do this? Is it worthwhile doing on a django project? What needs to change in the HTML templates for this to work? Are there any Django plugins which help with this? -
django sorting by dropdown list
I'm looking for a solution that I imagine would be pretty simple (however, I could not find any clues in the internet, nor in the documentation) I have a piece of code in my template that looks like this: <dl class="accordion"> {% for show in shows_list %} {% ifchanged show.film.film_name %} <dt><a href="">{{show.film.film_name}}</a> {% if show.show_on_festival != None %} <p class="additional">festival {{show.show_on_festival}}</p> {% endif %} </dt> {% endifchanged %} <dd>{{show.show_host}} {{show.show_time|time:"H:i" }}</dd> {% endfor %} </dl> I want to create a dropdown menu that rearranges it somehow by-click, for example, to this (i.e. display by cinemas instead of displaying by film): <dl class="accordion"> {% for show in shows_list %} {% ifchanged show.show_host %} <dt><a href="">{{show.show_host}}</a> {% if show.show_on_festival != None %} <p class="additional">festival {{show.show_on_festival}}</p> {% endif %} </dt> {% endifchanged %} <dd>{{show.film.film_name}} {{show.show_time|time:"H:i" }}</dd> {% endfor %} </dl> The question complicates with the fact of there must be other independent dropdown lists specifying tag-filters (i.e. 'shorts', 'doc', 'premiere', etc. - stored in show) and the result must come from applying all the dropdowns. So, how can all this be implemented, and what would the idea of doing it look like? -
Migrating django-stripe-payments to pinax-stripe
I am migrating from Django 1.8 -> and I need to remove django-stripe-payments. However, "payments" is listed in the dependencies under the initial migration. dependencies = [ ('contenttypes', '0002_remove_content_type_name'), ('payments', '__first__'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] I've tried removing the line with payments in it, but this raises another error. Unfortunately, the official documentation doesn't list steps on how to do this: https://pinax-stripe.readthedocs.io/en/latest/user-guide/upgrading/ -
Django Upload SVG to ImageField
Looking to see if anyone has come up with a creative approach for storing SVG files in an ImageField. Out of the box django doesn't support storing of SVG files in an ImageField. There's a (a few) hack(s) out there that allow the SVGs to be stored BUT the specific issue I'm encountering is that when an object with an SVG in an ImageField is retrieved from the database, if the respective file is not present in storage (for any number of reasons) an IOError is raised when trying to update the dimensions(here). This is really not ideal behavior. Ideally, django would offer some option to prevent the updating of the dimension fields, but this does not appear to be available. For context, consider an application where a user need to upload a logo. It's a bit strained to maintain separate models for JPEG or PNG files and SVG files. For DRF projects (which I am), perhaps there's a proxy model solution here using a serializer with a dynamic model. -
Django Python json loads show me /x97
Hello guys i’m trying to make my web app with django and python I’m working with jquery and Ajax, and all working fine, the only problem is when I’m trying to make json loads it convert me strings in some characters. How can I make a correct Jason loads correctly? This is an example how python send me the json import io, json data = json.loads(data) [{'div_oculto': ' 1 punto de medida \x97 Método \x97 Lugar de \x97 Servicio ', 'num_articulos': '1', 'no_item': '1', 'precio_real': ' 2470 ', 'descripcion_productos': ' INSTRUMENTO \x97 (10, 25 ó 50) (-40 a 130) °C ', 'precio_unitario': '2,470.00', 'comentarios_item': '', 'precio_total': '2,865.20', 'urgente': '0'}]3[{'descuento_gobal': '0'}, {'viaticos': '0'}, {'total_cotizado': '2,865.20'}][{'comentarios_cotizacion': ''}] -
Django Model with a Field Containing Lists / Dictionaries
I have a Django model where one of the fields is called Title. This field is populated with a list which can contain one or more titles. Currently when I render this field in a template I get the following: Title = ['Title 1','Title 2',...] Is there a way to parse Python objects such as lists / dictionaries from a field in a Django model? Alternatively do I need to create a separate "Title" model and link it to the original one? Currently, the field is displayed as a string, including the list brackets. -
automatically update django website with instagram
I want to create a website which articles will be instagram post. For example, when I post something to sell on instagram, it automatically generates a post on my website with a picture and a description (maybe also a contact form if I'm interested in the product, but this is not the most important for now) Can I do this with Django? If yes, I would appreciate some help. -
Exporting using django-import-export and showing verbose names of related objects
I was having a look at the following library - django-import-export. However, I am having issues with exporting with friendly/verbose column names for related objects. Related link: https://github.com/django-import-export/django-import-export/issues/52 class HumanModelResource(resources.ModelResource): def get_export_headers(self): headers = [] for field in self.get_fields(): model_fields = self.Meta.model._meta.get_fields() header = next((x.verbose_name for x in model_fields if x.name == field.column_name), field.column_name) headers.append(header) return headers class Meta: model = Human fields = ("name", "pet__name") class HumanAdmin(ExportMixin, admin.ModelAdmin): resource_class = HumanModelResource list_display = ("name", "pet") class Human(models.Model): name = models.CharField(max_length=255, verbose_name="Name") pet = models.ForeignKey(Pet) class Pet(models.Model): name = models.CharField(max_length=255, verbose_name="Pet Name") Exporting will show "Name" for the human but the pet name will show up as "pet__name". I'm not sure how to approach overriding the get_export_headers method to display the related objects verbose name. I am currently using: - Python 2.7 - Django 1.11 -
Django Foreign Key for groups and other apps
QUESTION 1) In the following codes, How do I make it in such a way that when the name of the user is selected from the drop down box, The mail ID entered while registering the user onto the admin site is automatically selected instead of the user while filling up this form writes the email ID manually? (To the assigned to Mail ID) QUESTION 2) How do we ensure that the members mentioned in the other Projects App are the only ones who get mentioned as options in this list? (In the assigned to column. Also, is it possible to change the data that gets mentioned like say for example Zack - Tester Jake - Debugger and so on) STATUS_CHOICE = ( ('Unassigned', 'Unassigned'), ('Assigned', 'Assigned'), ('Testing', 'Testing'), ('Tested', 'tested'), ('Fixed', 'Fixed') ) STATUS_CHOICE_1 = ( ('Bug', 'Bug'), ('Issue', 'Issue'), ('Enhancement', 'Enhancement'), ('Not an issue or bug', 'Not an issue or bug'), ('Fixed', 'Fixed') ) Project = models.ForeignKey(Project, on_delete=models.CASCADE) Issue_Title = models.CharField(max_length=50, blank=True, null=True) Situation_Type = models.CharField(max_length=25, choices=STATUS_CHOICE_1) Basic_Description = models.CharField(max_length=100) Detailed_Description = models.TextField(default='The Description, here.') Status = models.CharField(max_length=18, choices=STATUS_CHOICE) Assigned_to = models.ForeignKey(User, on_delete=models.CASCADE) Assigned_to_Mail_ID = models.EmailField(max_length=50, blank=True, null=True) Admin_Mail_ID = models.EmailField(max_length=50, blank=True, null=True) Reported_by = models.CharField(max_length=50, blank=True, null=True) … -
Django: Why won't the option render as selected?
In my html template I have a select control and want to set the selected option based on a variable {{specialtyId}}. The expected result is that the selected option will be selected, but the actual result is that no option is selected: Here is the code: <label>{{specialtyId}}</label> <select class="form-control" id="specialtyId" name="specialtyId" required="True"> {% for s in specialties %} <option value="{{s.specialtyId}}" {% if value == specialtyId %} selected {% endif %}>{{s.specialtyName}}</option> {% endfor %} </select> As you can see, {{specialtyId}} in the label has the value of 2 but the option associated with 2 is not selected. What am I doing wrong? -
Django+ptb+gunicorn+nginx telegram bot doesn't respond on command
Dear StackOverFlow community. Trying to setup webhook in my bot using Django, Ptb, Nginx, Gunicorn. But bot doesn't respond on /start command Telegram telling that's all ok with webhook: {"ok":true,"result":{"url":"https://mysite.info/partnersbot/token","has_custom_certificate":false,"pending_update_count":0,"max_connections":40}} When i sending /start to my bot - i got no response, but gunicorn log file tells that response is processed: [11/Sep/2018:12:46:42 +0000] "POST /partnersbot/token HTTP/1.0" 200 2 "-" "-" and "pending_update_count":0 in /getWebhookInfo application folder of my django project: /home/partners/partnersbot handlers appends in the: partnersbot/config.py from telegram import Bot from telegram.ext import Dispatcher, CommandHandler from partnersbot.handlers import start API_TOKEN = 'token' BOT = Bot(API_TOKEN) DIS = Dispatcher(BOT, None, workers=0) DIS.add_handler(CommandHandler('start', start)) handlers processing in: partnersbot/views.py from django.http import JsonResponse import json from telegram import Update from partnersbot.config import BOT from partnersbot.config import DIS def webhooks(request, bot_token): try: upd = Update.de_json(json.loads(request.body.decode("utf-8")), BOT) except Exception as e: return JsonResponse({}) DIS.process_update(upd) return JsonResponse({}, status=200) test handler in partnersbot/handlers/start.py def start(bot, update): update.message.reply_text('All works fine!') /etc/nginx/sites-available/partners server { listen 80; server_name myhost.info; return 301 https://myhost.info; location = /favicon.ico { access_log off; log_not_found off; } location / { include proxy_params; proxy_pass http://unix:/home/user/partners/partners.sock; } } server { listen 443 ssl; listen [::]:443 ssl; server_name myhost.info; ssl on; ssl_certificate /etc/letsencrypt/live/myhost/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/myhost/privkey.pem; location /static/ { root …