Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploy a Django App Using AWS, but always get 504 Gateway Time-out
I just followed this tutorial (https://www.packtpub.com/books/content/how-deploy-simple-django-app-using-aws) to put my django project to AWS server, using nginx and gunicorn Here's my nginx.conf: server { listen 80; server_name 52.63.229.89; access_log /var/log/nginx-access.log; error_log /var/log/nginx-error.log; root /home/ubuntu/code-query/ELEC3609/ELEC3609; location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; #uwsgi_read_timeout 120; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_connect_timeout 10; proxy_send_timeout 15; proxy_read_timeout 20; } } And my gunicorn is running, but I just get 504 Gateway Time-out on my website. What's happening? -
Can't get POST data from Django (sending it from React)
I'm spending hours to solve this problem. The problem is I can't send POST's body data. I'm getting 500 error from the server. Here is my HTTP request on React Native (I don't think I have a problem here). There might be problem on http body? export const createCloth = (token, hType, clothObject) => async dispatch => { let headers = { 'Authorization': `JWT ${token}`}; if(hType==1) { headers = { 'Authorization': `JWT ${token}`}; } else if (hType==2) { headers = { 'Authorization': `Bearer ${token}`}; } let {image, text, clothType, ... , onlyMe} = clothObject; console.log(text); <- printing ok console.log(bigType); <- printing ok let response = await axios.post(`${ROOT_URL}/clothes/create/`, { text, clothType, ..., onlyMe }, {headers}); console.log(response.data); Here is my part of Backend API. class ClothCreateAPIView(APIView): def post(self, request, format=None): # Create Cloth # self.request.POST.get('user_id') print('--------REQUEST-------') print(request) logged_in_user = self.request.user content = self.request.POST.get('text') cloth_type = self.request.POST.get('clothType') only_me = self.request.POST.get('onlyMe') ... print('----------PRINTING CLOTH CONTENT') print(logged_in_user) <- printing my username (GOOD) print(cloth_type) <- printing None always print(content) <- printing None always At the last two line, why are they always printing None? I'm checking these syntax back and forth more than twenty times. This is so frustrating I tried with self.request.POST.get(~) request.POST.get(~) ?? -
OperationalErrors - no such column django - ForeignKey
I have this field in my model: customer = models.ManyToManyField(Customer) Due to some changes, I realized that I have to change the relationship to this: customer = models.ForeignKey(Customer) I have tried to do the makemigrations app_name and migrate again and again but it still produces the error. I also have tried deleting the existing data of the model in the admin site. -
Why are my tasks not found although they are in the database?
I'm using the library django-background-tasks: https://github.com/arteria/django-background-tasks I'm doing the example in the documentation here: http://django-background-tasks.readthedocs.io/en/latest/ I ran the the task in the shell: from forker.tasks import notify_user notify_user(user.id) And I made sure that it was saved in the database successfully in the table background_task I ran the command: python manage.py process_tasks The process keeps running without finding any task. With some troubleshooting, I found the part of the code that can't find any tasks in background_task/management/commands/process_tasks.py: while (duration <= 0) or (time.time() - start_time) <= duration: if sig_manager.kill_now: # shutting down gracefully break if not self._tasks.run_next_task(queue): # there were no tasks in the queue, let's recover. close_connection() logger.debug('waiting for tasks') time.sleep(sleep) else: # there were some tasks to process, let's check if there is more work to do after a little break. time.sleep(random.uniform(sig_manager.time_to_wait[0], sig_manager.time_to_wait[1])) It always doesn't find tasks in the queue (the second if statement). Any idea why it can't find a next task? I am pretty sure I'm going through the documentation step by step but now I am looking the library code and feeling getting out of track. -
Django + docker + periodic commands
What's the best practices for running periodic/scheduled tasks ( like manage.py custom_command ) when running Django with docker (docker-compose) ? f.e. the most common case - ./manage.py clearsessions Django recommends to run it with cronjobs... But Docker does not recommend adding more then one running service to single container... I guess I can create a docker-compose service from the same image for each command that i need to run - and the command should run infinite loop with a needed sleeps, but that seems overkill doing that for every command that need to be scheduled What's your advice ? -
Django mail sending error when DEBUG is False
I have a Django website with contact form. I need to send email to user and admin. When the DEBUG is False in settings.py the mail was not send. It generates 500 error in console. Can you help me to solve this. -
Error "Section 'Boto' already exists"
I need make new S3 File System (different than existing one). When I'm trying to do it i get Section 'Boto' already exists I understand, that firstly I need to delete previous S3 File System. One question - how can I delete the existing one? -
Should I have a seperate table for each media type
See initially I thought this would be simple but this is killing me right now I have a post model which contains a field (foreign key to media) Media has 3 colums Image, Video, Audio (each related to their own tables) And each of those three tables above has 1 file field (except for image because that holds x and y coordinated too for the tagging purpose) I don't wanna disturb the order of the upload(the size if the field is gonna change in future because I have to store a thumbnail for each file) let's say a user uploaded a picture first and then audio and then a video I wanna display them in the order as they were uploaded but I really don't know how to achieve this Can anyone please help me figure out, what should I do to implement this -
Django internet explorer download page content instead render it
I create a website using django and python tecnologies. When i view it with browser like chrome,safari,firefox ecc ecc all done, but if i open in explorer this appen: in my views.py i have this code: def index(request): context = RequestContext(request) c_form = False try: c_form = request.COOKIES['cform'] except Exception: if request.POST: c_form = foo_email(request) context_list = {'form': c_form} response = render(request, 'base_home.html', context_list, context) if c_form: response.set_cookie('cform', value='1', max_age=None) return response the response variable contain the html strucutre of the page, other browser render it but ie doesn't, why? Thanks in advance -
Mongo query in Django (python) if I use variable as Collection Name?
My MongoDB query in Django App like this, how can i use dynamic variable name for Collection Name mycoll = 'my_collection_name' client = MongoClient() db = client['database_name'] collection = db.mycoll.find({'Return._id': q},{'Return.ReturnData':1,'_id':0}) -
Is there somewhere different between `pk` and `id`?
When I read the source code, I find the function use pk to as keyword to select data: def detail(request, album_id): try: album = Album.objects.filter(pk=album_id) except Album.DoesNotExist: raise Http404("Album does not exist") context = { "album":album, } return render(request, "music/detail.html", context) I am used to use id: album = Album.objects.filter(id=album_id) So, is there somewhere different between them? -
How do I add different users data on my Django backend?
I have a bunch of users on my django backend. Let's say each user has a field 'age'. I would like to add every users age and divide by the number of users to get an average. Would this best be done in a ModelView as a function that makes a call using a While loop (while User.age for example)? -
Iterating through json request with multiple objects - django
I have a django project that I am working on. I have a api request that is returning a json response. With the json reponse that I am getting, there is a list of funding sources and within each funding source is an item that has the name with the object. I want to go though each json item and grab the names from the list of objewcts. how can I do this with the following response. I will also attach the request code that I sent... response: { 'funding-sources':[ { '_links':{ 'self':{ 'href':'https://api-sandbox.dwolla.com/funding-sources/..546a9720a01', 'type':'application/vnd.dwolla.v1.hal+json', 'resource-type':'funding-source' }, 'customer':{ 'href':'https://api-sandbox.dwolla.com/customers/..524dde5a', 'type':'application/vnd.dwolla.v1.hal+json', 'resource-type':'customer' }, 'initiate-micro-deposits':{ 'href':'https://api-sandbox.dwolla.com/funding-sources/..6a9720a01/micro-deposits', 'type':'application/vnd.dwolla.v1.hal+json', 'resource-type':'micro-deposits' } }, 'id':'56b3ab2c-da7b-4edc-83a8-5546a9720a01', 'status':'unverified', 'type':'bank', 'bankAccountType':'checking', 'name':'Cheese', 'created':'2017-11-02T05:37:39.000Z', 'removed':False, 'channels':[ 'ach' ], 'bankName':'SANDBOX TEST BANK', 'fingerprint':'..ff1d7dcd22' }, { '_links':{ 'self':{ 'href':'https://api-sandbox.dwolla.com/funding-sources/..a51126e4', 'type':'application/vnd.dwolla.v1.hal+json', 'resource-type':'funding-source' }, 'customer':{ 'href':'https://api-sandbox.dwolla.com/customers/..6b56524dde5a', 'type':'application/vnd.dwolla.v1.hal+json', 'resource-type':'customer' }, 'with-available-balance':{ 'href':'https://api-sandbox.dwolla.com/funding-sources/..d3a51126e4', 'type':'application/vnd.dwolla.v1.hal+json', 'resource-type':'funding-source' }, 'balance':{ 'href':'https://api-sandbox.dwolla.com/funding-sources/..6e4/balance', 'type':'application/vnd.dwolla.v1.hal+json', 'resource-type':'balance' } }, 'id':'522d3f3c-5ea2-4751-a485-4ad3a51126e4', 'status':'verified', 'type':'balance', 'name':'Balance', 'created':'2017-11-02T01:51:27.000Z', 'removed':False, 'channels':[ ] } ] } here is the code that I have right now for the request... the funding sources is in the -embedded objects as you will see in the code below: sources = app_token.get('%s/funding-sources' % account_url) accounts = sources.body['_embedded'] -
port is listening in server but unable to telnet ( Django with Apache )
I have developed a Django application which I wish to deploy on apache2.4 server. I have configured mod_wsgi and stuff on a system, which is going to be my server and localhost:8081 (apache's port) is working properly on the server system. I am in a corporate environment. When I wish to access the application from another system, I am unable to access the page.(The server and client are in the same network, both using LAN) Observations: 8081 port is listening on my server system (Proto: TCP, Local Address: 0.0.0.0:8081, Foreign Address: Computername:0, State: LISTENING) I am unable to telnet to server ip on port 8081 (Connecting To 10.176.241.35...Could not open connection to the host, on port 8081: Connect failed) I have JDeveloper installed in my server system and I am able to access the homepage of WebLogic server from another system though. Site can't be reached, took too long to respond error while trying to access the page from client system What all I have done so far: Followed the exact steps mentioned in here for configuring apache with django Turned off firewall in both client and server systems Add inbound and outbound exception rules in Advcanced firewall settings in … -
How to sum and group data for template
For simplicity, assume a database with the following columns: Table: Tickets Columns: Gender, Quantity, Date where Gender can be M or F. A row is inserted for every purchase. Ultimately I want a stacked bar chart that shows the quantity purchased by males and females each month. I can't seem to find a way to do this that doesn't require 2 queries, one that sums for M per month and one for F per month. The problem is that the query sets may not have the same number of objects and may not be in the same order by date. I've tried: set = Model.objects.filter(date__month = month).values('gender').aggregate(Sum('quantity')) This sorts by date but doesn't separate M from F. Adding M or F as a filter yields the correct quantity for one of the groups. Using two queries(one for each of M, F) yields the correct quantities and date ranges but doesn't necessarily yield an identical number of sets. (eg. if in some months there are no purchases by M). Thanks in advance for guidance. -
TypeError: 'RegexValidator' object is not iterable
I was building integer array field for color. I tried to use CommaSeparatedIntegerField but it was depreated CommaSeparatedIntegerField has been deprecated. Support for it (except in historical migrations) will be removed in Django 2.0. HINT: Use CharField(validators=[validate_comma_separated_integer_list]) instead So I used set the color field as CharField instead of CommaSeparatedIntegerFieldas recommended from django.core.validators import validate_comma_separated_integer_list class Cloth(models.Model): color = models.CharField(validators=validate_comma_separated_integer_list) But I'm getting this error when I makemigrations TypeError: 'RegexValidator' object is not iterable Why am I getting this error? I followed the exact guideline :( -
Facilitate Multiple Django Files
There's multiple builtin files in Django. views.py models.py url.py settings.py wsgi.py It's frustrated to shift around. To use them effectively, one can try to create projects in repeated times. How can a newbie get used to functions of all the files in a short run? or how to organize them in mind -
Django refuse to connect to PostgreSQL [another session using the database]
I try to setup postgresql for django, with the following setting: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'tangorblog_features', 'TEST': { 'NAME': 'tangorblog_features' } }, } The idea is to test using development server with selenium. I will run the development server, and let selenium and Django LiveServerTestCase to test against that server, without creating a separate database. So each time the test run, the database is reset. But Django refuse that there are other session that using the database. However when I use mysql with the same settings like: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'tangorblog_features', 'HOST': 'localhost', 'PORT': '', 'USER': 'goat', 'PASSWORD': '', 'TEST': { 'NAME': 'tangorblog_features' } }, } The test runs without a problem, about database being used in another session. I think that this is the PostgreSQL problem. How can I tweak it, so it could behave like MySQL? -
How to Exclude Objects in QuerySet if length of QuerySet is Null?
I have 3 related Model querysets: orders = Order.objects.select_related('rest', 'oper') opers = Oper.objects.all() rests = Rest.objects.all() And a queryset that returns orders where rest is first rest and oper is first oper: r1 = orders.filter(rest=rests[0], oper=opers[0]) What I want is something like below: r2 = orders.filter(rest=rests[0], oper=opers[0]).exclude(if len(orders.filter(rest=rests[0], oper=opers[0])) == 0) I know I can do something like below: list = [] if len(r1) != 0: list.append(r1) But that will be too heavy to database, I want to optimize my queryset, hit database as less as possible is my goal. So how can I accomplish this ? -
Django view to display objects by user to visitor
I created an app that allows registered users to create products using a form. Each registered user has a profile page displaying their products, that only they can see when logged in. I want to create a view that will allow an unregistered user to view products by any user by click on a username. How do I do that? -
django-cors-headers Error occurred while trying to proxy request ...?
i'm using python3.6 and django-cors-headers proxy test page,but get the error, about app/home/productDetail/2(single goods detail) proxy error: [HPM] Error occurred while trying to proxy request /media/goods/images/2_20170719161435_381.jpg from localhost:8080 to http://shop.xxxx.com:1234 (ECONNREFUSED) (https://nodejs.org/ap i/errors.html#errors_common_system_errors) [HPM] Error occurred while trying to proxy request /media/goods/images/2_20170719161414_628.jpg from localhost:8080 to http://shop.xxxx.com:1234 (ECONNREFUSED) (https://nodejs.org/ap i/errors.html#errors_common_system_errors) [HPM] Error occurred while trying to proxy request /media/goods/images/2_20170719161405_249.jpg from localhost:8080 to http://shop.xxxx.com:1234 (ECONNREFUSED) (https://nodejs.org/ap i/errors.html#errors_common_system_errors) [HPM] Error occurred while trying to proxy request /media/goods/images/2_20170719161405_249.jpg from localhost:8080 to http://shop.xxxx.com:1234 (ECONNREFUSED) (https://nodejs.org/ap i/errors.html#errors_common_system_errors) [HPM] Error occurred while trying to proxy request /favicon.ico from localhost:8080 to http://shop.xxxx.com:1234 (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_syst em_errors) in the error, three image is saved at my project images/2_20170719161405_249.jpg images/2_20170719161414_628.jpg images/2_20170719161435_381.jpg why proxy return Error occurred while trying to proxy request ...? app/home/productDetail/2 and django-cors-headers settings is correct. -
jsonschema library -- schema is not valid?
I am using the jsonschema library (http://python-jsonschema.readthedocs.io/en/latest/validate/) in my Django application for server-side validation and am trying to do server-side validation of JSON with a provided schema. However, I get the error that the schema "is not valid under any of the given schemas." Here is my schema (it is the "scores_ap" property of the "schema" property of the class): class JSONListFieldSchemas: """ Schemas for all the JSON List Fields. Each key represents the field name. """ schema = { "scores_ap": { "$schema": "http://json-schema.org/draft-06/schema#", "title": "AP Scores", "type": "array", "items": { "type": "object", "properties": { "exam": { "type": "string" }, "score": { "type": "integer", "minimum": "1", "maximum": "5", "required": False } } } } } I am getting this error: {'type': 'object', 'properties': {'score': {'minimum': '1', 'type': 'integer', 'ma ximum': '5', 'required': False}, 'exam': {'type': 'string'}}} is not valid under a ny of the given schemas Failed validating u'anyOf' in schema[u'properties'][u'items']: {u'anyOf': [{u'$ref': u'#'}, {u'$ref': u'#/definitions/schemaArray'}], u'default': {}} On instance[u'items']: {'properties': {'exam': {'type': 'string'}, 'score': {'maximum': '5', 'minimum': '1', 'required': False, 'type': 'integer'}}, 'type': 'object'} I am using the schema as follows: from jsonschema import validate from .schemas import JSONListFieldSchemas raw_value = [{"score": 1, "exam": "a"}] validate(raw_value, JSONListFieldSchemas.schema['scores_ap']) -
django serializer split string and save to model
I have model structured like this - class BadKeywords(models.Model): bad_keyword = models.CharField(max_length=200) class Meta: db_table = "bad_keywords" if the method is post I get the string containing commas for eg.- hello, hi, hey. Now I want to split that string with the comma and save an individual item to model using serializer. -
Django Rest Framework foreign key nesting
I am trying to nest my Users table inside my Relationships table. So instead of this: [ { "user": 1, "related_user": 2, "relationship": "followed_by" } ] I am trying to get this: [ { "user": { "username": "user1", "name": "User 1", "email": "bla", "phone": "bla", "date_joined": "2017-11-01T21:34:13.101256Z" }, "related_user": { "username": "user2", "name": "User 2", "email": "bla", "phone": "bla", "date_joined": "2017-11-01T21:34:13.101256Z" }, "relationship": "followed_by" } ] I looked up tutorials and I tried adding serializers.RelatedField , UserSerializer(many=true, read-only=true) etc. but nothing worked Models.py class User(models.Model): username = models.CharField(max_length=255) name = models.CharField(max_length=255) email = models.CharField(max_length=255) phone = models.CharField(max_length=255) date_joined = models.DateTimeField(auto_now_add=True, blank=True) def __str__(self): return str(self.pk) + ", " + self.username RELATIONSHIP_CHOICE = [ ("follows", "follows"), ("followed_by", "followed_by"), ("none", "none"), ] class Relationship(models.Model): user = models.ForeignKey(User, related_name="primary_user", null=True) related_user = models.ForeignKey(User, related_name="related_user", null=True) relationship = models.CharField(max_length=40, choices=RELATIONSHIP_CHOICE, default=RELATIONSHIP_CHOICE[0]) Serializers.py from rest_framework import serializers from . import models class UserSerializer(serializers.ModelSerializer): class Meta: model = models.User fields = ( 'username', 'name', 'email', 'phone', 'date_joined', ) class RelationshipSerializer(serializers.ModelSerializer): related_user = UserSerializer(many=True) class Meta: model = models.Relationship fields = ( 'user', 'related_user', 'relationship', 'related_user' ) I tried to add related user to my serializer but it didnt work. I am getting an error: 'User' object … -
Is it accurate to say that Python/Django is more explicit than Ruby/Rails in how the components are constructed and connected together?
I've learned quite a bit with Ruby/Rails and am now venturing into learning Python/Django. What I've noticed so far is that I see the connections more clearly with Django than I did with Rails. In Rails, that magic that it has under the hood seems awesome, stuff just works....but I don't know exactly how. With Django, I have to be much more verbose but in having to write things out, I feel I understand the structure and concepts better. I haven't gone deep into Django just yet, so maybe I will hit the same roadblocks with it in the future.