Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django reverse lookup query within three tables
I have three tables User, Users_clients, and Credits. I want to list tables of current user's clients with their details and credit. If any client is listed in credit table then credit should return 0 where else it should return the credit value. my model.py is class User_clients(models.Model): user = models.ForeignKey(User, related_name='myuser') client = models.ForeignKey(User, related_name='myclient') class Credits(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) credit = models.IntegerField(null=True, default=0) my views.py is def clients(request): try: data = User_clients.objects.order_by('-id').filter(user_id=request.user.id)[0:10] except User_clients.DoesNotExist: data = None return render(request, "client_list.html",{'title':"Client List",'clients':data,'active':'myclients','open':'clients'}) Thanks a lot in advance! -
Django DRF TypeError: object is not iterable, how to approach this?
Wondering what I'm doing wrong here. I'm running DRF with a React frontend. Trying to get one serializer to GET and POST a user's selected stations. The AJAX POST works great, but the get on a page's initial load no longer works, and Django tells me: TypeError: 'Station' object is not iterable. From reading around I'm vaguely aware that I shouldn't be declaring station with many = True, as this is causing the exception to be thrown. But I can't find any other way to get it working, it mangles the JSON POST request if I remove this option and stops the data validating. The create is using custom code and is working fine. Should I be trying to get this to work seamlessly or should I just hack it / make a different serializer to do the POST? Am I doing this in a logical way or have i got it all back-to-front? Thanks models.py class Station(models.Model): network = models.ForeignKey(Network, on_delete=models.CASCADE) name = models.CharField(db_column='name', max_length=256) # Field name made lowercase. latitude = models.FloatField() longitude = models.FloatField() users = models.ManyToManyField('Account', through='UserStations') class Meta: managed = True def __str__(self): return self.name class UserStations(models.Model): station = models.ForeignKey(Station, on_delete=models.CASCADE) user = models.ForeignKey(Account, on_delete=models.CASCADE) … -
Django AWS S3direct Upload with Dynamic Forms
1. Initial Situation OK I use django-s3direct to upload Images directly to AWS S3. django-s3direct let me only upload one image on the form. I thought the easiest solution is to add dynamically another ImageForm if the user uploaded an Image or clicks an "add more" button. I use django-dynamic-formset. 2. Problem I can upload one image. Then i click the "add more" button and another ImageField appears. After I select a new file to upload I get an error: POST [XHR] http://127.0.0.1:8005/en/s3direct/get_upload_params/ [HTTP/1.0 403 FORBIDDEN 7ms] TypeError: uploadParameters is null The s3direct/bundled.js function which causes the error is: const checkFileAndInitiateUpload = function(event) { console.log('Checking file and initiating upload…') const element = event.target.parentElement, file = element.querySelector('.file-input').files[0], dest = element.querySelector('.file-dest').value, csrfTokenName = element.querySelector('.csrf-cookie-name').value, destinationCheckUrl = element.getAttribute('data-policy-url'), signerUrl = element.getAttribute('data-signing-url'), form = new FormData(), headers = {'X-CSRFToken': Cookies.get(csrfTokenName)}; form.append('dest', dest) form.append('name', file.name) form.append('type', file.type) form.append('size', file.size) request('POST', destinationCheckUrl, form, headers, element, function(status, response) { const uploadParameters = parseJson(response) switch(status) { case 200: initiateMultipartUpload( element, signerUrl, uploadParameters.object_key, uploadParameters.access_key_id, uploadParameters.region, uploadParameters.bucket, uploadParameters.bucket_url, uploadParameters.cache_control, uploadParameters.content_disposition, uploadParameters.acl, uploadParameters.server_side_encryption, file ); break; case 400: case 403: case 500: error(element, uploadParameters.error) break; default: error(element, 'Sorry, could not get upload URL.') } }) } and here is the snippet … -
Session token api in Django tastypie
I need to implement using api such behavior: App opening without registration If it's new user, then send /signup request, and get new session If there is a session, then check it. So I think I need /signup method which creates session and returns a session token. And /check method which gets a token and returns check result. I want to know how to create user without any params and return session token and how to check this token? I'm new at Django. And I want to use Tastypie for api. -
Retrieving a Django form field value using AJAX
For each fact in facts, there is a form where you can upvote or downvote the fact. Further explanation is found below. Template and Form code are listed below respectively: template <ul> {% for fact in facts %} <form method='POST' action="{% url 'facts:list' fact.pk %}" id="list_vote"> {% csrf_token %} {{ form }} <input type="submit" value="vote" /> </form> {% endfor %} </ul> forms.py code: VOTE_CHOICES = [ (1, 'upvote'), (0, 'downvote') ] class Vote(forms.Form): vote = forms.ChoiceField(choices=VOTE_CHOICES, widget=forms.RadioSelect(attrs={'class': 'vote'})) For each fact in models.Fact.objects.all(), there is a form, which consists of radio buttons of 2 inputs (upvote, downvote), created for this specific fact. What I'm now doing is basically Django 101: getting the value of the fact that is being voted and update its model accordingly in the views. What I want to do is retrieve the value of this specific fact using AJAX and update the model accordingly without leaving/refreshing the page -
How to filter in django by two properties of the same related object in a many-to-one relationship?
My model structure looks like this: class OneModel(model): not_important = IntegerField() class RelatedModel(): propertyA = IntegerField() propertyB = IntegerField() original = ForeignKey(OneModel, related_name='related') I am looking for a native django solution (without raw sql), to recreating basically this query: select * from OneModel om where not exists (select id from RelatedModel rm where original_id = om.id and propertyA = 1 and propertyB = 2); Here's what I've tried: OneModel.objects.exclude(related__propertyA=1, related__propertyB=2) Unfortunately this has the effect of selecting OneModel objects which have neither a related with propertyA=1, nor a related with propertyB=2, not ones that don't have a single related that matches both criteria. Here's the generated sql from my django query: SELECT lots_of_fields FROM "OneModel" WHERE NOT ("OneModel"."id" IN (SELECT U1."original_id" AS Col1 FROM "RelatedModel" U1 WHERE U1."PropertyA" = 1) AND "OneModel"."id" IN (SELECT U1."original_id" AS Col1 FROM "RelatedModel" U1 WHERE U1."PropertyB" = 2)) And just to be clear, my problem is not with using "id" in instead of exists, but with the logic of the query. I tried playing around with Q-objects, but can't figure out any way to use to solve this. I also looked at F-objects, but they also don't seem to be relevant. Is there any … -
Multiple updates on MySQL without overwriting data
I am using a jQuery sortable to sort the rows of my table. The new order gets saved in the backend and I am using python, Django. I have a column in my database called priority. This is how I handle the logic in the backend. the last array is a 2D list Basically, I want the following to happen: previous_order = [ 1,2,3,4,5 ] new_order = [3,4,5,1,2] orders_to_rearrange = [ ### gets passed in a function [1,3], [2,4], [3,5], [4,1], [5,2] ] ### UPPDATE the following: ### Priority 1 to become 3 ### Priority 2 to become 4 ### Priority 3 to become 5 ### Priority 4 to become 1 ### Priority 5 to become 1 The above is a pretty example, but when I encounter a complicated switch like this: ### Priority 5 to become 2 ### Priority 2 to become 4 ### Priority 4 to become 1 Notice how after 5 becomes 2, 4 becomes 2 and so did the previous 5. Now I end up having two priority 2 because it overwrites the statement inside the loop. I though that the WHEN THEN case statement in MySQL will help, but it ends up doing the same … -
Django Rest Framework: Function Based API serializers
Unsolicited for I've been put on an API-project where the requirements are: Django Django Rest Framework Python 3.5 API needs to be function based (so no classes) Where the goal is an API that returns data (so I only need 'Read' from CRUD-design principles) in JSON format for internal use by displays. Django itself has to connect to a default database and a legacy MYSQL data (this works). I've done so with the settings.py file. I then created a new application called museum_api; this works as well. After that I built my models of the legacy database with the help of python manage.py inspectdb --database=museum_data > models.py the above code generated a python file with classes for every table in the MYSQL database in the rootfolder called 'musart' of the project (this folder holds: manage.py, musart and museum_api.) Then I created a static JSON response by going inside of the folder called museum_api and created a file: views.py and urls.py I left these empty for a sec and went back to the root-folder and into the inner-project folder to edit the urls.py file in there. In that file I added: url(r'', include('museum_api.urls')), The intent is that the API is the … -
Django forward www.domain.com to domain.com with fastagi RewriteRule
I want to forward www.myapp.com to myapp.com. My current htaccess AddHandler fcgid-script .fcgi RewriteEngine on # Set up static content redirect: RewriteRule static/(.+)$ myapp-folder/public/static/$1 # The following two lines are for FastCGI: RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ application.fcgi/$1 [QSA,L] I tried adding below lines to above content RewriteCond %{HTTP_HOST} ^www.myapp.com$ [NC] RewriteRule ^(.*)$ http://myapp.com/ [R=301,L] But it doesn't give me the output I want. Without fastcgi I can just replace those lines since my app depends on it how can I add this forwarding without removing fcgi rule. -
running specific test case with python unittest in django
I have a set of unit tests that I can successfully run with: ./runtests.py wagtail.wagtailcore.tests But if I want to execute just one of them, I get an error that 'module' object has no attribute [test_case_name] My class would be something like: class TestPagePrivacy(TestCase): def test_anonymous_user_must_authenticate(self): so I would think you could just say: ./runtests.py wagtail.wagtailcore.tests.test_anonymous_user_must_authenticate Why doesn't this work? From the django docs: https://docs.djangoproject.com/en/1.11/topics/testing/overview/#running-tests # Run just one test method $ ./manage.py test animals.tests.AnimalTestCase.test_animals_can_speak -
Django ORM filter by Max column value of two related models
I have 3 related models: Program(Model): ... # which aggregates ProgramVersions ProgramVersion(Model): program = ForeignKey(Program) index = IntegerField() UserProgramVersion(Model): user = ForeignKey(User) version = ForeignKey(ProgramVersion) index = IntegerField() ProgramVersion and UserProgramVersion are orderable models based on index field - object with highest index in the table is considered latest/newest object (this is handled by some custom logic, not relevant). I would like to select all latest UserProgramVersion's, i.e. latest UPV's which point to the same Program. this can be handled by this UserProgramVersion queryset: def latest_user_program_versions(self): latest = self\ .order_by('version__program_id', '-version__index', '-index')\ .distinct('version__program_id') return self.filter(id__in=latest) this works fine however im looking for a solution which does NOT use .distinct() I tried something like this: def latest_user_program_versions(self): latest = self\ .annotate( 'max_version_index'=Max('version__index'), 'max_index'=Max('index'))\ .filter( 'version__index'=F('max_version_index'), 'index'=F('max_index')) return self.filter(id__in=latest) this however does not work -
Django Rest Framework MultipleChoiceField with dynamic options
So I just started using Django Rest Framework and one of my serializers has a MultipleChoiceField in which the choices are simply all the instances of another model. Here is the serializer in question: class ObjectTypeSerializer(serializers.ModelSerializer): def get_field_choices(): return sorted([ (p.id, p.name) for p in Parameter.objects.all() ]) object_fields = serializers.MultipleChoiceField( choices=get_field_choices() ) instance_fields = serializers.MultipleChoiceField( choices=get_field_choices() ) labels = serializers.SlugRelatedField( queryset=Label.objects.all(), many=True, allow_null=True, slug_field='name' ) class Meta: model = ObjectType fields = ('id', 'name', 'object_fields', 'instance_fields', 'labels') However, when I add a new Parameter object, the choices are not updated. In regular Django forms, I solved this simply using forms.ChoiceField(choices=[(p.id, p.name) for p in Parameter.objects.all()]) and it would update the choices when a new parameter is added without restarting the server. How can I accomplish the same thing with Django Rest Framework serializers? Any help is appreciated. Thanks! -
Django readonly form field does not appear in cleaned data
in my forms I changed this field to readonly class myForm(forms.Form): ... database = forms.CharField(label='Database', widget=forms.TextInput(attrs='style':'width:164px','readonly':'readonly'}), initial='production') I can see the initial value in the form on the browser, but then when I try to retrieve the values in the code def clean(self): cleaned_data = super(ReportForm, self).clean() print "CLEANED DATA ",cleaned_data database = cleaned_data['database'] # this throws an error The cleaned_data has all the other form items except the database it worked fine before adding attrs readonly -
django https 502 bad gateway
I am using nginx server with django. nginx.conf file user www-data; worker_processes auto; pid /run/nginx.pid; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; gzip_disable "msie6"; # gzip_vary on; # gzip_proxied any; # gzip_comp_level 6; # gzip_buffers 16 8k; # gzip_http_version 1.1; # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; ## # Virtual Host Configs ## include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } and the file in sites-available upstream app_server { server unix:/home/django/gunicorn.socket fail_timeout=0; } server { listen 80; server_name example.com; rewrite ^/(.*) https://example.com/$1 permanent; } server { listen 443 ssl default_server; listen [::]:80 default_server ipv6only=on; root /usr/share/nginx/html; index index.html index.htm; client_max_body_size 4G; server_name _ technocyan.com; ssl_certificate /home/django/example_cert_chain.crt; ssl_certificate_key /home/django/example.key; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_prefer_server_ciphers on; ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH'; keepalive_timeout 5; # Your Django project's media files - amend as required location /media { alias /home/django/django_project/myapp/media; } # your Django … -
Idiom for script directory in python application?
I have a python application (Django based), and I have a couple of standalone maintenance scripts that go along with the application, that I have to call every now and then. They have to import parts of my application (sub-packages). Currently, I just put them in my toplevel directory: application/ djangoproject/ djangoapp/ otherpackage/ tool1.py tool2.py Where tool1.py would do from djangoproject import wsgi from djangoapp.models import Poll I've accumulated quite some of these tools, and would like to move them to a scripts subdirectory. Then, I would like to be able to call them via python scripts/tool1.py or maybe cd scripts; python tool1.py. I understand (and sometimes lament) how Python's imports work, and I know that I can add some lines to each script to add the parent directory to PYTHONPATH. I am wondering if there is a widespread pattern to handle such a collection of assorted scripts. Maybe one could put the path manipulation into another file, and have every script start with import mainproject? I am using a virtualenv, and installing dependencies with pip. But the application itself currently doesn't use a setup.py, and I think it wouldn't help to move the scripts to a separate package installed … -
What does request_source do in a Django template
I am picking up some old Django code and am puzzled by a line in the site's master template. After a series of {% load xxx %} lines there is the line {% request_source 849051 %} I have been unsuccessful in finding any documentation for this command. Is it a standard template command? Or is it something custom to this code, and if so where would I likely find the implementation? The site was written for Django 1.5.12 if that makes a difference. -
How and where to format date in Django (Python, Ajax)?
Can I format the date in the foreach loop ? advertisements_list = [] for advertisement in advertisements: advertisements_list.append({ 'id': advertisement.id, 'description': advertisement.description, 'title': advertisement.title, 'picture_url': advertisement.image.url, 'date': advertisement.date -> format that }) In my template I would do something like {{ advertisement.date | date:"d.m.Y" }}. Is there something similiar which I can use in my foreach-loop ? I can not go the template way because it is Ajax. Is it even the right place for formatting or should I do the formatting with JavaScript/jQuery when I passed the data ? -
"utf-8" encoding works on development server but not when deployed
My django application hosted at pythonanywhere.com does not support utf-8 encoding. Characters like 'é' returns error. Views: def result_view(request): if request.method == 'POST': search= request.POST.get('textfield').encode("utf-8") print search try: try: value = wikipedia.page(search) title= value.title url=value.url print title data= wikipedia.summary(search, sentences=10) except wikipedia.exceptions.DisambiguationError as e: data = e title=search+" (Disambiguation)" u = search.replace(" ", "_") url = "https://en.wikipedia.org/wiki/"+u except: raise Http404() return render(request,"search/result.html",{'title':title,'url':url,'data':data}) else: return render(request,"search/result.html",{}) The textfield input is encoded with utf-8 and works fine in Django development server but returns 404 page in my pythonanywhere server. Template: <form name="myform" method="POST" action="{% url 'result' %}"> <div class="form-group"> <div class="input-group"> {% csrf_token %} <input type="text" class="form-control" name="textfield" placeholder="Search" required /> <div class="input-group-addon"> <span class="glyphicon glyphicon-search"></span> </div> </div> </div> <button type="submit" class="btn btn-danger btn-lg ">Search</button> </form> -
How to make django work with RTSP?
I searched everywhere but couldn't find an answer How can i make django work with RTSP. How to start the process of building an RTSP server and then connecting users to a particular stream. -
Python Django Load Images based on Tab Clicked
I am using bootstrap with nav-tabs to hopefully select filtered images based on the tab clicked. I can do an AJAX call to the view that I created that filters out the images based on category and returns an items.html template file. Is there a way to load the partial template without having to reload the entire page? Should I just do the AJAX call and it will update that partial view? -
How to upload image in react native?
Hi everyone i am trying unsuccessfully to upload image to my backend server (build with Django/python). When i try with postman it work well, but my code does not work. That is it: const data = new FormData(); data.append('id_pharma',13 ); // you can append anyone. data.append('name', { uri: this.state.photo.uri, type: 'image/png', // or photo.type filename: 'image.png' }); data.append('Content-Type', 'image/png'); fetch(config.base_url+'upload/', { method: 'post', body: data, headers: { "Content-Type": "multipart/form-data" } }).then(res => { console.log(res) }).catch((err)=> { this.setState({error_text: 'Echec de l\'ajout image', is_adding: false}) }); It is a REST API, and it is responding as django.utils.datastructures.MultiValueDictKeyError: "'name'" It seem like data is not going, please what am i doing wrong ?? (Sorry for my english) -
Best practise for package install on django server
So I'm setting up a server by myself. Now I ran into lots of different ways where to install the packages. I am thinking of the core packages like nginx, gunicorn, python3, postgresql and so on. I learned that setting up a VENV (virtual environment) is a good thing so I can have several projects running with different versions on packages. But it's a bit confusing wich ones are not going to be inside the VENV. Some install postgreSQL outside the VENV, but psycopg2 inside. Some the gunicorn inside VENV. and so on. Is there any best pratices or rules that are better safe to follow? For info. I'm setting up a Ubuntu server 16.04 with Nginx, gunicorn. PostgreSQL, psycopg2, python3 -
Which DRF generic view should be used for validating login credentials?
Just a quick question. All of my views are very redundant and just use APIView. Trying to clean it up by using generic views. Someone recommended using CreateAPIView for such things as credential verification, which didn't seem right. As expected, it tries to create the user when you provide credentials. http://www.django-rest-framework.org/api-guide/generic-views/#createapiview So just trying to find out which generic view should be used for verifying credentials passed to it from the front-end. Seems like RetrieveAPIView, but it is a get so seems like it would return the credentials which is not good. http://www.django-rest-framework.org/api-guide/generic-views/#retrieveapiview -
Can't make WhiteNoise work with Django & Heroku for production
I'm trying to reproduce a production website on Heroku, and to do that I followed step-by-step these 3 guides below: http://whitenoise.evans.io/en/stable/django.html https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Deployment devcenter.heroku.com/articles/django-assets Since I'm using Django 1.11, I don't know if I need to do something different from these guides. Part of my production.py(same as settings.py but only for production) looks like this: DEBUG = bool( os.environ.get('DJANGO_DEBUG', True) ) ALLOWED_HOSTS = ['(((MY WEBSITE))).herokuapp.com'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ # 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] And the bottom of production.py STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), '/var/www/static/', ] STATIC_URL = '/static/' CORS_REPLACE_HTTPS_REFERER = True HOST_SCHEME = "https://" SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_SECONDS = 1000000 SECURE_FRAME_DENY = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True SECURE_HSTS_PRELOAD = True X_FRAME_OPTIONS = 'DENY' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' Everything works fine when the DEBUG = True, but when I set DEBUG = False I get a Server Error (500) meaning it's something wrong with Django and/or WhiteNoise while handling the staticfiles but I really don't know where is the problem. Other relevant files: Procfile (required for heroku) web: gunicorn … -
Changing the primary key of a model in django back to default, even when the model has dependencies with other model?
I have a django model (say model1) where I have my own primary key, but now I want to change the primary key to default id field. But the problem if I try to change is, I have another model (say model2) which has many to many dependency to the model1 and it is causing errors when I am trying to modify the field. Is there any way I can change the primary key of this model? ex: class model2(models.Model): id = .. ... model1 = models.ManyToManyField("model1", blank=True) classs model1(models.Model): Name = models.charField(primary_key=True, max_length=280) .. Now I want to change the primary key of model1 back to Id.