Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django redirect incorrectly behind a reverse_proxy
I'm running a Django app on http://localhost:7777 behind a reverse proxy server (Nginx) Everything goes under http://example.tw/test should be redirected to http://localhost:7777 When I attempt to log in by visiting http://example.tw/test Django always redirects me to http://example.tw/accounts/login instead of http://example.tw/test/accounts/login I've already set USE_X_FORWARDED_HOST = True in my settings.py and proxy_set_header Host $http_host in my nginx config but none of these can get it to work... Can anyone tell me which part do I miss? Thank you. These are the configs: nginx.conf server { listen 80; server_name example.tw; location /test { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_pass http://localhost:7777/; } } server { listen 7777; server_name localhost; charset utf-8; location / { uwsgi_pass unix:///tmp/test.sock; include /etc/nginx/uwsgi_params; } } uwsgi.ini [uwsgi] proj_name = test chdir = %d wsgi-file = %d%(proj_name)/wsgi.py home = /home/%U/.pyenv/versions/%(proj_name) master = true processes = 2 threads = 2 socket = /tmp/%(proj_name).sock chmod-socket = 666 vacuum = true settings.py from django.core.urlresolvers import reverse_lazy ... LOGIN_URL = reverse_lazy('account_login') USE_X_FORWARDED_HOST = True -
How to refresh google access token from refresh token
I am having access token (got from django allauth). I also have refresh token. I want to know the process to get latest token using the refresh token. -
Django - dynamic sucess_url in UpdateView
I want my user to be able to see a page, update that page, and then be returned to that page or continue making more edits. Here's the view to show the information: # urls.py url(r'^gameview/$', views.GameView.as_view(template_name='matchview.html'), name='GameView') # Views.py class GameView(generic.TemplateView): template_name = "matchview.html" def get_context_data(self, **kwargs): context = super(GameView, self).get_context_data(**kwargs) q = self.request.GET.get('match') context['report'] = GameNotes.objects.filter(game=q) context['game'] = Schedule.objects.get(match=q) context['gamepic'] = Photo.objects.filter(game=q) return context So now they want to add information about a game. I use an UpdateView class GameView(generic.TemplateView): template_name = "matchview.html" def get_context_data(self, **kwargs): context = super(GameView, self).get_context_data(**kwargs) q = self.request.GET.get('match') context['report'] = GameNotes.objects.filter(game=q) context['game'] = Schedule.objects.get(match=q) context['gamepic'] = Photo.objects.filter(game=q) return context When the user finishes updating in the latter view, they should be returned to the former on the exact same team. This post helped me move in the right direction insofar as using 'get_success_url', but I'm still stuck because I don't think I'm using kwargs. Everything I've tried has resulted in errors. (My (gulp) thought is that I should re-write the urls to use PKs so that this stuff is easier, but I wanted to make sure) -
Django Admin hides names and shows (table_name object)
I am fairly new to django admin. I am trying to manage my table contents from the admin section for table created with the following models: class subject(models.Model): subject_id = models.CharField(max_length=12, unique=True) name = models.CharField(max_length=25) class subject_date(models.Model): sub_id = models.ForeignKey(subject) date = models.CharField(max_length=25) I have added my subjects to the subject table and now I want to add subject dates to the subject_date table from the admin section. Because of the one to many relationship I get a drop-down list under sub_id of all the subjects I added in the subject table. the problem is that the drop-down list has all the contents written as follows: subject object. This makes it impossible for me to see which subject I am dealing with. Can anyone please help me with this if its an issue that can be fixed. -
Detect groups from user just created from the Django (Wagtail) Admin area
I am trying to detect in which group a user is when creating this user from the Wagtail Admin area in order to modify some internal data (and do some stuff with it) but I cannot manage to make it work. So far I have tried to use a post_save signal to detect the user creation and a m2m_changed to detect the user group change, but I cannot manage to connect them both to collaborate together: detect that the user has been created AND if it is in certain group. My signals look like the following: def _user_created(sender, instance, created, *args, **kwargs): user = instance user_in_foo_group = user.groups.filter(name='foo').exists() # also tried User.objects.filter(pk=user.pk, groups__name='foo').exists() with no luck! #if it is being created if created and user_in_foo_group: # here I modify internal variables from the user user.some_foo = foo user.other_foo = otherfoo user.save() post_save.connect(_user_created, sender=settings.AUTH_USER_MODEL) def _user_groups_changed(sender, instance, action, **kwargs): if action == 'post_add' or action == 'post_remove': user = instance user_is_foo = user.groups.filter(name='FOO').exists() if user_is_foo: # until here works if user.created: # how to get this?????? user.foo_la = La user.foo_lala = Lala send_hello_foo_email(user) m2m_changed.connect(_user_groups_changed, sender=User.groups.through) Any help will be more than appreciated :) -
Django render_to_response renders the correct view but url in browser stays unchanged
I have come across a strange issue where a code snippet that served me for a year now behaves incorrectly. The problem is that redner_to_response seems to render the correct view, but does not change the url in my browser. HTML: <li><a href = '{% url "settings" %}' data-title="A new page">{% trans 'Settings' %}</a></li> settings.html {% extends "base.html" %} {% block content %} {% load i18n %} <p> This is my settings page. It is rendered, but the url stays "http://127.0.0.1:8000/, instead of "http://127.0.0.1:8000/settings/"</p> {% endblock %} The view: def user_settings(request): return render_to_response('settings.html', context = {}, context_instance = RequestContext(request)) Once again, **the question is, ** why a seemingly similar code snippet does not update the url to '127.0.0.1:8000/settings' and leaves it unchanged to be '127.0.0.1:8000/'? -
django rest framework schema APIView and query parameters
I am not very used to DRF. I wanted have docs for my api, but I do not know how to do it. in urls.py I have from rest_framework.schemas import get_schema_view urlpatterns = [ ... url(r'^docs/$', get_schema_view(title='Some API docs')), ... ] And in my views I have from rest_framework.views import APIView from .serializers import InSerializer, OutSerializer class SomeEndpointView(APIView): def get(self, request, user_id, format=None): qp_serializer = InSerializer(data=request.query_params) if not qp_serializer.is_valid(): # handle failure output_data = # create output data output_serializer = OutSerializer(output_data) return Response(...) Unfortunatelly, in schema it only shows user_id in path. How to document input and output? -
Django 1.9.9 unable to connect Azure SQL database from windows
On my windows machine, I have following packages installed in my app. django: 1.9.9 pyodbc==4.0.3 django-pyodbc-azure==1.10.4.0 In my settings.py file.. DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USERNAME'), 'PASSWORD': os.environ.get('DB_PASSWORD'), 'HOST': 'tcp:sdohsandbox.database.windows.net', 'PORT': '1433', 'OPTIONS': { 'driver': 'SQL Server Native Client 11.0', 'MARS_Connection': 'True', }, 'CONN_MAX_AGE': 120, } } When I start server I am getting following error.. django.core.exceptions.ImproperlyConfigured: Django 1.9.9 is not supported. Though I have latest version of pyodbc I am getting error. Need help. -
Django-CKEditor with ACE
I'm using Django-CKEditor in a project and I want to include code editing. I know CKEditor has an addon PBCKCode which enables code editor functionality for languages. Is there anyway to use this addon with Django-CKEditor? -
How should I show a link of existing file in Form.FileField from a model but not using ModelForm?
I've checked link which itself cites link, link, link, and cannot get an answer from the above. Let me use the following model to make an example: class Assignment(models.Model): file1 = models.FileField(upload_to='xxx') file2 = models.FileField(upload_to='yyy') other_val = models.CharField(...) # not important And the Form: class AssignmentForm(ModelForm): class Meta: model = Assignment fields = ['file1', 'other_val'] # but not file2 def __init__(self, *args, **kwargs): ... another_assignment = # assume somehow I get another assignment object from database self.fields['file2'] = forms.FileField(initial=???) I want to pass another_assignment.file2 as the default value. I think it is possible because ModelForm is capable of showing a link of the previously uploaded file. It looks like this: Currently: AssignmentTask_grading_script/grading_script_firing.py Change: [Choose File] no file chosen My question is, in a customized Form or if I want to add another FileField in a ModelForm, how should I pass a Model.FileField so that it can show a link if the file exists? -
django with nginx uwsgi bad gateway 502
i want to run django with nginx i followed this instructions and in /etc/nginx/sites-available/myproject upstream django { server unix:///root/cartoview_project/mysite.sock; # for a file socket } server { listen 80; server_name xx.xx.xx.xx; charset utf-8; # max upload size client_max_body_size 2048M; # adjust to taste # Django media location /media { alias /root/cartoview_project/uploaded; } location /static { alias /root/cartoview_project/static; } location / { uwsgi_pass django; include /root/cartoview_project/uwsgi_params; # the uwsgi_params file you installed } } then created symlink using: sudo ln -s /etc/nginx/sites-available/cartoview_one /etc/nginx/sites-enabled and in project folder mysite_uwsgi.ini: [uwsgi] project = cartoview_project chdir = /root/cartoview_project module = %(project).wsgi:application home = /root/env master = true processes = 10 socket = /root/cartoview_project/mysite.sock chmod-socket = 666 vacuum = true http-socket = 0.0.0.0:80 project structure : . |-- apps |-- cartoview_project | |-- __init__.py | |-- __init__.pyc | |-- local_settings.py | |-- local_settings.pyc | |-- local_settings.py.sample | |-- settings.py | |-- settings.pyc | |-- urls.py | |-- wsgi.py | `-- wsgi.pyc |-- default_oauth_apps.json |-- initial_data.json |-- manage.py |-- mysite_uwsgi.ini `-- uwsgi_params when i try to access website with myip this message appear : 502 Bad Gateway nginx/1.10.0 (Ubuntu) error.log : 2017/02/06 09:46:41 [crit] 6867#6867: *1 connect() to unix:///root/cartoview_project/mysite.sock failed (13: Permission denied) while connecting to β¦ -
Django generic relation admin site
I am using Django 1.9.9 with generic relations and in the admin site, I have to manually type in the Object ID. Is there any method so that I can select an object from a list like a regular foreign key? -
How to check current user's permissions from a Group in Django?
I have a group EuropartsBuyer and model named Product. The following code adds a permission to the Product model. class Meta: permissions = ( ("can_add_cost_price", "Can add cost price"), ) In one of my views I have the following code to add this permission to that group. europarts_buyer, created = Group.objects.get_or_create(name='EuropartsBuyer') add_cost_price = Permission.objects.get(codename='can_add_cost_price') europarts_buyer.permissions.add(add_cost_price) With the help of Django Admin I have added a user to the group EuropartsBuyer. When I use the following code in another view if request.user.has_perm('can_add_cost_price'): do something the result is supposed to be True but it is showing False. Thus, the code under the if clause doesn't run. I have imported the currently logged in user in Django shell and when I test the permission again it shows False. What am I doing wrong here? -
How to redirect user and display his/her username to a different page in Ajax?
I am trying to redirect the user (who has successfully logged in) to an article page with his/her username. but for some reason i don't see the username of the user in the article page. article html: <div class="container post" > <h2 class="author"><a>{{ username }}</a></h2> <hr> <h6 class="subject"> </h6> <p class="comment"><br><br> </div> Ajax: $('#loginForm').on('submit',function(e){ e.preventDefault(); $.ajax({ type: "POST", url: "/librarysystem/Login/", data: { 'username':$("#loginUsername").val(), 'password':$("#loginPassword").val(), csrfmiddlewaretoken:$ ('input[name=csrfmiddlewaretoken]').val () }, dataType: 'json', success: function(data){ if (data.response){ initalizeForm(); $("#invalid").html(" "); $('#loginmodal').modal('hide'); console.log(data.username); window.location = data.redirectTo + "?username=" + data.username; }else $("#invalid").html("<h5> Invalid username or password. </h5>").css('color','red'); }, error: function(jqXHR, status, err){ alert(jqXHR.responseText); } }); }); urls.py: from django.conf.urls import url from .import views urlpatterns = [ url(r'^register/$',views.registerUser), url(r'^$', views.index, name="Index"), url(r'^validateRegisterForm/$',views.validateRegisterForm), url(r'^validateLoginForm/$',views.validateLoginForm), url(r'^article/$', views.article, name="Article"), url(r'^Login/$',views.loginUser, name="Login"), url(r'^Logout/$',views.logoutUser, name="Logout"), ] views.py: def loginUser(request): data = {} if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username,password=password); if user is None: data['response'] = False else: login(request,user) data['response'] = True data['redirectTo'] = "/librarysystem/article/" data['username'] = username return JsonResponse(data) -
How should I allow a FileField not need to upload a new file when the existed in Django?
I have a model like this: class Assignment(models.Model): content = models.FileField(upload_to='xxx') And a form wrapping this model (ModelForm): class AssignmentForm(ModelForm): class Meta: model = Assignment fields = ['content'] My view looks like this (for simplicity I skip the request.POST/request.FILES. part): @login_required(login_url='/login/') def create_assignment(request): form = AssignmentForm() # render form @login_required(login_url='/login/') def update_assignment(request, assignment_id): assignment = Assignment.objects.get(id=assignment_id) form = AssignmentForm(instance=assignment) Creating an assignment works just fine - It forces me to upload a file, which is what I want. But when I want to update the content of the assignment (the file), it first shows a link of a previous uploaded file (excellent!) then the upload button, like this: Currently: AssignmentTask_grading_script/grading_script_firing.py Change: [Choose File] no file chosen But then I assume if I don't want to replace this file, I should simply click the submit button. Unfortunately, when I click the submit button, the form complains that I should upload a file. Is there a way to silent the complaint if a file is already in database? -
Whoosh (django haystack) error IndexError: string index out of range
When I run update_index or rebuild_index on django for django haystack during build it throws this error File "/home/ubuntu/webapps/djangoenv/local/lib/python2.7/site-packages/django/template/base.py", line 624, in resolve new_obj = func(obj, *arg_vals) File "/home/ubuntu/webapps/djangoenv/local/lib/python2.7/site-packages/markup_deprecated/templatetags/markup.py", line 30, in textile return mark_safe(force_text(textile.textile(force_bytes(value), encoding='utf-8', output='utf-8'))) File "/home/ubuntu/webapps/djangoenv/local/lib/python2.7/site-packages/textile/core.py", line 1360, in textile return Textile(html_type=html_type).parse(text) File "/home/ubuntu/webapps/djangoenv/local/lib/python2.7/site-packages/textile/core.py", line 250, in parse text = self.block(text) File "/home/ubuntu/webapps/djangoenv/local/lib/python2.7/site-packages/textile/core.py", line 465, in block if ext or not line[0] in whitespace: IndexError: string index out of range -
Why PDFKit doesn't work well with margins?
although I just don't have the need to ask something normally (internet is just a gold mine, especially this site), this is getting me off, as I had been two days trying to get this working and I don't find anything useful. Link for similar post would be thanked if founded, as I didn't found one. Let's get started. I'm using PDFKit with Python 2.7 and Django 1.9 to generate some HTML to PDF. Easy work. The HTML just looks like this: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style type="text/css"> * { /* Box-model */ margin: 0; padding: 0; } .wrapper { /* Box-model */ width: 229mm; height: 161mm; } </style> </head> <body> {% for someone in people %} <div class="wrapper"> <p><strong>{{ someone.complete_name }}</strong></p> <p>{{ someone.bio }}</p> </div> {% endfor %} </body> </html> My PDFKit options looks like this: { "page-width": "229mm", "page-height": "162mm", "paper-size": "CE5", "encoding": "utf-8" } In both cases I just don't add any margins or paddings. I generate the PDF, and looks great (no surprises, all goes where it belongs). But, if I add any margin/padding in the HTML and/or options, I just get a continued repetitive incremental margin when the PDF is generated (to give β¦ -
ReportLab Internal Link/Anchor Does Not Work
I am using ReportLab (3.30) on Python (3.5) in Django (1.10) to generate pdf and try to embed some internal link in the document. I follow the user guide instruction but the link does not work. Specifically, my anchor is on page 4 but the link only bring me to page 2. Could anyone suggest any solution to that? I attached the code as below for reference. Many thanks. def downloadpdf(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="mypdf.pdf"' pdfmetrics.registerFont(TTFont('MsBlack', 'msjh.ttf')) pdfmetrics.registerFont(TTFont('MsBlackBd', 'msjhbd.ttf')) registerFontFamily('MsBlack',normal='MsBlack',bold='MsBlackBd') buffer = BytesIO() doc = SimpleDocTemplate(buffer, pagesize=A4, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18) Story =[] styles=getSampleStyleSheet() styles.add(ParagraphStyle(name='Justify', fontName = 'MsBlack', fontSize=15, leading=20, alignment=TA_JUSTIFY)) styles.add(ParagraphStyle(name='PBold', fontName = 'MsBlackBd', fontSize=15, leading=20, alignment=TA_JUSTIFY)) str_input0 = 'TextTextTextTextTextTextTextTextText<font color="red">Red</font>TextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextText' ptext = '<font size=15>%s</font>' % str_input0 ltext = '<link href="#aaa" color="blue">aaa</link>' atext = '<a name="aaa" />bbb' Story.append(Paragraph(ltext, styles["Justify"])) Story.append(Spacer(1, 12)) for _ in range (0,30): Story.append(Paragraph(ptext, styles["PBold"])) Story.append(Spacer(1, 12)) Story.append(Paragraph(atext, styles["Justify"])) doc.build(Story , canvasmaker=NumberedCanvas) pdf = buffer.getvalue() buffer.close() response.write(pdf) return response -
Django: TemplateDoesNotExist at / home.html in my project
I can not understand why django can't search 'home.html' my project name is lucifer here's my tree of projects β βββ lucifer β β βββ __init__.py β β βββ settings β β β βββ __init__.py β β β βββ development.py β β β βββ partials β β β β βββ __init__.py β β β β βββ base.py β β β β βββ database.py β β β β βββ static.py β β β βββ production.py β β βββ templates β β β βββ base.html β β β βββ home.html β β β βββ partials β β β βββ footer.html β β β βββ header.html β β βββ urls.py β β βββ views β β β βββ __init__.py β β β βββ home.py and my home.html {% extends 'base.html' %} {% block title %} Home {% endblock %} base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>루μνΌ |{% block title %}{% endblock %}</title> </head> <body> {% include 'partials/header.html' %} {% block content %} {% endblock %} {% include 'partials/footer.html' %} </body> </html> home.py from django.views.generic import TemplateView class Home(TemplateView): template_name = 'home.html' urls.py from django.conf.urls import url from django.contrib import admin from .views import * urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'$^', Home.as_view(), β¦ -
Django query database and send data to template
I am still new to Django/web development but have experience with Python and PSQL. I have a psql database with a table that has an id, date, and value for a stock portfolio. The table is titled absolutedollarvalue. I want to send the data to the template and then graph it using Highcharts.JS. From what I understand, I need to set up models.py to query the database, which is installed in Django, convert it to JSON, and then send this to the template for graphing. Can anyone tell me if this is the right syntax to get the id, date, and value, and how to send the date and value in json format to the template? Below is my models.py code: from django.shortcuts import render from django.http import HttpResponse from django.db import connection from toa.models import Absolutedollarvalue as adv import psycopg2 import json import datetime def adv(request): adv.objects a = adv(id = '1103804') This is my template: <html> <head> <title> Fund Performance </title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <script src="http://code.highcharts.com/highcharts.js"></script> </head> <body> <div id="chart_container" style="width:100%; height:400px;"></div> <script type="text/javascript"> $(document).ready(function() { var absolutedollarval = { chart: { renderTo: 'chart_panel', type: 'time-series', }, legend: {enabled: false}, title: {text: 'Daily NAV'}, xAxis: {title:{text:'Date'}}, yAxis: {title: {text: β¦ -
is there dump() function in Django / Python?
I really like PHP dump() function from Symphony, is there something equivalent in Python Django? and is there a "die()" function in Python similar with PHP? -
Using google python api client with the token
Google api client https://github.com/google/google-api-python-client gives some examples that shows the full flow(right from asking user to login). But I am using django-allauth so I have the token(with necessary scopes) already with me. I want to use that token to make api calls. How to do that ? PS: I need to use google analytics api. -
How to create a file and upload it into a FileField within a Django View
I'm looking to be able to create a template with a form in it, and when someone hits "create," print that HTML and form to a PDF file, save it to a FileField in a model, and also display it for that person to print. Ultimately, I'm looking to avoid having to output the file, and then have the user re-upload the file. Any suggestions on how to do this in a Django view? Thanks! -
Django queryset update() in += way
How can I call update on Django queryset, that does not write particular value, but modify the value already there, as follows Entry.objects.filter(pub_date__year=2010).update(count+=1) How can I achieve that? -
Python: Django + robotframework for login automation
I have a project that needs to store login details in a MySQL database that will show only a list of URLs to the client in a form of a webpage - 50+ websites, 100+ users (intranet only). The user will click on the URL then he will be redirected to the login page of that particular URL with the login credentials filled in. Im a php guy and attacking this using PHP relies heavily on file_get_contents and a chrome extension for very secure webpages. I was thinking of migrating the project to Python using Django and Robotframework. Will this work considering that the users need no installations/reconfigurations done in their machines? App is in a local Server User login into the webpage/app using his machine Accounts related to the user will be displayed in the webpage User clicks on url and redirected to the login page, with the form already populated User clicks button to login to that website, i.e. mail.google.com I need your expert opinions/suggestions/violent reactions.