Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Foreign key field share for serialization speed ups
Imagine I have the next models (do not mind the field types, example purpose): class County(model.Model): country = models.TextField() class City(model.Model): country = models.ForeignKey(Country) city = models.TextField() class Person(model.Model): city = models.ForeignKey(City) name = models.TextField() and the corresponding serializations of these models class CountrySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Country fields = ('country') class CitySerializer(serializers.HyperlinkedModelSerializer): country = CountrySerializer() class Meta: model = City fields = ('city', 'country') class PersonSerializer(serializers.HyperlinkedModelSerializer): city = CitySerializer() class Meta: model = Person fields = ('name', 'city') Ok, so I'm using the Django REST Framework to build an API. One of the endpoints is /person that returns all the persons. def get(request): persons = Person.objects.all() data = PersonSerializer(persons, many = True) return JsonResponse(data.data, safe = False) The thing is: it takes so long to do the serialization of persons because of the ForeignKeys. My main goal is to make the request go as fast as possible tweaking this code, models or serializers. The easy [1] but, obviously not the best, is to store the actual strings of city and country inside the Person model, and only serialize those, so the actual foreign keys are only used for querying and filtering purposes. But in that case, the scaling … -
How can I get to access to the attrribute of my foreign key in my model?
Hello I am using Django and in my project I define a class which contains a foreign key. My problem is the following one : I don't achieve to access to the attributes of the field which is defined by the foreign key. Basically I tried this : mytable = MyTable.objects.filter(a=a) mytable.a.food So actually mytable contains a foreign field which is defined such as : a = models.ForeignKey(A, on_delete=models.CASCADE, default=None) and in the table a there exist a field by the name of food But the problem is I get this error : 'Queryset' object has no attribute 'a' Could you help me please ? Thank you -
does model design depends on the ui?
I am getting confused on designing the model. For example, take a scenario of job sites. There will be three kind of users. 1. End User - job seeker 2. Company 3. Recruiter Based on the type or role of user, they are redirected to their respective dashboard. Now if there is two different kind of UI for understanding the model design First Design where role is right there in the signup form signup username email password role Second Design where there is no role when signing up but its asked after signing up in a different page like signup/step/1 as a wizard signup username email password Does UI affects the model design? For now my model is something like this class User(AbstractUser): USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] USER_TYPE_CHOICES = ( ('enduser', 'enduser'), ('recruiter', 'recruiter'), ('company', 'company'), ) role = models.CharField(choices=USER_TYPE_CHOICES, max_length=20, default='enduser') objects = UserManager() def __str__(self): return self.email -
Django does not serve static files in Debug True
Here's my setting.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") here is my url.py if settings.DEBUG: urlpatterns += [ url(r'^static/(?P<path>.*)$', serve, {'document_root': settings.STATIC_ROOT, 'show_indexes':settings.DEBUG}) ] or if settings.DEBUG: urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) but when I want to access http://127.0.0.1:8000/static/ I get Directory indexes are not allowed here. The static folders are in the root folder of the project, beside of the manage.py -
Django prevent duplicates in database when uploading multiple files
Context I have a view that handles uploading multiple files at once. When a duplicate file (path already exists for a specific customer) is uploaded: 1) The duplicate files and corresponding fields are created in the database 2) The duplicate files are NOT saved in the filesystem, instead the existing files are used My views.py looks like this: # views.py class FileFieldView(FormView): form_class = FileFieldForm template_name = 'upload.html' success_url = 'upload.html' def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('data') if form.is_valid(): for f in files: customer = Customer.objects.get(customer_name=request.POST.get('customer_name')) File.objects.get_or_create(data=f, customer_uuid_id=customer.customer_uuid) return self.form_valid(form) else: return self.form_invalid(form) Problem I am satisfied with the behaviour of the filesystem when duplicate files are uploaded. However, I want to prevent duplicate entries in the database whenever duplicate files are uploaded. I figured that using get_or_create() in my view would do the trick since File.objects.get(data='path_that_already_exists', customer_uuid='some_customer') returns an existing File object in my Django console. However, whenever duplicates are uploaded, they are still added to the database. What I tried I also tried to write a custom FileSystemStorage which will check if a path already exists and if it does, delete the uploaded file but that did not do the … -
Algorithm to dynamically populate Javascript array with zeros before and after values
I get a data of months dynamically with python/django and pass it to my template. There I use Javascript to manipulate the data That means that in my template I have a javascript array, each number representing a month like so: months = [1,2,3,4] or so: months = [4,5,6] or so: months = [6,7,8] Depending on the array above I'd like to populate the missing positions with zeros. Missing positions means that the array should have a length of 12 at the end. Each month should be at the accurate position. For example: months = [1,2,3,4,0,0,0,0,0,0,0,0] or so months = [0,0,0,4,5,6,0,0,0,0,0,0] or so months = [0,0,0,0,0,6,7,8,0,0,0,0] I tried many things. Splicing seemed a good method but didn't work as expected. I couldn't solve it using Array.fill. I also tried to create a new array with 12 zeros and then pushing the values of the other array into it, but it didn't work. Can somebody point me into the right direction or has an idea? Very much appreciated. -
Development server is not starting and getting no response
I am just a begineer for django web development. Initially i created a project and an app. When i try to run the django server using the 'python manage.py runserver' command it loads for sometime and i get no response. Kindly help out with this issue. I am using Pycharm 2019 community edition -
how to post data into database through html template in django without using forms
I want to post data into database through html template and render template successfully inserted into your database.but showing error MultiValueDictKeyError at /empdetails 'eno' after chenging code in views.py like num=request.post['eno'] it showing error like this IntegrityError at /empdetails (1048, "Column 'eno' cannot be null") Here is my code models.py class Employee(models.Model): eno=models.IntegerField(null=True) ename=models.CharField(max_length=20) eadd=models.CharField(max_length=20) and views.py def Empdetails(request): num=request.POST.get('eno') nam=request.POST.get('ename') add=request.POST.get('eadd') details=Employee(eno=num,ename=nam,eadd=add) details.save() return render(request,'emp.html') and template emp.html <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/templates/inserted.html" method="post"> <label for="eno">Eid :</label> <input type="text" name="ex.reddy" value="" placeholder="eid" id="eno"> <label for="nam">Ename</label> <input type="text" name="name" value="" placeholder="name" id="nam"> <label for="add">Eadd</label> <input type="text" name="add" value="" placeholder="add" id="add"> <input type="submit" value="submit"> </form> </body> </html> -
Data source name not found and no default driver specified (0) (SQLDriverConnect)')
I am new to mac and trying to set up a new project in system ,I am running the server and getting the following error django.db.utils.InterfaceError: ('IM002', '[IM002] [unixODBC][Driver Manager]Data source name not found and no default driver specified (0) (SQLDriverConnect)') I am using docker to connect to database and have the following configurations. DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'xxx', 'USER': 'abc', 'PASSWORD': 'xxxx', 'HOST': '0.0.0.0', 'PORT': '1401', 'OPTIONS': { 'dsn': 'xxx', 'autocommit': True, } }, } docker docker run -e "ACCEPT_EULA=Y" -e "SA_PASSWORD=xxxx" -p 1401:1433 --name xxxx -d "microsoft/mssql-server-linux:2017-latest" -
AWS Elasticbeanstalk with Dajngo: Incorrect application version found on all instances
I'm trying to deploy a django application on elasticbeanstalk. It has been working fine then suddenly stopped and I cannot figure out why. When I do eb deploy I get INFO: Environment update is starting. INFO: Deploying new version to instance(s). INFO: New application version was deployed to running EC2 instances. INFO: Environment update completed successfully. Alert: An update to the EB CLI is available. Run "pip install --upgrade awsebcli" to get the latest version. INFO: Attempting to open port 22. INFO: SSH port 22 open. INFO: Running ssh -i /home/ubuntu/.ssh/web-cdi_011017.pem ec2-user@54.188.214.227 if ! grep -q 'WSGIApplicationGroup %{GLOBAL}' /etc/httpd/conf.d/wsgi.conf ; then echo -e 'WSGIApplicationGroup %{GLOBAL}' | sudo tee -a /etc/httpd/conf.d/wsgi.conf; fi; INFO: Attempting to open port 22. INFO: SSH port 22 open. INFO: Running ssh -i /home/ubuntu/.ssh/web-cdi_011017.pem ec2-user@54.188.214.227 sudo /etc/init.d/httpd reload Reloading httpd: [ OK ] When I then run eb health, I get Incorrect application version found on all instances. Expected version "app-c56a-190604_135423" (deployment 300). If I eb ssh and look in /opt/python/current there is nothing there so nothing is being copied across I think something may be wrong with .elasticbeanstalk/config.yml. Somehow the directory was deleted and setup again. This is the config.yml branch-defaults: master: environment: app-prod scoring-dev: environment: … -
Queryset only allowing me to SELECT just one tables fields in a join
I have two tables, but am just trying to get just the dNm from T table (while joining), but instead I can only pull fields from TSF. I have models file: models.py class T(models.Model): emailVerified = models.EmailField(max_length=50) dNm = models.CharField(max_length=40,unique=True) FKToUser = models.ForeignKey('auth.user', default=None, on_delete=models.PROTECT) class TSF(models.Model): httpResponse = models.IntegerField(validators=[MaxValueValidator(3)]) FKToT = models.ForeignKey('T', on_delete=models.PROTECT) In regular (pseudo) sql I'm trying to do something like: SELECT dNm FROM T, TSF WHERE T.id=TSF.FKToT AND T.FKToUser=<<THE CURRENTLY SIGNED IN USER>> However, its only allowing me to do the following in pseudo sql: SELECT <any field from TSF> FROM T, TSF WHERE T.id=TSF.FKToT AND T.FKToUser=<<THE CURRENTLY SIGNED IN USER>> My views.py: def viewed(request): AUS = TSF.objects.filter(FKToTld__FKToUser=request.user).values('dNm') return render(request, 'file.html', { 'ATFS':ATFSs }) This is throwing an error that only TSF fields are available in values() above. What am I doing wrong here? -
How to pass Django variable to Vue prop
I'm trying to pass a Django template boolean variable to a Vue component. At the component I added the variable to the props and specified the type: Vue.component('my-component', { props: { id: {type: Number, required: true}, static_url: {type: String, required: true}, the_boolean_variable: {type: Boolean, required: true}, }, Creating the component: <my-component v-bind:id={{ job.pk }} static_url="{{STATIC_URL}}" v-bind:the_boolean_variable={{ client.show_price }}> </my-component> My first attempt was to not bind it but just pass along the value of client.show_price. The value of the_boolean_variable was set to the string "True" or "False" and Vue complained that it received a string rather than a boolean. Duckduckgo told me that I need to bind non-string values, so I did but now I have the following error: "Property or method "True" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.". Inspecting the value of the_boolean_variable shows 'undefined'. I know that {{ client.show_price }} is set because if I print it, it shows up on the page, and if I put true rather than {{ client.show_price }} there are no errors. Thus I think that Vue … -
Deploy a flask application alongside a Django application with uwsgi + nginx
trying to deploy a simple flask app in a server where is currently deployed a django app. The django app works okay, but with the flask app shows 404 error, althogh I've done the correct settings and I don't see any error shown in the logs. currently, this is my app2.ini file my app.py: from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __name__ == "__main__": app.run(host='::') wsgi.py from flaskapp.app import app if __name__ == "__main__": app.run() nginx conf: server { listen *:80; listen [::]:80; server_name mysite.com; # Let's Encrypt location /.well-known/acme-challenge/ { root /var/www/html; } # Everything else -> SSL location / { return 301 https://$host$request_uri; } } server { listen 443; listen [::]:443; server_name mysite.com; access_log /var/log/nginx/access.log; ssl on; ssl_certificate /etc/letsencrypt/live/mysite.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/mysite.com/privkey.pem; client_max_body_size 256m; location / { try_files $uri @uwsgi; } location @uwsgi { include uwsgi_params; uwsgi_pass unix:/home/app/app/uwsgi.sock; } location /flask/ { include uwsgi_params; uwsgi_pass unix:/home/app2/app/flaskapp/uwsgi.sock; } } my app2.ini file: [uwsgi] socket = /home/app2/app/flaskapp/uwsgi.sock chdir = /home/app2/app wsgi-file = flaskapp/wsgi.py touch-reload = flaskapp/wsgi.py venv = /home/app2/pyvenv processes = 4 threads = 2 chmod-socket = 666 daemonize=true vacuum = true uid = app2 gid = app2 callable = app tree: flaskapp ├── … -
How to get the same context that's passed to change_list.html in another view?
I need to pass multiple ChangeLists and other variables that are passed to change_list.html and iterate over them in template. I don't know how to access them because when i try to make an instance of ModelAdmin subclass and i try to access get_changelist_instance method (SomeModelAdmin(SomeModel, admin.site).get_changelist_instance(request)), django gives following error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Is there a better way to get the same context thats passed to change_list.html in django admin from multiple models at once? I try to display change list for multiple models at once, but i don't know how to get cl and opts inside the code. -
Query two tables in Django on currently authenticated user
Im trying to query 2 tables in my django model - but having some issues formulating how to write the syntax. models.py class T(models.Model): emailVerified = models.EmailField(max_length=50) dNm = models.CharField(max_length=40,unique=True) FKToUser = models.ForeignKey('auth.user', default=None, on_delete=models.PROTECT) class TSF(models.Model): httpResponse = models.IntegerField(validators=[MaxValueValidator(3)]) FKToT = models.ForeignKey('T', on_delete=models.PROTECT) In regular (pseudo) sql I'm trying to do something like: SELECT * FROM T, TSF WHERE T.id=TSF.FKToT AND T.FKToUser=<<THE CURRENTLY SIGNED IN USER>> I'm just having some issues formulating how to write this in django orm. Can someone help? Thanks -
My Django project uploads media files to s3 bucket but they don't show up on site
I'm trying to link my django project to s3 bucket to storage my user uploaded files. The files are getting uploaded correctly but after django can't show them on page (it shows blank spot). When i use my photo.url variable in template it produces link to s3 but this is the server answer. 'storages' is added to INSTALLED_APPS XML answer to photo.url: xml http://oi64.tinypic.com/2vakyeg.jpg My setting.py settings http://oi66.tinypic.com/1zpjehi.jpg My storage_backends: storage http://oi67.tinypic.com/28arg2u.jpg -
Django serializer send array in object
I have models like this: class Model1(models.Model): time = models.DateTimeField(auto_now=True) class Model2(models.Model): model1= models.ForeignKey(Model1, on_delete=models.CASCADE, related_name="my_list") f1 = models.FloatField() I want to create endpoint for send data like this: {"time":"123", "my_list":[{"f1":"123"}, {"f1":"123"}, {"f1":"123"}]} This is my serializer class TestSerializer(serializers.ModelSerializer): class Meta: model = Model1 fields = ('id', 'time', 'my_list',) How i can send json like i want? ( {"time":"123", "my_list":[{"f1":"123"}, {"f1":"123"}, {"f1":"123"}]} ) -
What should be used to translate the values of the model columns?
I am using Django 2.1 and I want to make a site that will support multiple languages. Static page elements I translated using the tag: {% trans %} using i18n Please tell me what I need to use to add a translation to the values of the model columns, preferably manually, for example: product_name: 'pencil' And in the Russian version it would be 'карандаш' -
Django : is it possible to get a reference of a formfield from itself?
Take such a form : class MyForm(forms.Form): my_image = MyCustomizedImageField(**some_params) MyCustomizedImageField will display a customized widget (customized Dropzone.js here). On image upload, this widget will make an ajax call to a generic view. In this view, I would like to validate data, so I need a reference to MyForm.my_image to be able to use its validate() method. The generic view must work for all forms, so the reference to the field to validate should come from the request in some way. I could create the new parameter 'ajax_field' to do the job : class MyForm(forms.Form): my_image = MyCustomizedImageField(**some_params, ajax_field='my_app.MyForm.my_image') But it is ugly, I would like to avoid this extra parameter : is there a way, within my MyCustomizedImageField.__init__() to get this information : 'my_app.MyForm.my_image' in order to pass it to the widget ? -
Tablesorter sorts customely parsed numbers properly only in descending order, ascending order is wrong
Using Mottie's fork of tablesorter. Needed to sort dates in 'Jan 16' format. From Aug to Jul. Wrote a custom parser. let monthsFirstDayIndexes = { 'Aug': 0, 'Sep': 31, 'Oct': 61, 'Nov': 92, 'Dec': 122, 'Jan': 153, 'Feb': 184, 'Mar': 213, 'Apr': 244, 'May': 274, 'Jun': 305, 'Jul': 335, } $.tablesorter.addParser({ id: 'date', is: function() { return false; }, format: function(s) { dateSplitted = s.split(' ') return monthsFirstDayIndexes[dateSplitted[0]] + Number(dateSplitted[1]) }, type: 'numeric' }); I'm using the parser it the Django template {% extends 'base.html' %} {% load static %} {% load tags %} {% block title %} {{ player.name }} - Game Log - NHL stats tracker {% endblock title %} {% block styles %} <link rel="stylesheet" href="{% static 'players/tablesorter.css' %}"> {% endblock styles %} {% block content %} <img class="rounded-circle account-img" src="{{ player.image.url }}"> <h5>{{ player.name }} Game Log</h5> <a href="{% url 'player_detail' player.slug player.nhl_id %}">Return to the full profile</a><br> <!-- GOALIES --> {% if player.position_abbr == 'G' %} <!-- GAMELOG --> <table id="tab1" class="tablesorter"> <thead> <tr> <th>Date</th> <th>Opp</th> <th>Res</th> <th>Min</th> <th>GA</th> <th>SV %</th> <th>SV</th> <th>SA</th> <th>SHO</th> </tr> </thead> <!-- PAGER --> <tfoot> <tr class="tablesorter-ignoreRow"> <th colspan="28" class="pager"></th> </tr> <tr class="tablesorter-ignoreRow"> <th colspan="28" class="pager-g form-horizontal pager"> <button type="button" … -
Getting pkg_resources.DistributionNotFound: The 'supervisor==3.2.0' distribution was not found and is required by the application?
Getting an error while trying to run a gunicorn script through supervisor. The gunicorn script is running fine while running it directly. I am on ubuntu 16.04 supervisor version : Getting pkg_resources.DistributionNotFound: The 'supervisor==3.2.0' distribution was not found and is required by the application while running sudo supervisorctl reread my gunicron script to run Django application: #!/bin/bash NAME="applicant_screening" # Name of the application DJANGODIR=/home/applicant-screening-system/screening_backend # Django project directory #SOCKFILE=/home/track_ip/run/gunicorn.sock # we will communicte using this unix socket USER=root # the user to run as #GROUP=webapps # the group to run as NUM_WORKERS=3 # how many worker processes should Gunicorn spawn DJANGO_SETTINGS_MODULE=screening_backend.settings # which settings file should Django use DJANGO_WSGI_MODULE=screening_backend.wsgi # WSGI module name echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR source /home/screen-env/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Create the run directory if it doesn't exist RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR # Start your Django Unicorn # Programs meant to be run under supervisor should not daemonize themselves (do not use --daemon) exec gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER \ --bind=0.0.0.0:8000 \ --log-level=debug \ --log-file=- -
How to configure Traefik to use Django Sites Framework
I'm testing cookiecutter-django in production using Docker-compose and Traefik with Let'sencrypt. I'm trying to configure it to work with 2 domains (mydomain1.com and mydomain2.com) using Django sites. How to configure Traefik so it could forward traffic to necessary domain? This is my traefik.toml logLevel = "INFO" defaultEntryPoints = ["http", "https"] # Entrypoints, http and https [entryPoints] # http should be redirected to https [entryPoints.http] address = ":80" [entryPoints.http.redirect] entryPoint = "https" # https is the default [entryPoints.https] address = ":443" [entryPoints.https.tls] # Enable ACME (Let's Encrypt): automatic SSL [acme] # Email address used for registration email = "mail@mydomain1.com" storage = "/etc/traefik/acme/acme.json" entryPoint = "https" onDemand = false OnHostRule = true # Use a HTTP-01 acme challenge rather than TLS-SNI-01 challenge [acme.httpChallenge] entryPoint = "http" [file] [backends] [backends.django] [backends.django.servers.server1] url = "http://django:5000" [frontends] [frontends.django] backend = "django" passHostHeader = true [frontends.django.headers] HostsProxyHeaders = ['X-CSRFToken'] [frontends.django.routes.dr1] rule = "Host:mydomain1.com" -
django image can not be seen
I followed the steps indicated in the tutorials but the image is still not seen. It finds it but it does not show it: "GET /static/imagenes/triste.png HTTP / 1.1" 404 1782. {% load static %} <img src= "{% static 'imagenes/feliz.png' %}" alt="hola" > settings.py STATIC_URL = '/static/' STATICFILES_DIR = [os.path.join(BASE_DIR, 'static')] STATIC_ROOT = os.path.join(BASE_DIR,"static") MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
Adding foreign key to model in django 1.0.4
I have django 1.0.4 and I want to add a new model and one-to-many (Foreign Key) relationship. when I run the python manage.py syncdb command, I get the message: Creating table blog_blogcategory. Here is OK. One, I do not have a category field in the Blog table. Why this is not working? Here are my models: class BlogCategory(models.Model): name = models.CharField(max_length=255) class Meta: verbose_name = 'Blog categpry' verbose_name_plural = 'Blog categories' def __unicode__(self): return self.name class Blog(models.Model): category = models.ForeignKey(BlogCategory, related_name="blogs", null=True, blank=True) -
Django 1.9 Upgrade Issue "django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet."
I upgraded from Django 1.8 to 1.9 but facing this problem "django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet." None of the other solutions on stackoverflow worked. Please help I already tried other solution like adding import django django.setup() but no success.