Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
javascript loop over .onclick and query
So this results in the last element having the onclick function. Nothing else works. I tried to follow previous answers by wrapping i in () but that didn't seem to do anything... function waitForLoad(id, callback){ var timer = setInterval(function(){ if(document.getElementById(id)){ clearInterval(timer); callback(); } }, 100); } // to skip the LocationSet and LocationName, because we want to reuse our old Location ref = new Firebase("https://iplus1app.firebaseio.com/"); userLocs = ref.child("users/{{ user.username }}/locations"); // create the button function to redirect for each Location that exists userLocs.once("value", function(snapshot) { var keys = Object.keys(snapshot.val()) for (i = 0; i < snapshot.numChildren(); i++) { var locationKey = keys[i] //var locationKey = Object.keys(snapshot.val()[keys[i]]) var nickName = snapshot.val()[locationKey]['name'] locLat = snapshot.val()[locationKey]['position']['lat'] locLng = snapshot.val()[locationKey]['position']['lng'] locNick = snapshot.val()[locationKey]['name'] waitForLoad(nickName, function(){ document.getElementById(nickName).onclick = (function(i) { return function (i) { tempRef = ref.child("users/{{ user.username }}/temp_location"); tempRef.set( { position: { lat: locLat, lng: locLng }, name: locNick }) location.href = "{% url 'tutorLocationActivities' %}"; } })(i); }); } }) -
AttributeError: module Django.contrib.auth.views has no attribute
In my Django app useraccounts, I created a Sign-Up form and a model for my Sign-up. However, when I went to run python manage.py makemigrations, I encounter the error: AttributeError: module Django.contrib.auth.views has no attribute 'registration'. Secondly, am I coding the SignUpForm in forms.py correctly? I did not want to use the User model in models because it would request username and I didn't want my website to ask for a username. Here is my code: models.py from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import User class UserProfile(models.Model): first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) email = models.EmailField(max_length=150) birth_date = models.DateField() password = models.CharField(max_length=150) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) instance.profile.save() forms.py from django.forms import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from useraccounts.models import UserProfile class SignUpForm(UserCreationForm): class Meta: model = User fields = ('first_name', 'last_name', 'email', 'password1', 'password2', ) views.py from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate from useraccounts.forms import SignUpForm # Create your views here. def home(request): return render(request, 'useraccounts/home.html') def login(request): return render(request, 'useraccounts/login.html') def registration(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() user.profile.birth_date = … -
Django. Access primary key/id value during creation of a record
For my model I use default auto-incremented PrimaryKey/id field. I also have a field called serialNumber which according to design should reference id and generate it's own value based on id value. For example if id is 1234 then serialNumber field should be a string '00001234'. class MyModel(models.Model): ... serialNumber = models.TextField(max_length=8) ... I have no trouble updating serialNumber after the creation of record in DB, but my specific case requires serialNumber to be set together with object initial creation because right after it I return the record via REST API. I tried using signals, but pre_save returns None @receiver(pre_save, sender=MyModel) def my_pre_save(sender, instance, **kwargs): print(instance.id) On the other hand if I do: @receiver(post_save, sender=MyModel) def my_post_save(sender, instance, **kwargs): print(instance.id) I receive the value for id but it's too late because right after .save() my REST API returns response with created object and I don't want to add code that manages serialNumber to serializer. Overriding .save() method for MyModel didn't work either: def save(self, *args, **kwargs): print(self.id) super(MyModel, self).save(*args, **kwargs) Id field still returns None. Anyone has an idea how to access id value during initial creation of a record? -
Using a django model as a field for another model?
I have been tasked with creating Django Models for a hypothetical apartment booking application. My question is: can I use a model that I've defined, as a field in another model? For example, I will have one model called "Listing" that represents an apartment being listed. class Listing(models.Model): address = models.IntegerField() owner = models.CharField(max_length=256) duration = models.DurationField() price= models.IntegerField() I also want to have a "Booking" model that represents an apartment once someone has booked it. It will have the exact same info as a Listing, with the addition of the username of the person who booked it. So can I have my Booking model use Listing as a field? And then just have one extra field for the booker's username. Any other tips/critiques are highly appreciated as I am a complete beginner at Django. -
Django migrations without db table rewrites
I have a huge table and I don't want to cause a table rewrite or so. so in my model I first created a field like this: field = models.IntegerField(null=True) then executed makemigrations, then changed my field to field = models.IntegerField(null=False, default=0) executed makemigrations again and second migration looks like this: migrations.AlterField( model_name='game', name='field', field=models.IntegerField(default=0), ), Would this cause a table rewrite? I know I will still have Null values in the previous rows but I want to make this work for the next rows without causing DB downtime. My db is PostgreSQL. and first migration looks like this, if helpful: migrations.AddField( model_name='game', name='field', field=models.IntegerField(null=True), ), -
django OnetoOneField in database
how one-to-one field in django reflected in database? I have two model: Neighbor and Neighbor_Info which has one-to-one field connection to Neighbor. But In the database I don't see any reference field relation between this two table So I wonder how the one-to-one relation reflected on database? (I use postgresql) -
django registration redux error
I'm using django registration redux in my django project, the problem happened in mapping urls, when you visit: http://127.0.0.1:8000/accounts/register/ it redirect me into : http://127.0.0.1:8000/accounts/profile/ with error message : Using the URLconf defined in trydjango18.urls, Django tried these URL patterns, in this order: ^$ [name='home'] ^contact$ [name='contact'] ^about$ [name='about'] ^admin/ ^accounts/ ^activate/complete/$[name='registration_activation_complete'] ^accounts/ ^activate/resend/$[name='registration_resend_activation'] ^accounts/ ^activate/(P<activation_key>\w+)/$[name='registration_activate'] ^accounts/ ^register/complete/$ [name='registration_complete'] ^accounts/ ^register/closed/$ [name='registration_disallowed'] ^accounts/ ^register/$ [name='registration_register'] ^accounts/ ^login/$ [name='auth_login'] ^accounts/ ^logout/$ [name='auth_logout'] ^accounts/ ^password/change/$ [name='auth_password_change'] ^accounts/ ^password/change/done/$[name='auth_password_change_done'] ^accounts/ ^password/reset/$ [name='auth_password_reset'] ^accounts/ ^password/reset/complete/$[name='auth_password_reset_complete'] ^accounts/ ^password/reset/done/$ [name='auth_password_reset_done'] ^accounts/ ^password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(? P<token>.+)/$ [name='auth_password_reset_confirm'] ^static\/(?P<path>.*)$ ^media\/(?P<path>.*)$ The current URL, accounts/profile/, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. here is my code for settings.py INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'registration', #should be immediately above 'django.contrib.auth' 'django.contrib.auth', 'crispy_forms', 'newsletter',) and ACCOUNT_ACTIVATION_DAYS = 7 REGISTRATION_AUTO_LOGIN = True here is my code for urls.py: urlpatterns = [ url(r'^$', 'newsletter.views.home', name='home'), url(r'^contact$', 'newsletter.views.contact', name='contact'), url(r'^about$','trydjango18.views.about',name='about'), url(r'^admin/', include(admin.site.urls)), url(r'^accounts/', include('registration.backends.default.urls')),] -
django async task using django q task and redis server
i try to follow this tutorial for django q async tasks and i have install redis from this video on windows 10 (i have also rabbitqm server) I don't get some error but my function don't execute i don't get anything from my function i think the problem is on redis server config. any idea ? here the code : settings.py INSTALLED_APPS = [..]+'django_q', # redis defaults Q_CLUSTER = { 'redis': { 'host': '127.0.0.1', 'port': 6379, 'db': 0, 'password': None, 'socket_timeout': None, 'charset': 'utf-8', 'errors': 'strict', 'unix_socket_path': None } } tasks.py import math import sys def add(n1,n2): test=n1/n2 return test views.py def app_details(request,slug): if request.method == "POST": test = request.POST.get('iy') t1=test t2=test*1542 async('tasks.saga',t1,t2) return render(request, 'page.html',.... that message I get without error in pycharm : 23:54:27 [Q] INFO Enqueued 3 redis cmd : redis command server : -
Overwrite django view with custom context (Django 1.11, Viewflow)
I have a Django 1.11 project using Viewflow - https://github.com/viewflow/viewflow - that I've incorporated. It's been very helpful, but a lot of stuff is kind of "magic", and being my first serious Django project, I'm running into an issue I'm not sure of how to solve, or the best way. I have a generic template that expects a lot of context. I have a function that adds this context to all of my views: def add_general_context(context, MOC, MOC_enabled_fields = (), MOC_status = None): context['MOC'] = MOC context['current_date'] = timezone.now().strftime("%D") context['MOC_form'] = forms.MOCForm(prefix="MOC_form", MOC_enabled_fields=MOC_enabled_fields, instance=MOC) context['MOCAttachments'] = models.MOCAttachment.objects.filter(MOC=MOC) context['MOCAttachment_form'] = forms.MOCAttachmentForm(prefix="MOCAttachment_form") context['MOCApprovals'] = models.MOCApproval.objects.filter(MOC=MOC) context['MOCTasks'] = models.MOCTask.objects.filter(MOC=MOC) context['MOC_status'] = MOC_status context['MOCConversation'] = models.MOCConversation.objects.filter(MOC=MOC) # Add comments to the conversation for conversation in context['MOCConversation']: conversation.comments = models.MOCComment.objects.filter(conversation=conversation) context['MOCComment_form'] = forms.MOCCommentForm(MOC=MOC) context['MOCCommentReply_form'] = forms.MOCCommentReplyForm() I basically need to add this context to a view that is inside viewflow - namely, AssignTaskView - https://github.com/viewflow/viewflow/blob/f50accb3cde5d53f1d4db0debf5936867712c3bd/viewflow/flow/views/task.py#L109 I've tried a few things to overwrite/add to the context, but none seem to work. Attempt 1: Overwrite the URL and use extra_context (SO suggested this) - The issue is that the urls are "magic", my urlpatterns is very simply: from material.frontend import urls as frontend_urls urlpatterns = [ url(r'^MOC/', … -
Render Url dynamically in ReactJS depending on the environment
I am using ReactJS in the front end wherein upon clicking a submit button, it calls 4 apis in dev-environment: ReactDOM.render( <ParameterForm url_schema="http://192.168.99.100/api/v1/var" url_uischema="http://192.168.99.100/api/v1/ui" url_data="http://192.168.99.100/api/v1/data" url_submit="http://192.168.99.100/api/v1/calculated" />, document.getElementById('form') ); I am using docker to run the application locally which has a settings folder with base.py, local.py and production.py. For Production-env, I want the apis to be called something like these: ReactDOM.render( <ParameterForm url_schema="http://xyz:8000/api/v1/var" url_uischema="http://xyz:8000/api/v1/ui" url_data="http://xyz:8000/api/v1/data" url_submit="http://xyz:8000/api/v1/calculated" />, document.getElementById('form') ); I need to know whether is there a way in which these apis can be declared either in local.py or production.py and can be called dynamically in my DOM based on the environment in which I run my app. -
ImageField image_width and image_height auto fill for existing database?
I have an existing database table with an ImageField that already has a bunch of existing registries. I want to add the image_width and image_height on my model but I need something to auto-fill the existing tables with. class ItemImage(models.Model): file = models.ImageField(upload_to=image_directory_path, width_field='image_width', height_field='image_height') image_width = models.IntegerField() image_height = models.IntegerField() I read on the docs that both image_width and image_height get saved automatically when on save(), but the existing images have already been saved. -
Issue deploying django to AWS
I'm trying to deploy my personal website to aws using elastic beanstalk. My website is in django/python. I keep encountering the same issue. Each time I upload the files I get the following error in AWS console: Your requirements.txt is invalid. Snapshot your logs for details. Ok, so I check the logs and from the bits I notice the following: Error installing dependencies: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 2Traceback (most recent call last): File "/opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py", line 22, in main install_dependencies() pip version 7.1.2, however version 9.0.1 is available.You should consider upgrading via the 'pip install --upgrade pip' command. I googled and found many having this issue. They suggested updating pip and installing dependencies manually. So I logged into the server and started by updating pip. Boom, another issue. After updating to pip 9.0.1 when I type pip --version I get the following: -bash: /usr/bin/pip: no such file or directory I can't seem to move on with this. I thought elastic beanstalk is supposed to be easy but I keep getting more and more stuff to do. I'm at my wits end after all the testing today. Could I ask for any help with this? What should … -
syntax for django queryset exists
Suppose I have Django models like this: class Foo(Model): bar = ForeignKey(Bar, related_name="foos") class Bar(Model): dummy = models.CharField(max_length=128, null=False) I know that I can get all Foo object for a bar using bar.foos.all(). Suppose I just want to see if a bar has any Foos. What is the syntax for this: Option 1: bar.foos.exist() Option 2: bar.foos.all().exists() Which of the above is correct? Every example I have seen of exists() uses filter() so I'm not sure what to do if I don't need to filter.