Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Enhancing a queryset's performance
I'm learning DRF and experimenting with a queryset. I'm trying to optimize to work as efficiently as possible. The goal being to get a list of grades for active students who are majoring in 'Art'. Based on database optimization techniques, I've ran some different updates and don't see a difference when I look at the Time returned via the console's Network tab. I DO however, see less logs in the Seq scan when I run the .explain() method on the model filtering. Am I accomplishing anything by doing that? For example: Grades.objects.filter(student_id__in=list(student_list)).order_by() Anything else I can do to improve the below code that I might be missing? - Outside of adding any Foreign or Primary key model changes. class GradeViewSet(viewsets.ModelViewSet): serializer_class = GradesSerializer def retrieve(self, request, *args, **kwargs): active_students = Student.objects.filter(active=True) student_list = active_students.filter(major='Art').values_list('student_id') queryset = Grades.objects.filter(student_id__in=student_list) serializers = GradesSerializer(queryset, many=True) return Response(serializers.data) -
Django: variable in View is not null but Template takes is as null
I've a View: cart_details that queries my CartItem objects and my SampleItem objects, and sends both queries to my template: cart.html. In my view: Using prints statements I see that both queries, stored in variables cart_items and sample_items, are not empty. In my template: However Using if else statements in my template, these variables appear as null??? how come? views.py def cart_detail(request, total = 0, counter = 0, cart_items = None): try: cart = Cart.objects.get(id = request.COOKIES.get("cart_id")) if cart: print("Cart exist") else: print("Cart does not exist") cart_items = CartItem.objects.filter(cart = cart) if cart_items: print("There are CART_ITEMS") print(len(cart_items)) else: print("There aren't CART_ITEMS") for cart_item in cart_items: total += int(cart_item.sub_total()) sample_items = SampleItem.objects.filter(cart=cart) for sample_item in sample_items: total += int(sample_item.sub_total()) if sample_items: print("There are SAMPLE_ITEMS") print(len(sample_items)) else: print("There are not SAMPLE_ITEMS") culqi_my_public_key = settings.CULQI_PUBLISHABLE_KEY #Es necesario mandar la llave pública para generar un token culqi_total = int(total * 100) #El total para cualqui debe multiplicarse por 100 categories = Category.objects.exclude(name='Muestras') print(total) return render(request, 'cart.html', dict(cart_items = cart_items, sample_items = sample_items, total = total, counter = counter, culqi_total = culqi_total, culqi_my_public_key = culqi_my_public_key, categories = categories)) except: categories = Category.objects.exclude(name='Muestras') return render(request, 'cart.html', {'categories':categories}) cart.html {% extends 'base.html' %} {% load staticfiles %} … -
Acquire CSRF token for chrome extension from django
I want to use a POST request to send data from chrome extension to a Django app. However, I'm getting a 403 Forbidden error. How do I acquire the CSRF token from Django to send as a header along with the chrome extension? -
csrftoken cookie fails security test - Missing Flags
I am getting a security error (from Pentest-Tools) saying that the "Secure" and "HttpOnly" flags are missing in my Django project, and not quite sure how to remedy. I set the cooke with the following in my template {% csrf_token %} I've read you need to set these flags in the headers, but not sure if that's the resolution. What is the way to set the Secure and HttpOnly flags? -
Django- drop leading zeros in field with conditoinal
I'm displaying data from my database using Django templates. I would like to remove the leading zeros in a certain fields(the ops and obp fields), only when the value to the left of the decimal point is a zero. Otherwise if the value to the left of the decimal point is greater than zero, I would like that to be displayed. Yes, I realize it's the same value whether it has the leading zero or not, but I have my reasons for wanting to display it like this. views.py from django.shortcuts import render from .models import BattingRegStd # Create your views here. def batting(request): battingregstd2018 = BattingRegStd.objects.filter(year=2018) return render(request, 'playerstats/battingReg2018.html', {'battingregstd2018':battingregstd2018}) HTML {% extends "base.html" %} {% block contents %} <div align="center"> <table class="equalDivide"> <thead> <tr> <th>OBP</th> <th>OPS</th> <th>TB</th> </tr> </thead> <tbody> {% for index in battingregstd2018%} <td>{{ index.obp|floatformat:3}}</td> <td>{{ index.ops|floatformat:3}}</td> <td>{{ index.tb}}</td> </tr> {% endfor %} </tbody> </table> </div> <br> {% endblock %} -
Django ImportError: No module named myapp_name.settings
I was editing an old project that could be used for a new functionality but now I can not get it going. I have tried almost all the solutions I've seen on the web but I have not guessed right. The repository where the project is is this: https://github.com/AlejandroFerroBejerano/QARxisAccesControl.git and when I try to run '$ python manage.py migrate' I get the error: ImportError: No module named QARxisAccessControl.settings You can tell me where the error is? How can i launch the python manage.py migrate command without errors? I let you the repo tree since: ~/Proyectos/QARxisAccesControl/src/prototypes/QARxisAccessControl$ tree -
Javascript function causing page to freeze
I am using moment.js CDN to increment a time select box, based of the previous length select input. The function appears to be working fluidly in jsfiddle; however, when loaded on my local server, after activiating the function by choosing a length select option, the page simply freezes. I am unsure if this is an error with the Javascript function, or the order of my CDN scripts. I would greatly appreciate any help with this issue. HTML {% extends "view/base.html" %} {% block title %}XYZ{% endblock %} {% load static %} {% block body %} <hr /> <div class="row"> <div class="col-md-5 mx-auto border" id="box"> <!-- Form --> <form action="{% url 'student:profile_page_edit' %}" method="POST" autocomplete="off"> {% csrf_token %} <div class="text-center"> <div class="form-group"> <div class="ins-left"> <p>Cello</p> </div> <div class="date-right"> <p>May 2, 2019</p> </div> </div> <br /> <br /> <div class="form-group"> <label>Length</label> <select class="form-control" id="length"> <option>Please Select Length</option> <option>30 min.</option> <option>60 min.</option> <option>90 min.</option> </select> </div> <br /> <div class="form-group"> <label>Time</label> <select class="form-control" id="time"> <option>10:00 am</option> <option>11:00 am</option> <option>12:00 pm</option> <option>1:00 pm</option> <option>2:00 pm</option> <option>3:00 pm</option> </select> </div> <div class="ins-left"> <p>Price: <span id="price">$30</span></p> </div> <div class="bottom"> <button type="submit" name="submit" class="btn blue_button">Book Now</button> </div> </div> <div class="hidden"> <p id="start">10:00 am</p> <p id="end">2:00 pm</p> </div> … -
How to display ChoiceField in django with html file?
I am new to django and I am trying to get ChoiceField working for user entry. I have tried two iterations of html but neither display any form of drop down. see my code below for models, forms , html models.py from django.db import models from django.contrib.auth.models import User class Post(models.Model): CATEGORIES=( ('COM', 'Combat'), ('CRA', 'Crafting'), ('WAR', 'Warfare'), ) post= models.CharField(max_length=500) post2= models.CharField(max_length=500) category=models.CharField(max_length=3, choices=CATEGORIES) user = models.ForeignKey(User, on_delete=models.CASCADE) forms.py class HomeForm(forms.ModelForm): post = forms.CharField() post2 = forms.CharField() category = forms.ChoiceField(choices=Post.CATEGORIES) class Meta: model = Post fields = ('post','post2','category',) html <form method="post"> {% csrf_token %} {{form.as_p}} or {{form}} <input type="submit" value="Submit"> </form> -
Using Django with mostly Static pages
I am new to web development and am working on a site for my yacht club. Because we needed the ability to have accounts and login users who are members, have calendars, polls, etc. ... we decided to go with Django because it is touted to be relatively easy to use, and I am familiar with Python. In our index.html we have written the static html to have a menu system that displays content based on whether the user has been authenticated or not in Django. The problem I am running into is that the menu works as expected unless we navigate away from it. The menu no longer shows up and it SHOULD show up in all of the pages that the user goes to. I have placed this into one of the pages that index.html links to when I did a google search and it was suggested that this should work but it does not. <script src="http://code.jquery.com/jquery.min.js"></script> <script> $.get("/", function(data){ $("#msa_TopNavbar").replaceWith(data); }); </script> I am at a complete loss of how to make this function. I have considered creating each page an a Django app within my project even if it is just a static page. I have … -
How can i use hit-counter in function based view django?
I want to have a page counter that displays the number of visitors who have viewed a particular page on my site. Is it possible to do this using Django? i tried to use hit-counter model but , it use class based view Is there an alternative solution? cause i use function based view -
Django papertrail logging failing mysteriously
I have set up papertrail for a Django project but logging fails with OSError: [Errno 9] Bad file descriptor. The weird thing is if I call django.setup() before the logging call it works... settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'json': { '()': 'pythonjsonlogger.jsonlogger.JsonFormatter', 'fmt': '%(levelname)s %(asctime)s %(message)s', }, }, 'handlers': { 'papertrail': { 'level': 'DEBUG', 'class': 'logging.handlers.SysLogHandler', 'formatter': 'json', 'address': ('logsN.papertrailapp.com', 12345) }, ... }, 'loggers': { 'papertrail': { 'handlers': ['papertrail'], 'level': 'ERROR', 'propagate': True, }, ... /management/commands/logging_test.py from django.core.management import BaseCommand import django import logging # uncomment this line to make it work #django.setup() def test_logging(): logger = logging.getLogger('papertrail') logger.error( 'TEST LOGGING' ) class Command(BaseCommand): def handle(self, *args, **options): test_logging() I can call the test_logging function with: ./manage.py test_logging If I uncomment the line django.setup() it works. I have no idea why.... Any help much appreciated. -
How to manage environment variables in one settings file for dev and prod in Django
I'm trying to merge local and prod settings files to one. local.py ... SECRET_KEY = os.environ['DJANGO_SECRET_KEY'] DEBUG = os.environ['DEBUG'] prod.py ... AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] As I don't use AWS env variables in local, I want the compiler not to check those env variables and also, is there a way to check if the environment is dev or prod so that I can do something like the below? settings.py if env == local: DEBUG = True else: DEBUG = False -
Token.object not found
I'm using djangorestframework in djnago==2.0 with python 3.7 I put an event like this @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: from rest_framework.authtoken.models import Token Token.objects.create(user=instance) when I tried to create a user the compiler giving an error: Exception Value: type object 'Token' has no attribute 'objects' -
Ruby on Rails Developed Applications
I'm looking to develop a desktop (not server) web application and I have been comparing Ruby on Rails vs Django. Question is, with Django the client needs to install Python 2.5, does the client need to install anything to execute a Ruby on Rails application? Thanks.... -
Django: invalid literal for int() with base 10: 'csrfmiddlewaretoken'
I have this error, when Im trying to save my form with the data. The form: class EntityCreateForm(forms.ModelForm): def __init__(self, chain, *args, **kwargs): super(EntityCreateForm, self).__init__(*args, **kwargs) self.fields['chain'] = forms.ModelChoiceField(queryset=Chain.objects.filter(pk__in = chain)) class Meta: model = Entity fields = '__all__' What's wrong with my csrfmiddlewaretoken? p.s. Everything work fine if I remove this part of my code: def __init__(self, chain, *args, **kwargs): super(EntityCreateForm, self).__init__(*args, **kwargs) self.fields['chain'] = forms.ModelChoiceField(queryset=Chain.objects.filter(pk__in = chain)) But I need it, because I want to create a dynamic choice field (like this Creating a dynamic choice field). -
401 raised before 405 in Django Rest Framework
I have this simple viewset that allows to create, retrieve and list a model : class GenreViewset(CreateListRetrieveViewset): """ Creates, lists and retrieves genres. """ serializer_class = GenreSerializer queryset = Genre.objects.all() permission_classes = (IsAuthenticatedOrReadOnly,) lookup_field = 'slug' When I test the corresponding endpoint for a PUT request, I expect to get a 405 status. However, that's not the case when a user is not authenticated, a 401 error is raised first. It's only when a user is authenticated that a 405 error is raised. Why is that and is it possible to force 405 to appear before 401 ? Thanks ! -
Why can't I print a choice model instance in Django?
Just a little backstory: I am new to Python/Django but had a working app that I had made in it that I am trying to restructure so that I can fully utilize the power of Django's Models. I currently have a choice model that a user selects from a drop down, after that they are redirected to a success page. Eventually, a script will execute based on their selection. On the success page I want to display their current selection as a "confirmation" of what they've executed the script on. After researching for a good bit, I gathered sort of the direction I need to go, but am having issues implementing, which leads me to believe I may be lacking some fundamental understanding on model setup, so some clarification there would be nice. Anyways, I want to use the get_device_display field in a template to do this. Whenever I try to implement it, however, it does not work. I see that some people use custom Model Managers for this, do I need to implement this somehow? Or maybe make another form/TemplateView when displaying the success page? Here is my code: modles.py from django.db import models class DeviceChoice(models.Model): DEVICE_NAMES = ( … -
ModuleNotFoundError: No module named 'celery'
return _bootstrap._gcd_import(name[level:], package, level) File "C:\Users\moustafa gebril\allh\saleor\saleor__init__.py", line 1, in from .celery_app import app as celery_app File "C:\Users\moustafa gebril\allh\saleor\saleor\celery_app.py", line 4, in from celery import Celery ModuleNotFoundError: No module named 'celery' -
Django snippets didn't work on atom. I just installed a new two packages
I did nothing after install this packages. Then, i try for some code in Django, but just another snippets shown on the list, not django snippets -
Django: only 1 field from model not updating
I have a model with companies profiles, a model form and a page where I show the form and can edit it. When I change the data in the form all the fields get updated correctly except 1: "NombrePcia". It´s just a charfiled and there is no filtering around that value. I can´t understand why the update is missing just this filed. Thanks in advance. The model class Contactos(models.Model): codigo = models.IntegerField(help_text=" Código ", blank=True, null=True) Nombre = models.CharField(max_length=200, help_text=" Nombre ", blank=False, null=True) Domicilio = models.CharField(max_length=200, help_text=" Domicilio ", blank=True, null=True) Localidad = models.CharField(max_length=200, help_text=" Localidad ", blank=True, null=True) CodPostal = models.IntegerField(help_text=" Cod.Postal ", blank=True, null=True) PR = models.IntegerField(help_text=" PR ", blank=True, null=True) Razonsociallegal = models.CharField(max_length=200, help_text=" Razón.social.legal ", blank=True, null=True) Telefonos = models.CharField(max_length=200, help_text=" Teléfonos ", blank=True, null=True) NroDoc = models.DecimalField(help_text=" Nro.Doc. ", decimal_places=2, max_digits=100, blank=True, null=True) TD = models.IntegerField(help_text=" TD ", blank=True, null=True) SituacionIVA = models.CharField(max_length=200, help_text=" Situación.IVA ", blank=True, null=True) NombrePcia = models.CharField(max_length=200, help_text=" NombrePcia ", blank=True, null=True) emailEmpresa = models.CharField(max_length=200, help_text=" email.Empresa ", blank=True, null=True) Agrupacion1 = models.ForeignKey("Conceptos_Clientes", help_text="Concepto cliente", blank=True, null=True, on_delete=models.CASCADE) Agrupacion2 = models.IntegerField(help_text=" Agrupacion2 ", blank=True, null=True) BancoCBU = models.DecimalField(help_text=" BancoCBU ", decimal_places=2, max_digits=100, blank=True, null=True) CodigoZona = models.IntegerField(help_text=" CodigoZona ", blank=True, … -
Cannot assign "<class 'FitApp.models.user_list'>": "item.item_list" must be a "user_list" instance
Models for list and items inside lists. I am trying to get output to the page with a list that is assigned to user who created it. class user_list(models.Model): name = models.CharField(max_length=100, default="") parent = models.ForeignKey("self", on_delete=models.CASCADE, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE) class item(models.Model): name = models.CharField(max_length=100, default="") item_list = models.ForeignKey(user_list, on_delete=models.CASCADE) class data(models.Model): data = models.IntegerField(default="") data_list = models.ForeignKey(user_list, on_delete=models.CASCADE) I have a form in the app.html like this: <form action="{% url 'add' %}" method="POST" role="form"> {% csrf_token %} {{ form.text }} <span class="input-group-btn"> <button type="submit" id="id_btn">ADD</button> </span> </form> url "add" looks like this: path('add/', views.addList, name='add'), and views: @require_POST def addList(request): form = list_form(request.POST) if form.is_valid(): new_list = item(name=request.POST['text'], item_list=user_list) new_list.save() return redirect('app') I definetly has something to do with this "item_list=user_list" line but I cant figure out why. I think Im passing the list_id wrong. new_list = item(name=request.POST['text'], item_list=user_list) These models worked in django manage.py shell. I was able to create new lists and add items and data to them. I used this command in shell to make a new item: item1 = item(name='something', item_list=list1) list1 is user_list model wich I had created earlyer. But with user input that list1 place should change accordingly to user editing. -
How to sort elasticsearch query in Django?
How to sort elasticsearch query in Django? I need to sort articles by timestamp in descending order (at least, by id). I'm using elasticsearch-dsl==6.2.1, django==2.1.2 In search.py I have: class ArticleIndex(DocType): title = Text() content = Text() timestamp = Date() class Meta: index = 'article-index' def bulk_indexing(): ArticleIndex.init() es = Elasticsearch() bulk(client=es, actions=(b.indexing() for b in models.Article.objects.filter(is_active=True).iterator())) def search(item): s = Search().sort('-timestamp') # sort not works here q = MultiMatch(query=item, fields=['title', 'content']) response = s.query(q) return response If in search function I add for hit in response: print(hit) I have this: <Hit(article-index/doc/8): {'title': 'Article 8...}> <Hit(article-index/doc/12): {'title': 'Article 12...}> <Hit(article-index/doc/6): {'title': 'Article 6...}> ... Thank you for your time and help. -
Why does "pip download -r" require a setup.py file?
I'm setting up a private PyPI server pypis.example.com for storing packages that are required by my Django website. I'm using pypiserver to serve packages from that server. So far, pypiserver seems to work just fine. However, while I can download packages onto the server one at a time, I can't seem to download them if I'm using a requirements file. For example, if I run this command on my pypiserver, I can download individual packages with no errors: pip download -d /var/www/pypis.example.com/packages Django==1.8.4 But if I put all of my 40+ requirements in a requirements file and try to load them all at once with this command: pip download -r requirements.txt -d /var/www/pypis.example.com/packages/ I get this error: Directory '/var/www/pypis.example.com/packages' is not installable. Neither 'setup.py' nor 'pyproject.toml' found. My requirements file looks like this: -i https://pypi.org/simple django==1.8.4 django-rq==0.9.0 (more packages follow) Why is pip complaining about needing a setup.py file to download packages if one isn't required to install packages? I'm a web developer, not a Python package developer, so setup.py and pyproject.toml files are new to me. -
Error: __init__() keywords must be strings
Django Filter is throwing an error when filtering by a many to many field. It appears that the predicate isn't being formed correctly as its formed as {None:[instance id]} I assume that it should be more like {id:[instance id]} Below is a copy of the relevant code on my end and the related error. self.filters['template'] = django_filters.MultipleChoiceFilter( choices=models.Template.objects.exclude(name__in=default_template_names).values_list('id', 'name'), widget=autocomplete.Select2Multiple(attrs={'data-placeholder': 'Template'})) Error occurs here: django_filters/filters.py in filter at line 248 v = None predicate = self.get_filter_predicate(v) if self.conjoined: qs = self.get_method(qs)(**predicate) else: q |= Q(**predicate) predicate is: {None: '66'} 66 is the ID of the relevant instance trying to be filtered on. -
Sharing authenticated users between Django and django-rest-framework in the same project
I have a Django project that will ultimately consist of three apps. Two of which will be "normal" Django apps, the third is a djangorestframework app. I also plan on creating a desktop client for the project at some point. I want the rest app to be the only entity communicating with the database. Hence I use requests to communicate with the rest endpoints from the views of the "normal" Django apps and I will do the same for the desktop client. I want all apps to be accessible only for authenticated users, so I'm using Django's authentication backend. My question is how to pass on the authenticated user/session from the pure Django apps to the rest endpoints when using requests in the views. I managed to authenticate on the rest API using request's HTTPBasicAuth, but that requires me to have the user's password at hand in plain text. Sure, I could create a technical user to do these requests. But that would also mean that each and every request would need to go through authentication first and that doesn't feel like the best approach. I have tried to extract the session cookie from the request object that is provided …