Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to avoid duplication in filtering a field in a medium table (n to n relation)?
Extending my previous question on stack-overflow. I have four tables: A <--- Relation ---> B ---> Category (So the relation between A and B is n to n, where the relation between B and Category is n to 1) Relation stores 'Intensity' of A in B. I need to calculate the intensity of A in each Category and find the Maximum result. It is achievable using: A.objects.values( 'id', 'Relation_set__Intensity' ).annotate( AcIntensity=Sum(F('Relation_set__Intensity')) ).aggregate( Max(F('AcIntensity')) )['AcIntensity__max'] Now I need to filter the intensities based on some fields in B beforhand: A.objects.values( 'id', 'Relation_set__Intensity' ).filter( Relation_set__B__BType=type_filter ).annotate( AcIntensity=Sum(F('Relation_set__Intensity')) ).aggregate( Max(F('AcIntensity')) )['AcIntensity__max'] However I need to avoid duplication resulted due to table join which messes the calculation up.(beside those field to define filtration, I do not need any fields in B) Is there a way to achieve this using Django ORM? -
Django forms fixtures
In creating a project where you can view your sports teams upcoming fixtures, how do I create a form where the user can create a new fixture form where the "home team" field is only a choice of teams they are in -
How to fix Django All-auth 'SimpleLazyObject'' HTTP 500 error?
How can I fix these terminal errors in my Django All-Auth project? I tried to put @login_required above all my functions in the views.py file and tried to use request.user. TypeError: int() argument must be a string or a number, not 'SimpleLazyObject' [Feb/2018 07:16:20] "POST /join/1 HTTP/1.1" 500 117691 int() argument must be a string or a number, not 'SimpleLazyObject' Join function in views.py: def join(request, destination_id): if request.method == "GET": messages.error(request,"What?") return redirect('/') joiner= Destination.objects.join(request.user, destination_id) print 80 * ('*'), joiner if 'errors' in joiner: messages.error(request, joiner['errors']) return redirect('/travel') Join function in models.py: def join(self, id, destination_id): if len(Destination.objects.filter(id=destination_id).filter(travelers__id=id))>0: return {'errors':'You already Joined this'} else: joiner=User.objects.get(id=id) plan=self.get(id= destination_id) plan.travelers.add(joiner) return {} -
send_mass_mail display link as plain text
I use send_mass_mail and add to the message a link I get strange behavior: Some people will see the link as plain text other as link and some as half link half text, the link works when copy paste in the browser Any suggestion how to fix it, it’s a big problem for me sending a link that doesn’t work? for example: -
passing arguments into the reverse in get_success_url will return a list
I try passing an arg into the reverse function, but django reads the argument as a list of individual letters. For example, if I override it like this: def get_success_url(self, **kwargs): return reverse('profile:detail', args=self.kwargs['username']) if the username on the detail page was "peter", I'll receive an error that says: Reverse for 'detail' with arguments '('p', 'e', 't', 'e', 'r')' not found. 1 pattern(s) tried: ['profile/(?P<username>[\\w.@+-]+)/$'] How do I override it while passing an argument? -
Setting up Redistogo with Django app on heroku
I am New to Redistogo: I have built my project 100% working with Heroku. I wanted to run few operations on Django Models (Database transactions) after the user input. Doing these operations takes a bit time and so I decided to run it through a message broker, message queue. My first preference was using Celery for this but I could not install Celery as requirement on Heroku. It did not identify "Celery-server" as one of my requirement and the push failed. So as an alternate I started using RedisToGo which is avaialable as an add on to Heroku. I was able to start the worker and even the messages were being queued to Redistogo, but the jobs were moved to Failed queue. Please find the trace logs below. 2018-02-12T06:02:19.675113+00:00 app[worker.1]: Traceback (most recent call last): 2018-02-12T06:02:19.675115+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/rq/worker.py", line 789, in perform_job 2018-02-12T06:02:19.675116+00:00 app[worker.1]: rv = job.perform() 2018-02-12T06:02:19.675118+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/rq/job.py", line 573, in perform 2018-02-12T06:02:19.675119+00:00 app[worker.1]: self._result = self._execute() 2018-02-12T06:02:19.675121+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/rq/job.py", line 579, in _execute 2018-02-12T06:02:19.675123+00:00 app[worker.1]: return self.func(*self.args, **self.kwargs) 2018-02-12T06:02:19.675124+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/rq/job.py", line 206, in func 2018-02-12T06:02:19.675126+00:00 app[worker.1]: return import_attribute(self.func_name) 2018-02-12T06:02:19.675128+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/rq/utils.py", line 152, in import_attribute 2018-02-12T06:02:19.675130+00:00 app[worker.1]: module = importlib.import_module(module_name) 2018-02-12T06:02:19.675131+00:00 … -
Pycharm doesn't recognize .min.css file (Unresolved template reference) (Django)
I'm using Django with Pycharm. I started to use Pycharm Professional today, and Pycharm doesn't recognize my bootstrap.min.css file. <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}"> Errors I actually have that file in my project folder, but It doesn't appear in Pycharm file tree. my project folder pycharm file tree Of course, I've set the static_dir, staticfiles_dirs, and static_root. django static settings This never happend in Pycharm educational version. -
Javascript variable passed to html textbox but not to Django form
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script> function dropfunc(){ var s = document.getElementsByName('parameters')[0]; var text = s.options[s.selectedIndex].text; document.getElementById("mytext").value = text; document.getElementById("distance").value = text; } </script> <form action="/summarize_text/" method="post" enctype="multipart/form-data"> {% csrf_token %} <p><b> Text Summarizer</p></b> <select name = "parameters"> <option>Sentence1</option> <option>Sentence2</option> <option>Sentence3</option> <option>Sentence4</option> </select> <input type = "button" onclick = "dropfunc()" value = "Submit"> <input type="text" id="mytext"> <div class="fieldWrapper"> <label id="distance">Sentence</label> {{form.text_data}} </div> </form> </body> </html> In this code the textbox mytext is responsive to changes in the dropdown but the dropfunc() should make changes in the django form variable distance as well. Please suggest what I am doing wrong. -
Separating Business Workflow from Django Application
I've got a Django App where I need to follow different workflow for different inputs. I receive an input parameter with the data payload over the POST endpoint. Based on the input, I need to fire different functions, process the data accordingly and finally save it in the data store. One option is to write if-else, however writing if-else is difficult in maintaining as the code grows. For eg:- If input1, then function1(), process1(), save1() elif input2, then function2(), process2(), save2() I've looked into Intellect, django-viewflow and many other business-rule libraries, but not sure about the recommended way of doing it. -
Linux Apache Django video static file issue
Ubuntu 16.04, Apache, python 3.6 with django. My view is serving up the path of a static video file to my template. It was working fine running the manage.py dev server. It was not working properly on the apache server. I reloaded apache but still get: "No video with supported format and MIME type found" message in Firefox. Apache didn't have the full path, just a relative path from my django app. So I passed the full path to the template. I get the same error, dev and apache servers. I grabbed the HTML out of the template and it works fine; the video played. www-data has rwx all the way up to the file and the directories. Not sure what is going on. Any help is appreciated. -
Best way to create Slack bot responses using Django REST API
I have a simple piece of code that uses the EventsAPI for Slack, and will recognize certain words or phrases and give the user a response: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from django.conf import settings from slackclient import SlackClient SLACK_VERIFICATION_TOKEN = getattr(settings, 'SLACK_VERIFICATION_TOKEN', None) SLACK_BOT_USER_TOKEN = getattr(settings, 'SLACK_BOT_USER_TOKEN', None) Client = SlackClient(SLACK_BOT_USER_TOKEN) # Create your views here. class Events(APIView): def post(self, request, *args, **kwargs): slack_message = request.data #verify token if slack_message.get('token') != SLACK_VERIFICATION_TOKEN: return Response(status=status.HTTP_403_FORBIDDEN) #checking for url verification if slack_message.get('type') == 'url_verification': return Response(data=slack_message, status=status.HTTP_200_OK) #send a greeting to the bot if 'event' in slack_message: #process message if event data is contained in it event_message = slack_message.get('event') #ignore bot's own message if event_message.get('subtype') == 'bot_message': return Response(status=status.HTTP_200_OK) #handle the message by parsing the JSON data user = event_message.get('user') text = event_message.get('text') channel = event_message.get('channel') bot_text = 'Hi <@{}> :wave:'.format(user) #finally use the slack api to post the message with chat.postMessage if 'hello' in text.lower(): Client.api_call(method='chat.postMessage', channel=channel, text=bot_text) return Response(status=status.HTTP_200_OK) return Response(status=status.HTTP_200_OK) Obviously I want a much more robust database of keywords. But is the best way to do this … -
Django inspectdb generates TextField for MySQL mediumblob
I have a legacy MySQL database. I decided to generate models from the database tables using 'inspectdb'. I have some images stored as mediumblob fields in a table. I see that Django generated those field as following: origimage = models.TextField(db_column='OrigImage') # Field name made lowercase. Django documentaions says If inspectdb cannot map a column’s type to a model field type, it’ll use TextField and will insert the Python comment 'This field type is a guess.' next to the field in the generated model. I do not see the 'This field type is a guess'. Does not appear like Django treated this as a guess. Does Django translate mediumblob to TextField? I would need to see this as a file upload field in the Forms. Am I to change this to an ImageField for the field to be rendered correctly? -
A better way to order ForeignKey and M2M relations using drag-and-drop libraries like Sortable.js, muuri, etc
As the title says I hacked this together a bit ago as an initial run of handling updating models which are a ForeignKey relation to a base model (creating a related set) that can be ordered by the front-end / user using drag-and-drop libraries. But, this is hackish and can be a lot better I feel. So, the question is: Is there a better / more efficient way using a different schema such as through or method of updating than the below example. Example model layout: class ModelA(models.Model): pass class ModelB(models.Model): order = models.PositiveIntegerField() model_a = models.ForeignKey(ModelA, related_name='items') class Meta: ordering = ['order'] Any time ModelB is added to the items relation set the order is set to be the last. That is, new_instance.order = items.count(). Cool, that let's new items be last as expected. But, on the front-end let's consider drag-and-drop and updating with AJAX requests. Let's say I make a request to a view: update_order with url ^(?P<pk>\d+)/order/(?P<order>\d+)/$ and let's ignore error checking / permissions etcetera. A simplified version of this view is - with pk being a ModelB pk -: Essentially: Partition the set into gte and lt and handle appropriately offsetting lt as [0, order) and … -
Django - Limit the select options of a foreignkey and prevent duplicate objects
I have to create a new object that is related to another models. Model1 (for this model i have to create the new object class ProductStock(models.Model): # Relations product = models.ForeignKey( Product, related_name='product_stock', verbose_name=_('product'), on_delete=CASCADE, ) warehouse = models.ForeignKey( Warehouse, default=1, verbose_name=_('warehouse'), on_delete=CASCADE, ) # Attributes - Mandatory quantity = models.IntegerField( default=0, verbose_name=_('quantity'), ) and I have the Products Model and the Warehouses Model. Well, I have to create an object to define the stock of the product in one of the warehouses, but i only can have 1 object for each product and Warehouse. The problem here is this. For a Product i only can have one object in this model for each warehouse. And if i create 2 items with the same warehouse i have 2 objects with the same product and warehouse and i can't have that result. I can think of 2 ways to prevent it, one (the easy one) is in the model save method check if exist a object with that product and warehouse and raise the error. But I think is better for the User Experience try to limit the select options of warehouses in the form. But i don't know how i … -
How can I convert string to list
I use python djanggo for web development. I got an list from input forms, and I saved the list in my djanggo text fields. Then, I brought it from database and print it. I save the list like that [{'question': 'dsasda', 'type': 'ShortAns',},{'question': 'dsads', 'type': 'MultipleCho','answer': ['asdadsasd',]},] And then, I brought it in view like that survey_list = json.loads(survey.questions) I showed it in template, so {{ survey_list.0 }} But it print out only [ how can I solve this problem -
including bootstrap in django
i am working on a project on django and i want to include bootstrap to it to make it a responsive website.my bootstrap css works perfectly fine each time i include it<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> but when i try to do the same thing for js in bootstrap,it doesn't seem to work,here's my js<script src="https://ajax.gogglepis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="{% static 'js/bootstrap.min.js' %}"></script> -
How do you add a pre-existing database to psql?
I am using psql in my production server that houses my Django application. I am trying to create a database in psql that already exists. I have the host name, username, password, port, all that good stuff, but after reading psql's documentation it seems that there is no way to add in a prexisting database. -
cryptocurrency payment solution for django-oscar
I have an e-commerce site running on django-oscar (shop.minable.io). I want to integrate cryptocurrency payments. It doesn't seem like anyone has made a plugin for this. Does Coinbase have any plans to release a plugin for this? If I were to make such a plugin myself, how do I go about selling it to Coinbase? -
'tuple' object has no attribute 'Meta'
I'm working with django-rest and I made a filters.py but it marked me the error of suiguitor to be able to add my filters and API and I checked and I have the code correctly it does not mark me any other error more than the rest help me 'tuple' object has no attribute 'Meta' my code in is the following models.py class AutorizarCaptura(models.Model): folio = models.CharField(max_length=12) un = models.CharField(max_length=12) anio = models.IntegerField() fecha_captura = models.DateField(auto_now_add=True, blank=True) def __str__(self): return "%s" % (self.un) def __unicode__(self): return "%s" % (self.un) filters.py class AutorizarCapturaFilter(filters.FilterSet): un = CharFilter( name="un", lookup_expr="exact" ) anio = CharFilter( name="un", lookup_expr="exact" ) class Meta: model=AutorizarCaptura fields = [ 'un', 'anio' ] serialiazers.py class AutorizarCapturaSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = AutorizarCaptura fields = ( 'id', 'folio', 'un', 'anio', 'fecha_captura', ' ) -
How to load .sql file with manage.py
I have a .sql file from one of my production servers, and am now trying to load it into the database of another. I tried python manage.py loaddata, but its giving me an error CommandError: Problem installing fixture 'social': sql is not a known serialization format. How can I load my data into postgres from a .sql file with manage.py ? -
Accessing additional fields for customized UserCreationForm in Django
I am new to Django and working on my first app after running the official tutorial and reading other articles. I am having problem accessing the additional field that I added for User model. I am not able to figure out the problem, any help/pointers will be much appreciated. Forms.py (I have added the field country in the example code shown below) from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit class RegisterUserForm(UserCreationForm): country = forms.CharField() def __init__(self, *args, **kwargs): super(RegisterUserForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'id-exampleForm' self.helper.form_class = 'blueForms' self.helper.form_method = 'post' self.helper.form_action = '.' self.helper.add_input(Submit('submit', 'Submit')) class Meta: model = User fields = ( 'username', 'first_name', 'last_name', 'email', 'password1', 'password2' ) def save(self, commit=True): user = super(RegisterUserForm,self).save(commit=False) user.country = self.cleaned_data["country"] print user.country if commit: print "saving user" user.save() return user Views.py from django.shortcuts import render from django.views.generic import CreateView from .forms import RegisterUserForm class RegisterUserView(CreateView): form_class = RegisterUserForm template_name = 'accounts/register.html' success_url = '/' Admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from .forms import RegisterUserForm class NewUserAdmin(UserAdmin): add_form = RegisterUserForm admin.site.unregister(User) admin.site.register(User, NewUserAdmin) PROBLEM : In the admin app, … -
How to prevent DRF from escaping my non-ascii characters (UNICODE_JSON is True)
I've tried out a few versions of DRF that are compatible with Django 2.0, and they're escaping my non-ascii characters in my JSON. Here's an example JsonResponse: ["C\u00e2\u0080\u0099est int\u00c3\u00a9ressant ... I'm presently running 3.7.7. As per the encoding docs, I have set: UNICODE_JSON: True (though this is the default anyway) I'm still getting escaped chars, contrary to what the docs indicate. The other parts of my pages (handled by Django) render their accented characters fine, and my postgres client_encoding is 'UTF8'; it's definitely a DRF issue. How can I fix this? -
How do I deploy a Django server running in a docker on Digital Ocean Ngnix
I have never set up a server on digital ocean before and I am trying to set up my django website that runs inside a docker container and have it run on a django ubuntu digital ocean server. Can someone just list me through some basic steps of what needs to be done, I don't know how to have tell the digital ocean server to run my docker container and run the following command: "docker-compose -f dev.yml up". I read that you need to configure the Ngnix document, but i'm still confused. I watched this video: https://youtu.be/Y-CT_l1dnVU. I just cant wrap my head around the big picture I guess of what Ngnix and Gunicorn do and how the docker container is suppose to run on digital ocean. Any help is appreciated! Thanks -
Django Rest API isn't responding with the value of the challenge parameter
Working my way through this tutorial and it has been going mostly well until I try to verify my app with the slack API by submitting a ngrok tunnel link, which is <myID>.nrgok.io/events. I keep receiving 500 error: Your URL didn't respond with the value of the challenge parameter. Why isn't my app responding with the challenge parameter? # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from django.conf import settings from slackclient import SlackClient SLACK_VERIFICATION_TOKEN = getattr(settings, 'SLACK_VERIFICATION_TOKEN', None) SLACK_BOT_USER_TOKEN = getattr(settings, 'SLACK_BOT_USER_TOKEN', None) Client = SlackClient(SLACK_BOT_USER_TOKEN) # Create your views here. class Events(APIView): def post(self, request, *args, **kwargs): slack_message = request.data #verify token if slack_message.get('token') != SLACK_VERIFICATION_TOKEN: return Response(status=status.HTTP_403_FORBIDDEN) #checking for url verification if slack_message.get('type') == 'url_verification': return Response(data=slack_message, status=status.HTTP_200_OK) #send a greeting to the bot if 'event' in slack_message: #process message if event data is contained in it event_message = slack_message.get('event') #ignore bot's own message if event_message.get('subtype') == 'bot_message': return Response(status=status.HTTP_200_OK) #handle the message by parsing the JSON data user = event_message.get('user') text = event_message.get('text') channel = event_message.get('channel') bot_text = 'Hi <@{}> :wave:'.format(user) #finally use the slack api to post the … -
Django AWS RDS settings - EB deployment
I have a Django application on AWS Elastic Beanstalk. I am trying to connect my application to an external RDS database (mySQL). I have followed this tutorial to get this kind of setting: if 'RDS_DB_NAME' in os.environ: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'myName', 'USER': 'myUser', 'PASSWORD': 'myPassword', 'HOST': 'localhost', 'PORT': '5432', } } Everything works fine on AWS but when I redeploy my application I lose all the data in my database, e.g. all of the users's sign-ups are gone. That means the deployment overwrite the previous database and my application is not connected to an external RDS where data should be preserved. Any idea about what I am doing wrong? Thank you very much for your help ! Regards