Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Complex subquery - Get similar objects of other objects (and other model)
First of all, I am a non-native English speaker. Please excuse me if I make a mistake. I have these models: class Qualifier(models.Model) name = CharField(max_length=255, db_index=True) class Sale(models.Model): user = ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name='sales', null=True ) qualifiers = ManyToManyField(Qualifier, blank=True, related_name='sales') class Purchase(models.Model): user = ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name='purchases', null=True ) qualifiers = ManyToManyField(Qualifier, blank=True, related_name='purchases') I want to get all purchases that have the same qualifiers of a sale, and I already got it: class Sale(models.Model): def get_related_purchases(self): purchases = Purchase.objects.all() for qualifier in self.qualifiers.all(): purchases = purchases.filter(qualifiers=qualifier) return purchases But I also need all purchases that match all sales of a user. Currently I do this, but it is obvious that it is not optimal because I iterate over each user sale (and may be thousands): class User(AbstractUser): def get_related_purchases(self): purchases = None for sale in self.sales.all(): related_purchases = sale.get_related_purchases() if purchases is None: purchases = related_purchases else: purchases |= related_purchases return purchases Thanks for your help. -
django-haystack larger numbers returned as smaller
Currently running django-haystack with elasticsearch. Currently when I try to order prices of product a larger number is seen as smaller in the list. E.g. 19,342 is smaller than 2345 because of the first two charactes. 1 and 9. Anyone come across this before? -
How do I run Django migrations automatically on Deis when using a buildpack deployments?
The post-compile hook on Deis seems to function differently than on Heroku. On Heroku I could simply add a bin/post-compile file containing: # env bash python manage.py migrate --noinput On Deis this gives me a traceback Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line No module named django.core.management Is anyone running Django on Deis using buildpacks and have a working example of this? -
Django project can't connect with Postgresql database - Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432?
I am using Docker with my Django project. When I am trying to run server docker-compose up I get error: django_1 | django.db.utils.OperationalError: could not connect to server: Connection refused django_1 | Is the server running on host "127.0.0.1" and accepting django_1 | TCP/IP connections on port 5432? It seems to me that I was trying everything. I have no idea what is wrong. My settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'localhost', 'PORT': 5432, } } -
Flask static files not updating
on my flask python server I do this - open('index.html', 'r').read() and the first time it read it fine and when I update index.html it doesn't update on the browser. I've tried clearing browser cache. -
Low-level cache in django
I am going to use django low-level cache. Need I set up it in settings? I am not sure because it is simple cache- just a dictionary. Is it thread-safe? -
Django redirect views with parameter/context
I have register view in my django app, that redirects to the homepage: def register(request): ...register... return redirect("/") def homepage(request): users = User.objects.all().order_by('username') return render(request, 'index.html', {'users': users}) I want to add variable new_user that would tell the homepage if user is new. I would pass variable from register view to the homepage view and than into the template where i would handle it: {% if new_user %} <h1>Welcome</h1> {% endif %} But i dont know how to pass this variable from register view to homepage and than into the template. Help is well appreciated! -
set two python paths in the some Django app in pycharm
I have create a Django app and working nice using pycharm editor in windows. my app : myapp - __init__.py - settings.py - urls.py - wsgi.py app.name - __init__.py - admin.py - apps.py - forms.py - modelspy - test.py - urls.py - views.py now I need to add new python file in app.name to call some function in views.py like this: myfynction(input,output) #that in views. app.name - __init__.py - admin.py - apps.py - forms.py - modelspy - test.py - urls.py - myfunction.py - views.py the problem is the additional myfunction.py file have different python path python.exe from all Django app. can I set two python paths in the some Django app in pycharm ? -
how to display image description written by user in django template
I am a newbie in Django.I want to create simple upload app in which description of image ,price and email-id will be entered by the user.And want to display the description text and email along with the image.But the text is not appearing along with the image. See the final image after uploading Below is my code : Models.py # -*- coding: utf-8 -*- from django.db import models class Document(models.Model): docfile = models.FileField(upload_to='documents/%Y/%m/%d') description = models.CharField(max_length=255, blank=True) price = models.IntegerField(default=0) emailId = models.CharField(max_length=255, blank=True) forms.py from django import forms class DocumentForm(forms.Form): docfile = forms.FileField( label='Select a file', ) description = forms.CharField(max_length=255) price = forms.IntegerField() emailId = forms.CharField(max_length=255) views.py from django.template import RequestContext from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.shortcuts import render from django.shortcuts import render_to_response from myapp.models import Document from myapp.forms import DocumentForm def list(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile = request.FILES['docfile']) newdoc.save() return HttpResponseRedirect(reverse('list')) else: form = DocumentForm() # A empty, unbound form documents = Document.objects.all() return render(request,'myapp/list.html',{'documents': documents, 'form': form} ) def index(request): return render_to_response('myapp/index1.html') list.html {% load staticfiles %} {% load static %} <meta charset="utf-8"> <title>Recent Uploads</title> <form action="{% url "list" %}" method="post" enctype="multipart/form-data"> {% csrf_token … -
python requests fails an https request if coming from an https connection
I'm trying to get a saml connection working for an internal website. Its using django/gunicorn behind nginx using https. In my django code i need to make a request to the endpoint to get the initial metadata to continue. The code is a simple get request to an https:// url and i do this with the requests lib. However, i get an error about max_retries/connection refused: HTTPSConnectionPool(host='server.com', port=443): Max retries exceeded with url: /foo/metadata (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x42bab10>: Failed to establish a new connection: [Errno 111] Connection refused',)) However, when i try making the same request on the shell from the internal server (the one getting the error), the request goes through just fine. I'm having trouble locating the cause of the problem based on the error it gives me. Thanks -
Django- CSRF and POSTing an Html form
In a Django view, I'm placing an Html form (actual string with some Html, from my DB) into an Html template, with a tag: {{ injected_form|safe }}. This succeeds in showing the form, but I've got an issue POSTing it: Forbidden (...) CSRF token missing or incorrect. (Which I know is appropriate Django behaviour, as I have no CSRF token tag/field inside the form itself. Btw the reason for the custom Html form strings in the DB is that they can be produced by the actual user) A solution I could implement is TheBronx's answer to a question here. This seems to be a case where just doing <form method="post"> {% csrf_token %} ...... </form> is not possible! Are there solutions for this issue? I've figured out how to handle/receive POSTs without a related Django model, but I didn't foresee this CSRF problem submitting them :( Any help would be greatly appreciated -
How Can I Add an E-Commerce System to my Website? [on hold]
I am using Python Django to create a dynamic webpage/web-app and have finished completing the overall design for the site. The one thing that I have left to do is implement an E-Commerce system into my website and have not found any place online that can give me a tutorial for how this can be accomplished. My goal is simple: on my "Services" page, where I have laid out all of my company's services, I would like for there to be a way that I can collect payments for the individual products and services that our company provides. I've heard of things such as WooCommerce and other shopping cart apps of the like; however, If I were to purchase WooCommerce's services to use as a shopping cart app, how do I install this app within my website to use freely such as have my "Purchase" buttons lead the customer to a popup or page that receives payment information? Thank you in advance. -
edit a post in django
I am beginner in django. In the following there is a function for edit a post. I don't know what these two lines do. id = eval("request." + request.method + "['id']") post = Post.objects(id=id)[0] def update(request): id = eval("request." + request.method + "['id']") post = Post.objects(id=id)[0] if request.method == 'POST': # update field values and save to mongo post.title = request.POST['title'] post.last_update = datetime.datetime.now() post.content = request.POST['content'] post.save() template = 'index.html' params = {'Posts': Post.objects} elif request.method == 'GET': template = 'update.html' params = {'post':post} return render_to_response(template, params, context_instance=RequestContext(request)) -
Print a stack trace to stdout on errors in Django while using IIS
I have my Django Web application already mounted in IIS version 10 and I am able to see some views but I am unable to see other views working because I am getting the following error in my browser's console when I do my AJAX request: GET http://10.51.112.24:89/statistics/chart-data3 500 (Internal Server Error) I am searching for a snippet of a logging configuration to get Django or IIS to just output a stack trace when it encounters an error during a request. This code is specifically for local debugging and mainly when I do AJAX GET/POST requests. So far, I have enabled the following logging configurations in my settings.py file but they are not enough to trace down this error: DEBUG = True DEBUG_PROPAGATE_EXCEPTIONS = True Any tool or code snippet that can help me to troubleshoot better this problem besides the web browser console from Chrome is welcome. -
Create a array from dynamic number of 'select' option values and send the array via post request to django backend
I have no code to show,because i have no idea how to do this. Is there a way to select multiple values from a select and store it into an array? Also the value of the option selected should be displayed on the page dynamically. Then the array with the values of the selected options should be POST to django backend? note that the values send to django should be used to get details from database. Please shed some light on this -
Django Admin: class media pass an object to javascript file
I need to pass an object to the javascript file def user(admin.ModelAdmin): list_display('name', 'dob') js = { 'all': ( '/path_to_javascript' ) } def get_list_x(): return { foo: 1, bar: 1 } I need to pass the object that the function get_list_x returns to the javascript file. -
Creating Django Model class that creates new records from parsing text from another model class automatically
I'm using django-mailbox to store incoming emails from an imap account. I see that it's working properly and email message objects are being stored. I need to parse client info from these emails that will be stored and viewable in my lead management interface. I created another model class that has all the fields I need to store - names, email, a url, and dates all parsed from the body of the received email. What I'd love to do is have each new message automatically parse the text and create this new object whenever a message is received. I learned here that I'll just use regex for parsing the text. The question is, where should these instructions reside? I'm guessing within the models.py of the django-mailbox app? What would that look like? Thank you! -
Auto-login after social signup
I'm using django-allauth to manage my local and social (Facebook and Google) user signup. After social sign-up user is asked to enter desired login and e-mail, but after that he's not logged in automatically. Is it possible to change this behaviour? -
Django view not getting post param
I know its basic but I got stuckl because of it I internet did not help me. This is snippet of my django class based view (django 1.7) def post(self, request,*args, **kwargs): context = RequestContext(request, {}) print request.POST print request.POST['search_text'] In html <form method="post" action="{% url 'storage_place' %}">{% csrf_token %} <div class="container"> <div class="row"> <div class="col-md-4"> <div class="form-group"> <input type="text" class="form-control" id="search_text" name="search_text " placeholder="Key words..."> </div> </div> <div class="col-md-3"> <div class="s_btngroup"> <div class="col-md-6 col-sm-4 col-xs-5"> <input type="submit" class="btn ft_default-btn-red ft_primary-btn-mini" value="Search" /> </div> </div> </div> </div> </div> </form> When I do print request.POST It is printing QueryDict: {u'csrfmiddlewaretoken': [u'GInHZCd4UK8oWjs2txgppCNEof3VC8zy'], u'search_text ': [u'defrghj']} But in very next line when I do print request.POST['search_text'] I am getting multivalue dict error. Please tell me what would be the reason for this. -
Django - Adding {% url %} in template with slug
I am trying to create the URL in order to access the EDIT and DELETE views directly from the post detail instead of typing it in the browser. I am having trouble finding the right url pattern and template {% url %} code since there is a slug. posts.urls urlpatterns = [ url(r'^$', post_list, name='list'), url(r'^create/$', post_create), url(r'^(?P<slug>[\w-]+)/$', post_detail, name='detail'), url(r'^(?P<slug>[\w-]+)/edit/$', post_update, name='update'), url(r'^(?P<slug>[\w-]+)/delete/$', post_delete, name='delete'), post_detail.html {% block content %} <div class='col-sm-6 col-sm-offset-3'> {% if instance.image %} <img src='{{ instance.image.url }}' class='img-responsive' /> {% endif %} <h1> {{ title }} <small> {% if instance.draft %} <span style='color:red;'>Draft</span> {% endif %}{{ instance.publish }} <div class=''> <a href="{% url 'update' %}"> Edit </a> | <a href="{% url 'delete' %}"> Delete</a> </div> </small> </h1> -
How to pass context objects as Django url template tag arguments
In my django project, I have two model classes - Category & Action. Category is the ForeignKey of Action (all Actions fall under a Category). Within my django templates, I'd like to be able to pass a context object into a {% url %} tag that accepts a string containing the name of a Category as an argument. So in a perfect world my django template would have a line like: <form action="{% url 'actions' {{ category }} %}"> And when submitted, Django would follow the form to a urlpattern like: url(r'^(?P<timespan>\w+)', views.actions, name='actions'), But unfortunately it doesn't look like I'm able to nest template filters into template tags. What's an alternate way I can reference the ForeignKey of a Django object within a url tag? Or perhaps a different way to structure my code? -
losing fields during validation - nested serializer create()
I don't understand why specific fields are being dropped within validated_data. I have the following serializers within Django REST framework: serializers.py: class ClassificationLabelDetailSerializer(serializers.ModelSerializer): class Meta: model = ClassificationLabel fields = ('displayName', 'helpText', 'identifier', 'backgroundColour', 'foregroundColour', 'comment', 'description', 'lastChanged', 'revision') read_only_fields = ('identifier', 'lastChanged', 'revision',) class PolicySerializer(serializers.ModelSerializer): labels = ClassificationLabelDetailSerializer(many=True) class Meta: model = Policy fields = ('displayName', 'identifier', 'labels', 'lastChanged', 'description', 'comment') read_only_fields = ('identifier', 'lastChanged',) def create(self,validated_data): labelData = validated_data.pop('labels') thisPolicy = Policy.objects.create(**validated_data) for label in labelData: for k, v in label.items(): print(k, v) thisLabel = ClassificationLabel.objects.get(identifier=label.identifier)#insert organisational filter here PolicyMemberClassificationLabel.objects.create(policy=thisPolicy, label=thisLabel, order=index) return thisPolicy when sending the following payload it seems to be dropping the identifier, lastChanged and revision fields from the nested representation within validated_data. { "labels": [ { "displayName": "Test name", "helpText": "Wayfarers sartorial authentic, small batch readymade disrupt coloring book. Wayfarers sartorial authentic, small batch readymade disrupt col", "identifier": "fa27e9bd-5007-4874-b10c-46b63c7c8a86", "backgroundColour": "#808900", "foregroundColour": "#000000", "comment": "Wayfarers sartorial authentic, small batch readymade disrupt coloring book.", "description": "Wayfarers sartorial authentic, small batch readymade disrupt coloring book.", "lastChanged": "2017-07-03T09:26:20.450681Z", "revision": 2 }, { "displayName": "Test name 1", "helpText": "Wayfarers sartorial authentic, small batch readymade disrupt coloring book.", "identifier": "29c968dd-8b83-4374-962d-32b9ef527e1b", "backgroundColour": "#9f0500", "foregroundColour": "#FFFFFF", "comment": "Wayfarers sartorial authentic, small … -
After installing jinja2 TemplateDoesNotExist at /admin/
I have installed jinja2 and after that 'DIRS' stopped working(I have to include them by hand). Changing 'APP_DIRS' doesn`t help templates look like that: TEMPLATES = [ { 'BACKEND': 'django.template.backends.jinja2.Jinja2', 'APP_DIRS': False, 'DIRS': ['main/templates', 'shop/templates'], 'OPTIONS': { 'environment': 'django_test.create_jinjia_env.environment', 'autoescape': True, 'auto_reload': DEBUG, 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] If don`t include templates into DIRS it throws the same error Didn`t find the questions like that. Thanks in advance! -
Specialized filtering by FK in Django
I am building an app to track production in a facility. I have an model representing inputs and a model representing a process, with the process model having a FK to the input model. def Inputs(models.Model): description = models.CharField(max_length=30) date = models.DateField() in_stock = models.BooleanField() def Process(models.Model): date = models.DateField() input_item = models.ForeignKey("Inputs") I want to be able to filter the list of inputs that show up in the admin form of the process model. That I already figured out how to do. (Found in Django Docs); class ProcessAdmin(admin.ModelAdmin): def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "input_items": kwargs["queryset"] = Inputs.objects.filter(in_stock=True) return super(ProcessAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) The problem is as follows; I want to filter the available models based on what inputs are currently in stock, but I also want to be able to access older records which record items which are no longer in stock. The current setup will not show those items when I try to access that old record. -
Celery with django (gunicorn) and supervisor - how to give a unique name to each worker
I've got 2 applications that start their own pool of workers. So at first I thought that each pool should have a unique name only. But I realise that there are still conflict between them. For example sometimes the first pool of workers will receive a task and the error will be written by workers of the other pool. Or if an other task arrive before the first one finished, it might not execute. This is how my supervisor.conf looks like: [program:celery-worker] environment=DISPLAY=":1001",DJANGO_SETTINGS_MODULE=victoria.settings.production directory = /home/victoria/current command = /home/victoria/virtualenv/bin/celery -A victoria worker -l info --hostname=worker1@myhost stdout_logfile = /home/victoria/celery-victoria-worker.log stderr_logfile = /home/victoria/celery-worker.log loglevel=warn [program:api-worker] environment = DJANGO_SETTINGS_MODULE=settings.live user = victoria directory = /home/victoria/webapps/citysail/src command = /home/victoria/webapps/citysail/.venv/bin/celery -A celery_app worker -l info -n api-worker --beat stdout_logfile = /home/victoria/api-worker.log loglevel = info Do you have an idea how to generate a unique name for each worker? Thanks!