Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to write this query in django queryset? Find all topic_name for gaurd name = Algebra?
Defined Models Are... Gaurd(name, category) Chapter(Gaurd, Chapter, rates) and Topic(chapter, topic_name, level) These three are connected via foreign key with each other. -
django-filter and DRF: AND clause in a lookupfield
This question expands on this one. Suppose my models are class Car(models.Model): images = models.ManyToManyField(Image) class Image(models.Model): path = models.CharField() type = models.CharField() and my filter class is class CarFilter(django_filters.FilterSet): having_image = django_filters.Filter(name="images", lookup_type='in') class Meta: model = Car then I can make queries like ?having_image=5 and get all cars that have an image with pk=5. That's fine. But what if I need to return both cars with this image AND also cars with no images at all, in one list? How do I unite two conditions in one django_filters.Filter? -
Django migration from dynamic fields
i' ve the following django model: class Apple(models.Model): text = models.TextField() . I' ve already many records, and i' d like to add a subject field to the model, so it' ll look like: class Apple(models.Model): text = models.TextField() subject = models.CharField(max_length = 128) . In this case i run a makemigrations, but since subject can be empty, i need to set a default value either in the model, or in the migration file. What would be the correct procedure if i' d like to take the subject from the text for the already existing database lines (for instance: text[:64])? My solution would be to create a migration with a default value, run a management commend to update the values, and with a new migration remove the default value for the subject. Is there a better solution, right? What is it? Can i somehow combine / do this in the migration itself? Python: 3.4.5 Django: 1.9.2 . -
Django: Paginating Aggregated query
Imagine I have simple database model like in the django tutorial: class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') Source: https://docs.djangoproject.com/en/1.11/intro/tutorial02/#creating-models I want a result that looks like this Month | Number of Question of this Month 2017-01 | 201 2017-02 | 345 ... | ... How to create the matching QuerySet and how to paginate it? -
Django: Ordering Users in Messaging App
Here's my model, class Message(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") msg_content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) I wants to order the Users based upon who sent a message to "request.user" or to whom "request.user" sent a message most recently! As we see on social networks. How can I do that? -
Django - AttributeError: 'NoneType' object has no attribute 'method'
I noticed that when I use DRF documentation I get error AttributeError: 'NoneType' object has no attribute 'method' and this is associated with this line if self.request.method == 'POST' Any ideas how can I solve it? class UserObject(GenericAPIView): def get_serializer_class(self, *args, **kwargs): if self.request.method == 'POST': return ObjectPostSerializer return ObjectSerializer -
Django MQTT use shell not working
My problem is when I use python manage.py shell and I type my code line by line, then It will working fine(receive messages and print it). But when I use python manage.py shell < my.py It will not working( receive message and print it) Is any problem with threads? here is my script.py code: import os import django os.environ["DJANGO_SETTINGS_MODULE"] = 'myprojects.settings' django.setup() import paho.mqtt.client as paho_mqtt from mqtt.mqtt import on_connect, on_message username = "****" password = "****" client = paho_mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.username_pw_set(username=username, password=password) client.connect("********", 1883, 60) client.loop_forever() And here is my function code def on_connect(client, userdata, flags, rc): try: client.subscribe(topic="********") print('subcriptions') except Exception as e: print("connect subscribe error " + str(e)) def on_message(client, userdata, msg): data = msg.payload.decode('utf-8') res_json = json.loads(data) print(res_json) -
How to increase time to end UWSGI connection
Now each of my connections is closed after 60 seconds. I would like to increase this time to 300 seconds. To do this I changed my ini file : [uwsgi] # Django-related settings # the base directory (full path) chdir = /home/root/djangoApp # Django's wsgi file module=djangoApp.wsgi:application # process-related settings # master master = true # maximum number of worker processes processes = 10 # the socket (use the full path to be safe http = 127.0.0.1:8000 # ... with appropriate permissions - may be needed chmod-socket = 664 # clear environment on exit vacuum = true protocol = uwsgi harakiri = 300 http-timeout = 300 But it doesn't work, still the process is killed after 60 seconds. I will be very thankful for help, Thanks -
Django: Messaging App
Here's my model, class Message(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") msg_content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) Here i'm trying to order the User based upon who sent a message to "request.user" or to whom "request.user" sent a message most recently! As we see on social networks. Here's what I tried, users = User.objects.filter(Q(sender__receiver=request.user) | Q(receiver__sender=request.user)).annotate(Max('receiver')).order_by('-receiver__max') This code is working fine only if request.user sent someone a message (it's shows the name of that user at top) but if someone sent request.user a message it's not showing their name at the top. How can I do that? -
Call stored procedure
I want to know how can I call a stored procedure from oracle using django. I must insert in multiple tables and I already have a procedure that does that. How should I call this proc? This is how I am trying now: c = connection.connection.cursor() c.callproc('PKG_SOMETHING.pr_insert',(i_param, o_param1, o_param2) ) c.close() return o_param1 + o_param2 -
DRF - Filter queryset in PrimaryKeyRelatedField
I've the following models: class ModelX(models.Model): STATUS_CHOICES = ( (0, 'ABC'), (1, 'DEF'), ) status = models.IntegerField(choices=STATUS_CHOICES) user = models.ForeignKey(Users) class Users(models.Model): phone_number = models.Charfield() and the serializer for ModelX is : class ModelXSerializer(serializers.ModelSerializer): phone_number = serializers.PrimaryKeyRelatedField( source='user', queryset=Users.objects.get(phone_number=phone_number)) class Meta: model = ModelX fields = ('phone_number',) In the request for creating the ModelX record, I get phone_number instead of the user_id. Now, I've to fire a filter query in order get the user instance. How do I do that, ie Users.objects.get(phone_number=phone_number) Also, when creating a record, the status field will always be 0. The client wont post the status parameter in the body. Its the internal logic. Is there a way in serializers that can set the status field to 0 automatically. Please dont recommend to set this field as default=0 in models. There's some logic behind this. This is just a shorter version of the problem statement. -
Random query is hitting PostgreSQL RDS instance
We have a django application hosted on AWS Elastic Beanstalk, which is using PostgreSQL RDS as a database. Since yesterday, we found that our RDS storage shows full-storage message. When we checked the logs are filling up and taking most of the space. The logs shows some random query is hitting the DB and causing error. 2017-10-30 06:59:59 UTC:172.31.0.218(48038):MyPostgreSQLDB@ebdb:[16817]:STATEMENT: INSERT INTO "auth_user" ("password", "last_login", "is_superuser", "username", "first_name", "last_name", "email", "is_staff", "is_active", "date_joined") VALUES ('pbkdf2_sha256$30000$L21goli52Bdt$CrFNDOGuwszHC3wkKvoVee1O8ey/V/NdMt9CaG53mCk=', NULL, false, 'dk12345678910111213141516171819202122232425', 'd', 'K', '', false, true, '2017-10-30T06:59:59.550627+00:00'::timestamptz) RETURNING "auth_user"."id" 2017-10-30 07:00:00 UTC:172.31.6.238(47206):MyPostgreSQLDB@ebdb:[22437]:ERROR: value too long for type character varying(150) 2017-10-30 07:00:00 UTC:172.31.6.238(47206):MyPostgreSQLDB@ebdb:[22437]:STATEMENT: INSERT INTO "auth_user" ("password", "last_login", "is_superuser", "username", "first_name", "last_name", "email", "is_staff", "is_active", "date_joined") VALUES ('pbkdf2_sha256$30000$rtHpPn996XzO$H2RS/H5RYHC12MxjnRIRK1St21VQS8/6Bd/Hnc3H0Jc=', NULL, false, 'deepak kumar k12345678910111213141516171819202122232425262728293031', 'Deepak Kumar ', 'k', '', false, true, '2017-10-30T06:59:58.751020+00:00'::timestamptz) RETURNING "auth_user"."id" 2017-10-30 07:00:00 UTC:172.31.26.180(52740):MyPostgreSQLDB@ebdb:[23882]:ERROR: value too long for type character varying(150) 2017-10-30 07:00:00 UTC:172.31.26.180(52740):MyPostgreSQLDB@ebdb:[23882]:STATEMENT: INSERT INTO "auth_user" ("password", "last_login", "is_superuser", "username", "first_name", "last_name", "email", "is_staff", "is_active", "date_joined") VALUES ('pbkdf2_sha256$30000$Ve4JkxutDfyC$lB9A+bzEvQSJYamlhXscU/cWfDHtMSHaMU45kKcyxsM=', NULL, false, 'ashokkumar1234567891011121314151617181920212223242526272829303132333435', 'ASHOK', 'Kumar', '', false, true, '2017-10-30T07:00:00.208427+00:00'::timestamptz) RETURNING "auth_user"."id" 2017-10-30 07:00:00 UTC:172.31.26.180(52938):MyPostgreSQLDB@ebdb:[26159]:ERROR: value too long for type character varying(150) We are not able to trace who is hitting this random query? How can we locate the culprit application or who is trying … -
Django Reset API not working on Docker
I am new to Docker, before docker I work on heroku, and these Django Rest APIs run perfectly on local server and heroku, but when i deploy these APIs on docker they sending me 400 Bad Request error, I don't know what the issue is, can somebody give me a hint what went wrong on docker. -
How to stop page reloading for components using react-router-dom with django
I'm trying to implement react-router-dom in a site build using react, redux and django as back end. My Problem is when we click on links created by react-router-dom, It loads right component but reloads the whole page due to which the redux state is lost. I don't want to serve all my requests to server, requests should be handled by react-router-dom without page reload. So my django urls.py looks like from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView from django.conf import settings from food import views urlpatterns = [ url(r'^admin/', admin.site.urls), # url(r'^api/', include('hodapp.urls')), url(r'^api/items/', views.ItemList.as_view()), url(r'^api/categories/', views.CategoryList.as_view()), url(r'^', TemplateView.as_view(template_name='index.html')), ] Every request other than admin and api will serve index.html which looks like. {% load render_bundle from webpack_loader %} <!DOCTYPE html> <html lang="en"> <head> <!-- Meta --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> {% load static %} <!-- CSS Theme --> <link id="theme" rel="stylesheet" href="{% static '/css/themes/theme-beige.min.css' %}" /> </head> <body> <div id="container"></div> {% render_bundle 'main' %} </body> </html> Webpack serves index.jsx which looks like: import React from 'react'; import { render } from 'react-dom'; import App from './components/App'; import { BrowserRouter as Router} from 'react-router-dom'; const BrowserApp = () … -
How to handle exceptions in a Django database setting?
I have a Django application which gives the operational error: django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '172.16.1.38' (111)") When I am giving the wrong port number or IP address in database configuration of setting.py file. For example: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': "movement", 'HOST': "172.16.1.38", 'PORT': 3306, 'USER': "adc", 'PASSWORD': "abcde", } } above is the correct configuration of the database access but if I mess with any of the value from PORT, HOST or USER, I am getting the operation error. So, I wanted to know, is there any way to show a message instead of this error? or how can I handle this exception? -
python - read file add 1 to the data and write in file using data frame
It is my input file. comma separated values. It should read the file, convert that into panda dataframe. If any of the values in a row is 1, then all other columns in the same row should be 1. Input file(filter.txt) col1 2 3 4 5 6 abc, 0 0, 0, 0, 0 def, 0, 0, 1, , abc, 0, 1, , , def, 0, 0, 0, 1, xyz, , , , , Expected output step 2 abc, 0 0, 0, 0, 0 def, 0, 0, 1, 1, 1 abc, 0, 1, 1, 1, 1 def, 0, 0, 0, 1, 1 xyz, 1, 1, 1, 1, 1 After that it should group by column 0 and sum the values. So, far my code is, import pandas as pd data = pd.read_csv('Desktop/filter.txt', sep=",", header=None) my_df = pd.DataFrame(data) #what logic i should apply here? summary = my_df.groupby([0]).sum() print summary Expected output step 2 abc, 0, 1, 1, 1, 1 def, 0, 0, 1, 2, 2 xyz, 1, 1, 1, 1, 1 Any help would be appreciated. Thanks. -
Django Rest Framework JWT - Custom Payload with Extend User
I have a Extended User with sample serializers (Profile is Extend User, not Abstract User) { "id": 3, "url": "http://localhost:8000/api/v1/users/demo/", "username": "demo", "first_name": "First", "last_name": "Demo", "profile": { "gender": null, "location": "Sa Pa", "date_of_birth": null, "job_title": null, "phone_number": null, "fax_number": "", "website": "", "intro": "", "bio": "", "interested_in": null, "languages": null, "quotes": null, "nickname": null } } How can I custom payload with all above fields and get it with axios? Now it just get payload: authUser:Object email:"test@gmail.com" exp:1509183691 user_id:1 username:"First Demo" token:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImxlY29uZ3RvYW4iLCJ1c2VyX2lkIjoxLCJlbWFpbCI6ImRyYWZ0bGlnb25ncXVhbjdAZ21haWwuY29tIiwiZXhwIjoxNTA5MTgzNjkxfQ.KSEp-7g-SGDbqfspedNwkT1rABFi0UQ45yKDJDTX2zA" I followed with this link: #145 but isn't work Please help me! -
Byte Order Mark (ÿþ) preventing deployment to Heroku
I've been trying to learn Django, and I've been running into some trouble deploying to Heroku. When I try running git push heroku master, I get the following output PS E:\My\Git\Directory> git push heroku master Counting objects: 31, done. Delta compression using up to 8 threads. Compressing objects: 100% (26/26), done. Writing objects: 100% (31/31), 6.71 KiB | 0 bytes/s, done. Total 31 (delta 2), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! The latest version of Python 3 is python-3.6.2 (you are using ÿþpython-3.6.2, which is unsupported). remote: ! We recommend upgrading by specifying the latest version (python-3.6.2). remote: Learn More: https://devcenter.heroku.com/articles/python- runtimes remote: -----> Installing ÿþpython-3.6.2 remote: ! Requested runtime (ÿþpython-3.6.2) is not available for this stack (heroku-16). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to intense-river-64521. remote: To https://git.heroku.com/intense-river-64521.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/intense-river- 64521.git' Running the site on localhost has no problems. My runtime.txt only contains: python-3.5.2 I assumed the issue … -
Django model save related model
I have three models, Person, Role and Student. Person is related to role with ManyToManyField and Student inherits from Person. The code: class Person(models.Model): #fields class Role(models.Model): ROLE_CHOICES = ( ('AL', 'ALUMNO'), #... more choices ) person = models.ManyToManyField(Person) role = models.CharField( 'Rol', max_length = 2, choices = ROLE_CHOICES ) class Student(Person): # fields def save(self, *args, **kwargs): super(Student, self).save(*args, **kwargs) # what code should I put here? I want to, on saving a Student, automatically save a role for him/her ('AL'). As I understand, I can override the save method, but I'm not sure how exactly do this. Thanks. -
redirect(reverse) -- pass form (field_errors) to template
I unsuccessfuly try to pass form (including the field_errors), if form.is_valid() is not true, to the template with a redirect(reverse). I use two different views (TemplateView and FormView) urls.py urlpattern = [ url(r'^(?P<slug>[0-9]+)/$', SomeView.as_view(), name='detail'), #... ] views.py class Form_View(FormView): # ... if form.is_valid(): #... else: return redirect(reverse('detail', kwargs={'slug': var})) template.html <p>Validation: {{form.non_field_errors}}</p> What i already tried: return redirect(reverse('detail', kwargs={'slug': var})) Works, but form is missing return redirect(reverse('detail', kwargs={'slug': var, 'form': form})) NoReverseMatch return redirect(reverse('detail', kwargs={'slug': var}), {'form': form}) form is empty in template / does not show anything -
Github-flavored markdown in django-markdown-deux
Has anyone figured out how to get django-markdown-deux to correctly render github flavored markdown? -
How to send to django template from dictionaries / tuples in a relational manner?
So I have an alphabet dictionary which has the letter name as the key and an integer as an id for the value. (This is used for the jump to navigation at the top of the page which is hardcoded html) Then I have many named tuples. Each one is for a state. It has the alphabet id state name and state id. Then theres many named tuples for partners. Each has a state id, image url, link, and partner name. The part which I am struggling with is how to display these in the template. I want each state to go in an alphabetical manner, to have a jumpto-nav id, and partners in that state. Greatly appreciate any feedback!!! Thanks. Note: the dictionary/tuples are located in views.py -
django.db.utils.OperationalError: (1054, "Unknown column
An interesting issue. Getting Unknown column exception -- Please find the stack trace I try to get new leads list and responded leads. I merge them. When I merge them there is an exception. After debugging its found that new_leads method has exclude of two fields collection and delivery . If we make it one exclude all is well . I mean dont check the other, if we include both the filters we have an issue. I tried using filter/ exclude etc. but it didnt work. Query Set contains following method def all_leads_related_to_user(self, user): """ User new and past leads Use this queryset for performing lead search. """ new_leads = self.new_leads_for_user(user) responded_leads = self.leads_responded_by_user(user) all_leads = (new_leads | responded_leads).distinct() <= Issue is here. return all_leads def new_leads_for_user(self, user): .... # User's location filter if user.sub_region_excluded_list: sub_region_exclude_list = [10, 12] qs = qs.exclude( Q(collection_point__sub_region_id__in=sub_region_exclude_list) | Q(delivery_point__sub_region_id__in=sub_region_exclude_list)) # <== Make it just one exclude it works. Model class Suburb(models.Model): state = models.ForeignKey(State, blank=False) sub_region = models.ForeignKey(SubRegion, blank=False) postcode = models.CharField(_('postcode'), blank=False, max_length=10) name = models.CharField(_('suburb name'), blank=False, max_length=200) class Load(models.Model): ..... collection_point = models.ForeignKey(Suburb, related_name='collection_point', on_delete=models.SET_NULL, null=True) delivery_point = models.ForeignKey(Suburb, related_name='delivery_point', on_delete=models.SET_NULL, null=True) Stack Trace:- >>> Load.objects.all_leads_related_to_user(User.objects.all()[0]) Load.objects.all_leads_related_to_user(User.objects.all()[0]) Traceback (most recent call … -
How to send message from kafka/spark to websocket?
I'm designing an Analytic platform using kafka as message queue and Django for web app. But I don't know how to build real-time dashboard with data get from kafka. So I don't know something below: 1) Could we get data from kafka and emit to websocket? ( django framework) 2) Could we use spark for this ( store to casandra and get data from kafka and emit to web socket) If you have any ideas or document please share to me. Thanks & Best Regards, jame -
Django on Google App Engine: "Instance names cannot contain the ':' character."
I am following this tutorial to run a Django project on Google AppEngine. I have reached the steps to create a Cloud SQL instance. When I follow these steps I get the following error: $ gcloud sql instances describe django-polls-184415:us-west1:polls ERROR: (gcloud.sql.instances.describe) Instance names cannot contain the ':' character. If you meant to indicate the project for [polls], use only 'polls' for the argument, and either add '--project django-polls-184415:us-west1' to the command line or first run $ gcloud config set project django-polls-184415:us-west1 When I follow the instructions in the error message, I get $ gcloud config set project django-polls-184415:us-west1 Updated property [core/project]. $ gcloud sql instances describe polls ERROR: (gcloud.sql.instances.describe) HTTPError 403: The client is not authorized to make this request. What am I doing wrong? And more importantly how do I do it correctly?