Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django router forgets the DB while pointing to ForeignKey
My mobileapp is going to be used by different schools( with different db but same structure).Logged in user(parent) will be connected with multiple db(if their two child in different schools) using DynamicDbRouter. Now the problem is django router forgets the DB while pointing to ForeignKey. views.py class StudentFees(LoginRequiredMixin,TemplateView): template_name = 'student_fees.html' def get_context_data(self,**kwargs): context = super(StudentFees,self).get_context_data(**kwargs) schl_id=kwargs['schl_id'] school_id=School.objects.get(id=kwargs['schl_id']) with in_database(school_id) : context['classes'] = StudentSection.objects.filter(student_detail=kwargs['student_id']) context['invoices'] = Invoice.objects.filter(student_master=kwargs['student_id'],status=1) print context return context Here student_detail & student_master are foreign key fields. routers.py class in_database(object): def __init__(self, client, read=True, write=False): ... database = {'ENGINE':'django.db.backends.mysql','NAME':client.db_name,'USER':client.username,'PASSWORD':client.password,'HOST':client.host,'PORT':client.port} ... Instead of pointing to client_db.model it points to default_db.model while accessing foreign keys. I can able to see context details in console.. but values not redering in student_fees.html. It throws error like ProgrammingError : default_db.studentsection' doesn't exist -
Gunicorn & django sock file not created
Setting up django with nginx and gunicorn I've been able to have it serve static files but brings a 502 on django. The site runs okay with runserver 0.0.0.0:8000 I've also worked on uwsgi before, I don't think the two (gunicorn and uwsgi) are conflicting however. When I run gunicorn status check I get ubuntu@ip-172-31-16-133:~$ sudo systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Tue 2017-01-31 10:36:23 UTC; 4min 20s ago Process: 32261 ExecStart=/home/ubuntu/djangoenv/bin/gunicorn --workers 10 --bind unix:/home/ubu Main PID: 32261 (code=exited, status=203/EXEC) Jan 31 10:36:23 ip-172-31-16-133 systemd[1]: Started gunicorn daemon. Jan 31 10:36:23 ip-172-31-16-133 systemd[1]: gunicorn.service: Main process exited, code=exited, Jan 31 10:36:23 ip-172-31-16-133 systemd[1]: gunicorn.service: Unit entered failed state. Jan 31 10:36:23 ip-172-31-16-133 systemd[1]: gunicorn.service: Failed with result 'exit-code'. and the error log reads 2017/01/31 10:36:31 [crit] 32205#32205: *7 connect() to unix:/home/ubuntu/webapps/kenyabuzz/gunicorn.socket failed (2: No such file or directory) while connecting to upstream, client: 105.231.127.174, server: kenyabuzz.nation.news, request: "GET / HTTP/1.1", upstream: "http://unix:/home/ubuntu/webapps/kenyabuzz/gunicorn.socket:/", host: "kenyabuzz.nation.news" Here's the conf file #kb gunicorn nginx settings server { listen 80; server_name kenyabuzz.nation.news; charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media … -
Pytho Django: how to select the index type?
As stated in https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.Field.db_index, you can add indexes to your table using db_index=True. But how do you force hash vs btree indexes? -
Does form_valid on a CreateView in django roll back a save if an error occurs?
I have a CreateView for a ModelForm with a form_valid() method, which calls form.save() quite early on (so that I can get the object's ID), then goes on to do some other stuff (create some related objects, and send some emails). def form_valid(self, form): context = self.get_context_data() preferences_formset = context['preferences_formset'] if preferences_formset.is_valid(): student = form.save() ... send_email_one() send_email_two() send_email_three() return HttpResponseRedirect(self.get_success_url()) I recently discovered that some of the later processing had some errors resulting in an unhandled exception in some cases when send_email_three is called. I can see from my logs that send_email_one and send_email_two are being called, and the exception occurs in send_email_three. However, when this has occurred, I can't find the objects in the DB. I was under the impression that form.save() should create and save the object in the DB - is this the case or does it roll back the save if the form_valid function errors out at a later point? I'm using django 1.8.2 PS: Yes, I know I should have the emails in a deferred task; that will be implemented later. -
Django Save DB into Docx and Download to Client
I am trying to write the Django (1.10) database data to a Word document and export it to the client machine. I think I have done the first part by putting the db data into a new docx. However, I failed to export it by saving it into docx. The Django did not do anything when I initialize the process. I am wondering what has gone wrong and could anyone advise how to fix it? My code is as below for your reference. Many thanks. views.py: def admin_export(request): from io import StringIO, BytesIO from docx import * document = Document() docx_title="Report.docx" document.add_paragraph('Downloaded Reports') for sel_id in in_news: document.add_paragraph() document.add_paragraph(str(getattr(db_article.objects.get(id=sel_id), 'Article'))) f = BytesIO() document.save(f) length = f.tell() f.seek(0) response = HttpResponse( f.getvalue(), content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document' ) response['Content-Disposition'] = 'attachment; filename=' + docx_title response['Content-Length'] = length return response -
Install Django project on Ubuntu distant server
I'm trying to install my Django project from my MacOSX localhost to an ubuntu distant server. I'm getting a problem with Apache in order to display my project. This is some steps that I've done : Create an ubuntu distant server with IP adress : 172.30.10.58 Copy/Paste my Django project to /var/www/html/ Install Apache2 Install all Django modules (it's ok because if I run python manage.py runserver, I don't get error) I followed some tutorials : Running django project on apache in ubuntu So my /etc/apache2/sites-available/000-defaut.conf looks like : <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost ServerName etat_civil.com ServerAlias www.etat_civil.com DocumentRoot /var/www/html/etat_civil/ Alias /static/ /var/www/html/etat_civil/BirthCertificate/static/ Alias /uploads/ /secure_dir/uploads/ WSGIDaemonProcess daemon-etat_civil user=www-data group=www-data processes=1 maximum-requests=1 … -
custom login page is not working
IF i call this url: http://www.payallpayments.com/ login page is not showing. IF i call this url: http://www.payallpayments.com/login login page is showing. How to make it. IF i call this url: http://www.payallpayments.com/ login page will show. How can i achieve that? uthtest/urls.py #!python # authtest/urls.py from django.conf.urls import include, url from django.contrib import admin # Add this import from django.contrib.auth import views from log.forms import LoginForm urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'', include('log.urls')), url(r'^login/$', views.login, {'template_name': 'login.html', 'authentication_form': LoginForm}, name='login'), url(r'^logout/$', views.logout, {'next_page': '/login'}), ] log/urls.py #!python # log/urls.py from django.conf.urls import url from . import views #from .views import Home,success,failure # We are adding a URL called /home urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^$', views.login, name='login'), url(r'^recharge/$', views.recharge, name='recharge'), url(r'^recharge/payment/$', views.payment, name='payment'), ] -
Saving content to Django models fail -
I have been trying to save a form content to a model, but I always end up with three errors which lead to another editor.models.DoesNotExist: ContentModel matching query does not exist. sqlite3.IntegrityError: UNIQUE constraint failed: editor_contentmodel.ref_id django.db.utils.IntegrityError: UNIQUE constraint failed: editor_contentmodel.ref_id model.py class ContentModel(models.Model): ref_id = models.CharField(primary_key=True, max_length=120, default='1', unique=True) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) def __str__(self): return self.content class Meta: unique_together = ("content", "ref_id") views.py def index(request): template = "editor/home.html" try: json_content = ContentModel.objects.get(ref_id='1') except Exception: raise HttpResponseServerError if request.method == 'POST': form = ContentFormModel(request.POST) if form.is_valid(): ref_id_new = '1' form_data = form.cleaned_data.get('content') new_content, created = ContentModel.objects.get_or_create(content=form_data) if created: new_content.ref_id = ref_id_new new_content.save() else: form = ContentFormModel() context = {'content': json_content.content, 'form': form} return render(request, template, context) forms.py class ContentFormModel(forms.ModelForm): class Meta: model = ContentModel fields = ['content'] I am not sure whats wrong in the code. Is it because the ref_id is a primary key? Update I am using Django 1.10 on Python 3 -
Django Debug=False whitenoise/static files stop working
I am trying to deploy my fully functional (when local and Debug=True) site to Heroku. When I use the default Django staticfile_storage settings, my site appears live but without any static files (css, images, etc). The admin panel works but it doesn't have any styles either. But, when I try to use Whitenoise, which is what I originally intended, I get a server 500 error. The admin panel will not work then. I can't figure out for the life of me what I am doing wrong. I have tried to model my settings.py file after Heroku's template: https://github.com/heroku/heroku-django-template, and Whitenoise's documentation http://whitenoise.evans.io/en/latest/django.html. When I look at my most recent Heroku logs, I see at=info method=GET path="/static/css/styles.css" host=www.mysite.net request_id=826280da-21ba-48a1-8a05-679c92871d38 dyno=web.1 connect=0ms service=3ms status=404 bytes=361 When I push to Heroku, deployment is successful, but when I run heroku run python3 manage.py collectstatic it says that I have to write over preexisting files (yes/no), and when I say yes, I get an error stating that the app/static directory is not to be found. I am absolutely puzzled - what could I be doing wrong? If my static files directory is not correct, how do I find it? settings.py import os from secrets import … -
FileNotFoundError: [WinError 3] The system cannot find the path specified:
Please find the below error log: traceback: Traceback (most recent call last): File "E:\ent\branc\LS\EV\ent\ent_apps\chat\chat\chat\ent_chat.py", line 53, in __processAimlToGetMatchQuestion amilFileList = [f for f in listdir(pathAiml) if isfile(join(pathAiml, f))] FileNotFoundError: [WinError 3] The system cannot find the path specified: 'E:\ent\branch\LS\EV\ent\ent_apps/chat/data/aiml/ls/' -
mptt add child does not work due to missing trailing slash
I am using Django 1.9.5 with django-mptt 0.8.7 and django-mptt-admin 0.4.4. In the admin treeview of my model there are two links next to each model instance: (edit) (add) (edit) works well. (add) does not work. It creates a link http://127.0.0.1:8000/admin/myapp/mymodel/add?insert_at=507 which can't be resolved. If I enter http://127.0.0.1:8000/admin/myapp/mymodel/add/?insert_at=507 by hand (see additional slash after add), then django-mptt-admin works as desired. I've set APPEND_SLASH=True, although I doubt that this is related to the problem. -
Is it possible to target the value of a html element in Django template language?
<h1 class='username'>something</h1> {% if request.user|stringify == .username %} Is something like this possible or no? -
Gunicorn and Django error permission denied for sock
Trying to setup a site with django and gunicorn getting this error in the nginx log file: 2017/01/31 07:04:50 [crit] 30386#30386: *1 connect() to unix:/home/ubuntu/webapps/kenyabuzz/kb.sock failed (13: Permission denied) while connecting to upstream, client: 197.232.12.165, server: kenyabuzz.nation.news, request: "GET / HTTP/1.1", upstream: "http://unix:/home/ubuntu/webapps/kenyabuzz/kb.sock:/", host: "kenyabuzz.nation.news" static files are served correctly. The gunicorn file in nginx/sites-enabled settings #kb gunicorn nginx settings server { listen 80; server_name kenyabuzz.nation.news; charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /home/ubuntu/webapps/kenyabuzz/kb/media; # your Django project's media files - amend as required } location /static { alias /home/ubuntu/webapps/kenyabuzz/kb/static; # your Django project's static files - amend as required } location /favicon.ico { alias /home/ubuntu/webapps/kenyabuzz/kb/static/kb/favicon.ico; # favicon } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/webapps/kenyabuzz/kb.sock; } } and the gunicorn setting /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/webapps/kenyabuzz ExecStart=/home/ubuntu/djangoenv/bin/gunicorn --workers 10 --bind unix:/home/ubuntu/kenyabuzz/kb.sock kb.wsgi:application [Install] WantedBy=multi-user.target checked the status of gunicorn ubuntu@ip-172-31-16-133:/etc/nginx/sites-enabled$ sudo systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Tue 2017-01-31 06:59:49 UTC; 8min ago Main PID: 30281 (code=exited, status=203/EXEC) Jan 31 06:59:48 ip-172-31-16-133 systemd[1]: Started gunicorn daemon. Jan 31 06:59:49 … -
Django - Pysftp authentication error on template
I'm trying to solve this but I have no clue how to. I'm working with pysftp on Django. the problem is if everything goes ok, nothing happens but if I enter a wrong host, usuario, or clave. I'm still getting Success instead of Error. Something Failed. or Authentication Failed as say if I open Django console when I enter a bad host , usuario or clave. How can I make it work to get Authentication failed error in both places? Django console and Django webapp? Thanks..!! Here's what I have: def sftp_form(request): if request.method == 'POST': form = sftpForm(request.POST or None) if form.is_valid(): data = form.cleaned_data host = data['host'] usuario = data['usuario'] clave = data['clave'] print host print usuario print clave try: SFTP_bajar(host,usuario,clave) messages.success(request,' Success') return redirect('auth_login') except: messages.error(request, 'Error. Something Failed.') else: form=sftpForm() return render(request, 'sftp.html', {'form':form}) def SFTP_bajar(host,usuario,clave): try: transferencia = sftp.Connection(host=host, username=usuario, password=clave) remotepath= 'myremotepath' localpath="mylocalpath" print ('\n' + 'Success') except Exception, e: print str(e) -
Unable to import class from one app into another in django
I am trying to import a class from one django app inside another django app. mainProjectFolder |--__init__.py |--manage.py |--app1 |--__init__.py |--class1.py |--app2 |--__init__.py |--anotherClass.py |--mainProjectFolder |--__init__.py |--settings.py ... in app2.anotherClass.py, I am doing from mainProjectFolder.app1.class1 import Class1 And I get the following error, ImportError: No module named 'mainProjectFolder.app1' I have registered my the apps in INSTALLED_APPS in the settings.py file as well. Please let me know if anything is unclear, I will edit the required. -
TimeField and DurationField int error
I have run into this error when running python manage.py migrate when using DurationField and TimeField both give me a: return int(round(value.total_seconds() * 1000000)) AttributeError: 'int' object has no attribute 'total_seconds' I have seen this error on this site but only for a django 1.8. Currently I am using django 1.10. I have tried the suggesions DurationField(default=timedelta()), nothing inside the DurationField(), DurationField(default=timedelta()), and DurationField(default=int(timedelta(minutes=20).total_seconds())). My model currently looks like: user = models.OneToOneField(User, on_delete=models.CASCADE) lunchnumber = models.IntegerField(null=True, blank=True) role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, null=True, blank=True) breaktime = models.DurationField(defualt=timedelta()) out_time = models.TimeField() in_time = models.TimeField() is_out = models.BooleanField(False) -
Error in parsing binary 16 bit data in Django model
I have a 16 bit binary field in MySql database. I want to map the field to a Django model. I have tried the following: class BookingFareDetails(models.Model): id = models.BinaryField(primary_key=True) In this approach I am getting the following error: UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128) Then I tried to change the type of the field: class BookingFareDetails(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True) And ran into the following error: raise ValueError('badly formed hexadecimal UUID string') ValueError: badly formed hexadecimal UUID string Any help on how to map the binary field would be great. -
Include auto generated primary key in Django ModelForm fields
I have a model where I didn't specify a primary key and Django generated one for me. Now I create a ModelForm for the model and I have specified id in the fields section of ModelForm. However, in my ModelForm object, the id field is not present. Are only the model fields explicitly declared visible in the ModelForm? -
Recaptcha with Django
I migrated my Flask code to Django to handle recaptcha but for some reasons it's always returning False for me now. I have verified that the allowed domains are in the recatpcha instance that I'm using. Here's my flask code: if request.method == "POST": captcha_verify_url = "https://www.google.com/recaptcha/api/siteverify" data = {"secret": "MYSECRET", "response": request.form["g-recaptcha-response"], "remoteip": request.remote_addr} captcha_response = requests.post(captcha_verify_url, data=data).json() if not captcha_response["success"]: #skip, this is robot and this is my django version of it: from ipware.ip import get_ip .... .... if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): captcha_verify_url = "https://www.google.com/recaptcha/api/siteverify" data = {"secret": "MYSECRET", "response": request.POST.get("g-recaptcha-response"), "remoteip": get_ip(request) } captcha_response = requests.post(captcha_verify_url, data=data).json() if not captcha_response["success"]: #skip, this is robot What am I doing incorrectly? The HTML for the captcha is identical, and the form does validate, just not the captcha response -
Periodically update a Django website
What I want to achieve: I have a website that currently updates upon user request (unscalable), I would like my website to update itself every 10 minutes or so. Basically I am building an API that returns data from my Django models. This data is scraped from the web using a python script. When a user requests the page, a script is run which scraps the newest information of a different website. I would like this script to run periodically instead. Many posts have mentioned Celery, and Cron jobs. However, I want to know if there is a simpler way to achieve this. Any information/ideas would be greatly appreciated. -
Django multiple databases error with routes
I'm using 3 databases in my project: DATABASES = { 'default': { (postgres, read, write)... }, 'admission_db': { (postgres, read, write)... }, 'journals_db': { (mysql, read only)... } } DATABASE_ROUTERS = [ 'main.lib.DbRouter.DbRouter', ] wrote db router: class DbRouter: ... def allow_migrate(self, db, app_label, model=None, **hints): if db == 'admission_db': if model and model._meta.app_label == 'admission': return True return app_label == 'admission' elif db == 'journals_db': return False return None when i make migrate command python manage.py migrate admission --database admission_db it migrates normally, but when i try to make python manage.py migrate, it throws django.db.utils.OperationalError: no such table: admission_educationform because of it i can make make migrate on other apps. (python 3.5.2, django 1.10.5) what can be cause of problem? -
ipdb debug not executing on breakpoint
I can not understand why is ipdb entering manage.py every time I start server, my breakpoint is set inside restapi/views.py and I'm starting my server with python -m ipdb manage.py runserver 192.168.33.11:8080, I'm working on vagrant. This is my ipdb log when I start my server > /home/vagrant/vincluos/VincluCMSProject/manage.py(2)<module>() 1 #!/usr/bin/env python ----> 2 import os 3 import sys ipdb> How come that ipdb does not recognize my breakpoint? -
Passing list or array (as parameter) in Django View
How to use the passed value (list/array) in Django View? I have tried something like this: def to_csv(request): g_data = request.GET.getlist('json_data') g_header = request.GET.get('header') g_info = request.GET.get('info') response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="somefilename.csv"' list_header = [[g_info, '', '', '', '', '', '', ''], ['Municipality', 'Barangay', 'Total Number of Structures', 'Total Not Affected', 'Total Affected', 'Low', 'Medium', 'High', 'Total Affected %']] disclaimer = [ 'Disclaimer: The information....', '', '', '', '', '', ''] for val in g_data: perc = (val[4] / float(val[2])) * 100 st_perc = str(round(perc, 2)) val.append(st_perc) list_header.append(val) list_header.append(disclaimer) writer = csv.writer(response) writer.writerows(list_header) return response and in my JavaScript code using AJAX: function to_csv(json_data, header, info){ $.ajax({ url: "/to_csv/", headers: { Accept : "text/csv; charset=utf-8", "Content-Type": "text/csv; charset=utf-8" }, type: "GET", data: { 'json_data': json_data, 'header': header, 'info':info }, The problem is, it does not get the passed data (g_data) -
django token based authorization
Hi I am new to Django and I have implemented the Django oauth2 token based authentication. Can anyone help me out with registering the user and then managing the tokens issued? For registering the user POST call is evaulated for a token which I dont have. Can anyone help me out with initial flow? -
How to change django foreign key select field to input field
So, In the django admin, the foreign key field is always set to a select field by default. Is there any way to make it an input field, and while writing the content it will suggest the value based on what i'm typing, instead of all that long list. Thanks in advance.