Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CSV File read in Python 3 and Django
im writing a Webapp with Django and im trying to open a csv fiel. On my local maschine that was no problem(there i used python2.7 or something). On the Server is Python 3 installed and i get an Error: '_io.BufferedReader' object has no attribute 'xreadlines' But i didnt use this "xreadlines"... with open(os.path.dirname(__file__) + '/../***.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=';') for row in readCSV: #... What im doing wrong? -
Django query objects using non related models
I have these 3 models: class Person(models.Model): name age class Person_Address(models.Model): address number city state person = models.ForeignKey(Person) class State_Schedules(models.Model): state hour I also have a models.QuerySet for the State_Schedules for filtering based on current time (basically the contactables() below). How can I get the Person objects comparing it's state in django? I tried this but it seems cumbersome having to fetch the Persons using their Person_Address. persons = Person_Address.objects.select_related('person').filter(state__in=(_.state for _ in State_Schedules.objects.contactables())) Is there a better approach or I'd have to resort to raw sql? -
How do you cleanly maintain django migrations on non-master branch?
Imagine that I have a branch that has a migration. It's an experimental branch that keeps up with master, but will not be merged into it for a while, if ever. Master migrations change over time. The result is that when I merge in master, I end up with multiple migration leaves, meaning that manage.py migrate errors out. If I just do manage.py makemigrations --merge, then it creates a new leaf that will later also be out of date. Is there a nice way to handle this? I'm tempted just to avoid having any migrations in long-lived dependent branches. -
How to POST Model with Many to Many through in Django REST
I have a model with a many to many connection. I would like to make this model available in Django REST. By default such a model is read only, but I would also like to write. Furthermore, it would be great to get the information of the through connection integrated into the GET as a nested model. ... class KeyDateCase(models.Model): ... diagnoses_all_icd_10 = models.ManyToManyField( 'common.ICD10', through='CaseICD10Connection') ... class CaseICD10Connection(models.Model): case = models.ForeignKey('KeyDateCase', on_delete=models.CASCADE) icd_10 = models.ForeignKey('common.ICD10', on_delete=models.CASCADE) is_primary = models.BooleanField(default = False) certainty = models.CharField( max_length=1, choices=CERTAINTY_CHOICES, default='G', ) class KeyDateCaseViewSet(viewsets.ModelViewSet): ??? class KeyDateCaseSerializer(serializers.ModelSerializer): ??? How can I achieve this? What should my view and serializer look like? -
Django mapping to Postgres citext array returns a str instead of a list
I have a Django model with an array of aliases based on citext. When I retrieve a record, instead of a list ['foobar'], I am getting a str '{foobar}' and obviously, trying to add an alias fails. I used to have: from django.db import models class zone(models.Model): name = models.CharField(max_length=255) aliases = ArrayField( models.TextField(max_length=255, blank=True), size=4, null=True, blank=True, ) That was working fine but since I needed to make it case insensitive, I changed the TextField to CITextField: from django.contrib.postgres.fields import ArrayField, CITextField from django.db import models class zone(models.Model): name = models.CharField(max_length=255) aliases = ArrayField( CITextField(max_length=255, blank=True), size=4, null=True, blank=True, ) The result: item = zone.objects.filter(name__iexact='foo') print(type(item), item.aliases) >> <class 'str'> {"foobar"} Any idea on why this citext would not be decoded as an array rather than a plain string ? -
Django unittesting different databases for api and for test
By default django creates a test database when running tests which raises some inconvenience for me: The API that i am writing test for uses a database. When i run the test, a new database is created, some dummy data is being inserted into the test database and a http post request is being sent to the API under test. What happens is that my API under test does not see inserted data. With the problem explained, what are the right solutions / best practices for testing APIs with databases ? -
Test django project with native unittest lib
Is it possible not to use a unit test tool provided by Django but use native python unittest library? I know that for simple tests it works just fine. But when i involve other apps and models into the test i get various exceptions like 'apps are not loaded yet and so on'. So is there a workaround to test django project with unittest lib that works in most cases ? -
Dynamically changing html element's class in jquery mobile
I have a page i created using jquery mobile, the challenge i am having is how to add the ui-btn-active class to an anchor element on the page's navbar without directly doing that on the html. I tried adding that in a javascript function that should be executed after the page is loaded but the function gets called without the desired changed being effected. It however seems that the element gets the class added when i reload the page. Is there a way of doing that without reloading the page manually? Or do i need to add a function that automatically reloads the page each time a new page is fetched? -
Looping through directory and creating models
For each sound - sound1, sound2, sound3... - I have each sound being spoken by a female and male speaker. So, in my directory, I have files such as F_sound1.wav, M_sound1.wav, F_sound2.wav, M_sound2.wav. I want to create a model for each sound like: Sounds.objects.create(sound="soundname", male='malefile', female='femalefile'); I coded: for filename in os.listdir("DIRECTORY"): if filename.endswith(".wav"): start = filename.index("_") end = filename.index(".") soundname = filename[start+1:end] # find files and create model here? to extract the soundname from each file so I can create a list of all the sound names. However, since all the sound files (for male and female) are all lumped in the same folder, I'm not sure how to find the relevant files and where in the function I should create the model. Could someone give me some tips on this part? Thank you! -
Django Python and pyad
I am trying to create a simple search form in Django to query Active Directory but I keep getting com_error at /console/users/ (-2147221008, 'CoInitialize has not been called.', None, None) views.py: from pyad import pyad, aduser, adquery @login_required def users(request): if request.method == 'POST': form = UserSearchForm(request.POST) if form.is_valid(): user = pyad.from_cn(form.cleaned_data['cn']) return render(request, 'console/users/details.html', {'user': user}) else: form = UserSearchForm() return render(request, 'console/users/index.html', {'form': form}) forms.py from django import forms class UserSearchForm(forms.Form): cn = forms.CharField(label='Common Name', max_length=100) Python 3.6. Django 2.0.3 pyad 0.5.20 -
can't find data in django
i hava some question for help,it's about django orm with mysql this is my models.py from django.db import models #电影列表 class Movieinfo(models.Model): movienum = models.IntegerField(primary_key=True) moviename = models.CharField(max_length=100) movierelease_time = models.CharField(max_length=20) movietype = models.CharField(max_length=100) class Meta: ordering = ["movienum"] def __str__(self): return self.moviename #短评论 class Moviescritic(models.Model): movieinfo = models.ForeignKey(Movieinfo) movienum = models.IntegerField() moviescrit= models.TextField() class Meta: ordering = ["movienum"] def __str__(self): return self.moviescrit #长影评 class Movielcritic(models.Model): movieinfo = models.ForeignKey(Movieinfo) movienum = models.IntegerField() movielcrittitle = models.TextField() movielcrit = models.TextField() class Meta: ordering = ["movienum"] def __str__(self): return self.movielcrit this is my views.py import logging from django.http import HttpResponse from django.views.generic import DetailView from django.template import loader from yingping.models import Moviescritic logger = logging.getLogger('__name__') def cdview(request): template = loader.get_template('worldcloud.html') movie_shu = Moviescritic.objects.filter(movieinfo__movienum='10014') content = { 'movie_shu':movie_shu, } return HttpResponse(template.render(content,request)) but i can't find any data in html,Is my understanding of django onetomany wrong? {% block worldcloud %} {% if movie_shu %} {% for x in movie_shu%} <p>{{x}}</p> {% endfor %} {% else %} print("err") {% endif %} <!--SERVICES SECTION END --> {% endblock %} the html just find print("error"),when i find data in itself table i can find data in HTML. so what's wrong with me -
Search through context in custom templatetag
I am currently in the process of reducing my template code by using custom templatetags. I am essentially passing the context from the view to the tag and then rendering that into a shared template. I have come up against a problem that I have been unable to solve, however. The context of the views I am passing to the tag each contain a key which ends in '_collection'. Essentially, I need to go through the context and find the key/value pair that corresponds to that substring and then map it to the tag context. Here is the templatetag I am using: from django import template register = template.Library() @register.inclusion_tag('main/collection.html', takes_context=True) def collection(context): ctx = { 'is_create': context['is_create'] } if '_collection' in context: # not sure how to get this into the context return ctx Basically I just want to correctly map that value to the templatetag context by using that substring. Any help would be much appreciated. Thanks for your time. -
django2.0 iexact translate to like not ilike
i have a model like this: class Article(models.Model): title = models.CharField(max_length=200) content = models.TextField() class Meta: db_table = 'article' and i write query: articles = Article.objects.filter(title__iexact='hello world') print(articles.query) the output is: SELECT ... FROM `article` WHERE `article`.`title` LIKE hello world you can see iexact is translated to like.but django document say it will translate ilike, who are wrong? by the way: my mysql collation is utf8_bin. mysql is serviced on ubuntu. code is running on windows. -
Internal Server Error djangosaml2 login from React-Native Webview
Error Message: "Internal Server Error: /saml2/acs/" Connecting to my IdP using React-Natives Webview Component. After logging in, I am beeing redirected to my website, and the djangosaml2 library should log in the user. Here I get the Internal server error. The login is working when using chrome, but not from the React-Native app. I am using react-native-cookies, and all the cookies seems to be deleted when redirected to my website. Any help is greatly appreciated :) The whole error message: Internal Server Error: /saml2/acs/ Traceback (most recent call last): File "/home/tpweb/webapps/dev_tpdjango/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 132, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/tpweb/webapps/dev_tpdjango/venv/lib/python3.5/site-packages/django/views/decorators/http.py", line 45, in inner return func(request, *args, **kwargs) File "/home/tpweb/webapps/dev_tpdjango/venv/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/home/tpweb/webapps/dev_tpdjango/venv/lib/python3.5/site-packages/djangosaml2/views.py", line 253, in assertion_consumer_service outstanding_queries) File "/home/tpweb/webapps/dev_tpdjango/venv/lib/python3.5/site-packages/saml2/client_base.py", line 597, in parse_authn_request_response binding, **kwargs) File "/home/tpweb/webapps/dev_tpdjango/venv/lib/python3.5/site-packages/saml2/entity.py", line 1140, in _parse_response response = response.loads(xmlstr, False, origxml=origxml) File "/home/tpweb/webapps/dev_tpdjango/venv/lib/python3.5/site-packages/saml2/response.py", line 534, in loads "Unsolicited response: %s" % self.in_response_to) saml2.response.UnsolicitedResponse: Unsolicited response: None Request repr(): <WSGIRequest path:/saml2/acs/, GET:<QueryDict: {}>, POST:{'RelayState': 'https://tptest.teknologiporten.no/', 'SAMLResponse': 'PHNhbWxwOlJlc3BvbnNlIHhtbG5zOnNhbWxwPSJ1cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6cHJvdG9jb2wiIHhtbG5zOnNhbWw9InVybjpvYXNpczpuYW1lczp0YzpTQU1MOjIuMDphc3NlcnRpb24iIElEPSJfNzc4NmVjMGJkNjQxMTg2OGU2Y2UwYjkwZjczOTE0YjAwMjM5OGJlMDVlIiBWZXJzaW9uPSIyLjAiIElzc3VlSW5zdGFudD0iMjAxOC0wNC0wM1QxMzoxOTowOVoiIERlc3RpbmF0aW9uPSJodHRwczovL3RwdGVzdC50ZWtub2xvZ2lwb3J0ZW4ubm8vc2FtbDIvYWNzLyI+PHNhbWw6SXNzdWVyPmh0dHBzOi8vaWRwLXRlc3QuZmVpZGUubm88L3NhbWw6SXNzdWVyPjxzYW1scDpTdGF0dXM+PHNhbWxwOlN0YXR1c0NvZGUgVmFsdWU9InVybjpvYXNpczpuYW1lczp0YzpTQU1MOjIuMDpzdGF0dXM6U3VjY2VzcyIvPjwvc2FtbHA6U3RhdHVzPjxzYW1sOkFzc2VydGlvbiB4bWxuczp4c2k9Imh0dHA6Ly93d3cudzMub3JnLzIwMDEvWE1MU2NoZW1hLWluc3RhbmNlIiB4bWxuczp4cz0iaHR0cDov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dIAK6yok6KSBO0DOl2IVsWQ2Sl', 'DOCUMENT_ROOT': '/usr/local/apache2/htdocs', 'GATEWAY_INTERFACE': 'CGI/1.1', 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate', 'HTTP_CACHE_CONTROL': 'max-age=0', 'HTTP_CONNECTION': 'close', 'HTTP_FORWARDED_REQUEST_URI': '/saml2/acs/', 'HTTP_HOST': 'tptest.teknologiporten.no', 'HTTP_HTTPS': 'on', … -
Django Loop condition html
How can i achive that buttons on default are green when the student is available, but when they are taken (added into the classList) then the button turns red. {% for student in studentList %} <tr> <td>{{ student.firstname }}</td> <td>{{ student.lastname }}</td> <td>{{ student.teacher }}</td> {% for class in classList %} {% if student.id == class.student_id and class.week == 14 %} <td><a href="#" class="btn btn-danger" role="button">Not Available</a></td> {% else %} <td><a href="#" class="btn btn-success" role="button">Book Student</a></td> {% endif %} {% endfor %} </tr> {% endfor %} So imagine, all the students are available for now, but as soon they are booked (appears inside the classroom list) the button for those students should be red. As it now, it query the database and looks for the correct details. But if the classroom list is bigger than 1, then the loop create buttons all over the place. Instead only place buttons due to the if condition. Image -
Django render view based on choice of radio button
I have a django project where I have to render view according to the choice selected in radio button i.e if student is selected it has to go to one page and if faculty is selceted it should go to another page forms.py DISPLAY_CHOICES = ( (1, "Student"), (2, "Faculty") ) class Wru(forms.Form): display_type = forms.ChoiceField(widget=forms.RadioSelect, choices=DISPLAY_CHOICES) views.py def index(request): form=Wru(request.POST) if request.method == 'POST': if form.is_valid(): if form.fields['display_type'].choices[1]: return home(request) else: return simple_upload(request) return render(request, 'acads/index.html', {'form': form}) -
Django, ManyToMany field
I have two models in my blog app: class Tag(models.Model): tag_name = models.CharField(max_length=20, null=True) def __str__(self): return self.tag_name class Post(models.Model): tag = models.ManyToManyField(Tag, related_name="blog_tag", blank=True) In views i have: tags = Tag.objects.all() And post = get_object_or_404(Post, status="published", publish__year=year, publish__month=month, publish__day=day, slug=post) So my question is - how can i filter tags by post ? I mean that i want to show only tags what i add to my post. I tried to do than in template , but something dosen't work : {% for tag in tags %} {% if tag in post %} <div> {{ tag.tag_name }} </div> {% endif %} {% endfor %} -
Deploy Django backend on google cloud gives error on console but no error in logs
I am trying to deploy my django backend rest apis on GCP by following the google tutorial at https://cloud.google.com/python/django/flexible-environment I was able to deploy sample app successfully but when I am trying to deploy my django app then I get below errors: latest: digest: sha256:d43a6f7d84335f8d724e44cee16de03fd50685d6713107a83b70f44d3c6b5e8f size: 2835 DONE ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Updating service [default] (this may take several minutes)...failed. ERROR: (gcloud.app.deploy) Error Response: [9] Application startup error: [2018-04-03 13:01:35 +0000] [1] [INFO] Starting gunicorn 19.7.1 [2018-04-03 13:01:35 +0000] [1] [INFO] Listening at: http://0.0.0.0:8080 (1) [2018-04-03 13:01:35 +0000] [1] [INFO] Using worker: sync [2018-04-03 13:01:35 +0000] [7] [INFO] Booting worker with pid: 7 [2018-04-03 13:01:35 +0000] [1] [INFO] Shutting down: Master [2018-04-03 13:01:35 +0000] [1] [INFO] Reason: Worker failed to boot. In build history, it shows success: Build information Status Build successful Build id b2f2ab39-18df-420e-8fac-eeda74dc7a75 Image eu.gcr.io/bcbackend-200008/appengine/default.20180403t182207:latest Trigger — Source gs://staging.bcbackend-200008.appspot.com/eu.gcr.io/bcbackend- 200008/appengine/default.20180403t182207:latest Started April 3, 2018 at 6:23:32 PM UTC+5:30 Build time 6 min 13 sec In GCP logs also it shows no error but "Worker failed to boot": A 2018/04/03 13:01:32 Ready for new connections A 2018/04/03 13:01:33 Listening on /cloudsql/bcbackend-200008:europe- west3:bc-mysql-instance for bcbackend-200008:europe-west3:bc-mysql-instance A [2018-04-03 13:01:35 +0000] [1] [INFO] Starting gunicorn 19.7.1 A [2018-04-03 13:01:35 +0000] [1] [INFO] Listening at: http://0.0.0.0:8080 … -
How can I make 'index.html' redirect to wagtail page
I'm replacing a static site with wagtail. The static site has urls, but also exposes index.html for each page. How can I easily remove the /index.html and have this redirect to the wagtail page ? -
502 Bad Gateway nginx, I have one dominion for two distinct apps (FLASK and DJANGO). I'm using one index page to distribute routes
I think this erros happens, because of proxy_pass is incorrect, if someone has any idea please tell me thanks NGINX FILE proxy_cache_path /var/nginx/cache/project keys_zone=djangoproject_cache:60m; gzip on; gzip_proxied any; gzip_types text/plain text/xml text/css application/javascript application/x-javascript; gzip_vary on; gzip_disable msie6; upstream appserver { server unix:/home/dir/projects/djangoproject/gunicorn.sock fail_timeout=0; } server { listen 80; listen [::]:80 default_server; return 301 https://$host$request_uri; } server { listen 443; server_name www.subdominion.dominion www.subdominion.dominion; add_header X-Frame-Options "SAMEORIGIN"; ssl_certificate certificate.crt; ssl_certificate_key certificate.key; ssl on; server_tokens off; root /var/www/html/; index index.html index.htm; location / { try_files $uri $uri/ =404; } location /djangoproject{ proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; # Fix the “It appears that your reverse proxy set up is broken" error. rewrite ^/djangoproject(.*) /$1 break; proxy_pass http://unix:/home/sftpserver/projects/podaexpress/gunicorn.sock; -- I think the error is here try_files $uri @proxy_to_appserver; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; sendfile_max_chunk 1024k; root /home/dir/projects/djangoproject/static; proxy_read_timeout 90; } location /flaskproject{ proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; # Fix the “It appears that your reverse proxy set up is broken" error. rewrite ^/flaskproject(.*) /$1 break; proxy_pass http://unix:/home/dir/projects/flaskproject/gunicorn.sock; proxy_read_timeout 90; } location @proxy_to_appserver { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header REMOTE_ADDR $remote_addr; proxy_redirect off; proxy_pass … -
How to get Google Recaptchas at the bottom of a form?
Even though I put my recaptcha at the bottom of my form (after every other input), it still stays at the top of the form. Why is this and any idea how I can get around this problem? <form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}"> {% csrf_token %} {{ form.as_p }} {{ form.captcha }} {{ form.captcha.errors }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <button type="submit">{% trans "Sign Up" %} &raquo;</button> </form> -
django objects.all() vs objects.filter()
Queryset.objects.all() return all objects and also, Queryset.objects.filter() return all objects too. I have two query that use Queryset.objects.filter() and i want to use it for return all objects. Question: Are both Queryset.objects.all() and Queryset.objects.filter() performance the same? -
django redirect after delete
After deleting an object from my DB I want to redirect to a certain view. here is my view where the deletion happens: def client_delete(request): if request.method == 'GET': return _not_exist_page(request) else: client = Client.objects.get(id=request.POST['id']) client.delete() print('deleted') return redirect('clients:index') print('deleted2') when I delete an object here's what I see on the terminal: deleted [03/Apr/2018 15:55:50] "POST /clients/delete/ HTTP/1.1" 302 0 [03/Apr/2018 15:55:50] "GET /clients/ HTTP/1.1" 200 7467 it means that the redirect is triggered(and that's why the second print doesn't show up) but view in my browser doesn't change. Any idea why that happens? Thanks -
How to make database of sounds in Django?
class Migration(migrations.Migration): dependencies = [ ('app', '0001_initial'), ] operations = [ migrations.CreateModel( name='Sounds', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('sound', models.TextField(blank=True, max_length=500)), ('male_one', models.TextField(blank=True, max_length=500)), ('male_two', models.TextField(blank=True, max_length=500)), ('female_one', models.TextField(blank=True, max_length=500)), ('female_two', models.TextField(blank=True, max_length=500)), ], ), ] So this is code that someone else started, and I'm supposed to finish it - the end goal is a database of audio files. Each sound has four files each by a different speaker - male 1, male 2, female 1, female 2. I'm not sure where to insert the individual sound files into this model. If I have a folder "/app/sounds" with four different folders for each speaker, could someone give me an example of how to create a simple database (maybe by looping through the folder?). -
How to convert a Function based view into a Class based View in django
I was doing some research about function vs class based views and I found out that class based views are quite efficient. I have the following code snippet and would like to convert the function based view into class based view. How do I implement this correctly? @api_view(['GET']) def get_payslip_detail(request, pk, format=None): try: payslip = list(Payslip.objects.filter(id=pk).values( 'payment_mode','payslip_no','month_ending','basic','id','employee' ))[0] # accesss object from list above # access from object get id which is an integer >>>>> id=payslip['employee'] employee = list(Employee.objects.filter(id=payslip['employee']).values( 'user','hr_number','basic','tax_id_number', 'department', 'designation','id'))[0] payslip['emp'] = employee bank_acc = list(BankAccount.objects.filter(account_owner=payslip['employee']).values( 'bank_acc_number','bank_id' ))[0] # append extra key to emp payslip['acc_no']= bank_acc['bank_acc_number'] bank_name= list(Bank.objects.filter(id=bank_acc['bank_id']).values('name'))[0] # print(bank_name) payslip['bank_name'] = bank_name['name'] allowances = Allowance.objects.filter(payslip=pk).values('amount','name') deductions = Deduction.objects.filter(payslip=pk).values('amount','name') payslip['allowances'] = list(allowances) payslip['deductions'] = list(deductions) payslip['total_allowances'] = allowances.aggregate(net_allowance=Sum('amount'))['net_allowance'] payslip['total_deductions'] = deductions.aggregate(net_deduction=Sum('amount'))['net_deduction'] payslip['netpay'] = (payslip['total_allowances']+int(employee['basic']))-payslip['total_deductions'] except Exception as e: # print(e) return Response(data=e, status=status.HTTP_400_BAD_REQUEST) return Response(data=payslip, status=status.HTTP_200_OK)