Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I get get_absolute_url to render a string in views.py in Django
I am trying to send an email with HTML content. The email would include a link to a DetailView of a specific instance of a model. So in the "post" part of view which sends the email, I have something like: html_content = '<a href="'+str(my_model_instance.get_absolute_url())+'">'+str(text)+'</a>' The email that gets sent is: <a href="<bound method MyModel.get_absolute_url of <MyModel: my instance name>>">my instance name</a> How do I render an HTTP string in views.py? Thank you -
How do I translate this MySQL query to Django?
I don't know how to make a Django queryset out of this. SELECT DISTINCT delivery_product_id, delivery_inventory_id, SUM(Pear_delivery.delivery_amount) FROM (Pear_delivery LEFT JOIN Pear_product ON Pear_delivery.delivery_product_id = Pear_product.id) LEFT JOIN Pear_inventory ON Pear_product.id = Pear_delivery.delivery_product_id GROUP BY Pear_product.product_name, Pear_inventory.inventory_city, delivery_product_id, delivery_inventory_id ORDER BY delivery_product_id; -
Sending CSRF Tokens via Postman
I'm trying to test my web server's login with Postman. First, I send a GET request to my login url, and I get a CSRF token as a cookie. Then, I make a POST request to that login page, with my username, password, and CSRF token. My problem is, when I do this in Postman, I get a 403 forbidden error when I try to make that POST request to login. I'm copying the CSRF token received and putting it as one of the POST parameters, and I'm using a valid username and password. Is there anything I'm overlooking here? -
How to get ?next=/xxx/ working with Django login page so that referring page is returned to once user is logged in
I am modifying a Django project made by somebody else. There are links on the existing website that look like this: http://example.com/accounts/login/?next=/secondexample/ Where secondexample is the name of a page that is intended to load once the user has logged in. Currently when the above URL is visited, the login page loads fine and the user is able to login, however once the user is logged in, they are redirected to http://www.example.com and not http://www.example.com/secondexample I have found this: django redirect after login not working "next" not posting? and this Django login redirect not working? But was unable to get the redirect working, despite trying what was suggested. I modified my login.html ; following the advice in the first post above, like so: {% if next %} <form action="http://example.com/accounts/login/?next=http://www.example.com{{next}}" method="post" > {%else%} <form class="login-form" action="" method="post"> {% endif %} Now if i visit the login form , without passing a next parameter into the url and inspect the code I see this: <form action="" class="login-form" method="post"> If I visit the login page, and pass a next parameter in by visiting this url for instance: http://example.com/accounts/login/?next=/testdirectory/ and then inspect the html on the login form again, I see the form action … -
python-social-auth in Django: pass data to pipeline
I am trying to learn this on the fly. <li><a href="{% url 'social:begin' 'github' %}?next={{ request.path }}">Claim Generated GitHub Account</a></li> I am using this to initiate my pipeline. Say I wanted to pass data to the pipeline from a form, or depending on which button was pressed. How would I pass data to, and access data from, the pipeline? -
Filter at multiple levels with GraphQL and Graphene
I'm using Django and Graphene and have multiple levels I'd like to filter on. But I can't get past either "Unknown operation named \"undefined\"." or getting ALL objects at each level of the hierarchy (i.e.: ALL jobDetails for all jobs listed for EACH job). I'm trying to do this query: query { allPushes(revision: "1ef73669e8fccac35b650ff81df1b575a39a0fd5") { edges { node { revision author jobs (result: "testfailed") { edges { node { result jobDetails (url_Iendswith: "errorsummary.log") { edges { node { url } } } } } } } } } } In Django, jobDetails has a foreign key to jobs, which has a foreign key to pushes My first attempt was to setup my nodes: class JobDetailNode(DjangoObjectType): class Meta: model = JobDetail filter_fields = { 'url': ('exact', 'icontains', 'iendswith') } interfaces = (relay.Node, ) class JobNode(DjangoObjectType): class Meta: model = Job filter_fields = ('result', 'tier') interfaces = (relay.Node, ) job_details = DjangoFilterConnectionField(JobDetailNode) class PushNode(DjangoObjectType): class Meta: model = Push filter_fields = ('revision', ) interfaces = (relay.Node, ) jobs = DjangoFilterConnectionField(JobNode) But this returns, as I said, all jobDetails at for EACH job, not just the jobDetails that belong to that job. But if I remove those DjangoFilterConnectionField fields, then I can't filter … -
cron jobs with django.core.management
In a project, a guy (travelling now) created the cron.py with the content # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.core import management def hourly(): management.call_command( 'transactions', check_completed=True, verbosity=0, interactive=False) def deposits(): management.call_command( 'transactions', deposits=True, push=True, verbosity=0, interactive=False) def debit(): management.call_command( 'transactions', debits=True, push=True, verbosity=0, interactive=False) Could anyone be able to tell me what are hourly(), deposits() and debit()? It seems he used that for cron jobs, but it is unclear for me. -
AngularJS router does not load page served at `templateURL`
This is my HTML page (which gets served when accessing the path /): <form ng-submit="ctrl.loginUser()" name="myLoginForm"> <div class="form-group"> <label>Username</label> <input type="text" name="uname" class="form-control" ng-model="ctrl.loginuser.username" required> </div> <div class="form-group"> <label>Password</label> <input type="password" name="pwd" class="form-control" ng-model="ctrl.loginuser.password" required> </div> <input type="submit" value="Login"> </form> <div ng-view></div> And this is what gets called when the form is submitted: angular.module("BaseApp", []) .config(['$httpProvider', function($httpProvider) { $httpProvider.defaults.xsrfCookieName = 'csrftoken'; $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; }]) .config(['$locationProvider', function($locationProvider){ $locationProvider.html5Mode(true); }]) .config(['$routeProvider', function($routeProvider) { $routeProvider .when('/home', { templateURL: 'static/templates/mainPage.html' }) /* .otherwise({redirectTo: '/'}); */ }]) self.loginUser = function(loginuser) { return $http.post("/custom-api-auth/login", loginuser) .then(function(response) { $location.url("/home"); }); }; static/templates/mainPage.html is this: TESTTTTTTTT I tried testing this and submitting the form. The URL changes to /home, but TESTTTTTTTT doesn't show up. When I manually change my static URL to /static/templates/mainPage.html through the address bar and then hit enter, mainPage.html does in fact appear. When I change templateURL: 'static/templates/mainPage.html' to template: '<h5>This is the default route</h5>', This is the default route does show up correctly. How come static/templates/mainPage.html does not show up? I am using Django / DRF as my backend, and this is my urls.py: from django.conf.urls import url from django.conf.urls import include from ebdjangoapp import views from rest_framework import routers router = routers.DefaultRouter() … -
ImportError: No module named operator - Python/Django error after upgrading Debian 7 to 8
I'm unable to run my Django app on Debian 8 after upgrading from 7. Currently on Django 1.7.11 and Python 2.7. [Tue Apr 04 00:14:19.214416 2017] [wsgi:error] [pid 30493] [client] mod_wsgi (pid=30493): Target WSGI script '/var/www/web/apache/django.wsgi' cannot be loaded as Python module. [Tue Apr 04 00:14:19.214495 2017] [wsgi:error] [pid 30493] [client] mod_wsgi (pid=30493): Exception occurred processing WSGI script '/var/www/web/apache/django.wsgi'. [Tue Apr 04 00:14:19.214533 2017] [wsgi:error] [pid 30493] [client] Traceback (most recent call last): [Tue Apr 04 00:14:19.214571 2017] [wsgi:error] [pid 30493] [client] File "/var/www/web/apache/django.wsgi", line 10, in <module> [Tue Apr 04 00:14:19.214679 2017] [wsgi:error] [pid 30493] [client] import django.core.handlers.wsgi [Tue Apr 04 00:14:19.214707 2017] [wsgi:error] [pid 30493] [client] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 3, in <module> [Tue Apr 04 00:14:19.214921 2017] [wsgi:error] [pid 30493] [client] import cgi [Tue Apr 04 00:14:19.214959 2017] [wsgi:error] [pid 30493] [client] File "/usr/lib/python2.7/cgi.py", line 37, in <module> [Tue Apr 04 00:14:19.215424 2017] [wsgi:error] [pid 30493] [client] from operator import attrgetter [Tue Apr 04 00:14:19.215485 2017] [wsgi:error] [pid 30493] [client] ImportError: No module named operator -
How to order nested model in django DetailView
I'm using Django 1.10 I'm learning Django by make Survey program I made three models, Survey include Questions, and Question include Choices Models.py from django.db import models class Survey(models.Model): title = models.CharField(max_length = 200) description = models.TextField() pub_date = models.DateTimeField('date published') def __str__(self): return self.title class Question(models.Model): survey = models.ForeignKey(Survey, on_delete=models.CASCADE) question_text = models.CharField(max_length=200) def __str__(self): return "%s : %s" % (self.survey, self.question_text) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return "%s - %s" % (self.question, self.choice_text) I want to show my result page ordered by votes but now, I just show non-ordered result page. I think I have to modify my views.py using queryset or extra context. but I don't know how to use. Here is my views and template. views.py class SurveyResultsView(DetailView): model = Survey template_name = 'survey/results.html' results.html {% extends 'survey/base.html' %} {% block content %} <div class="survey-info-container"> <h1>Results of {{survey.title}}</h1> <p>{{survey.description}}</p> <p>{{survey.pub_date}}</p> </div> <div class="result-container"> {% for question in survey.question_set.all %} <p> <h3>{{question.question_text}}</h3> <ul> {% for choice in question.choice_set.all %} <li>{{choice.choice_text}} -- {{choice.votes}} votes </li> {% endfor %} </ul> </p> {% endfor %} </div> {% endblock content %} Thanks for read. -
Very simplistic django Heroku app crashing
I have a very very simple Django app, literally just 1 view. When I upload it to Heroku, I receive this error: 2017-04-03T23:32:18.494436+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=powerful-taiga-40434.herokuapp.com request_id=9135150c-bade-4b38-8da4-7886a96bdef5 fwd="71.62.73.144" dyno= connect= service= status=503 bytes= protocol=https 2017-04-03T23:32:19.261516+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=powerful-taiga-40434.herokuapp.com request_id=f080b6c0-b26e-480b-9ac7-418c0f612e72 fwd="71.62.73.144" dyno= connect= service= status=503 bytes= protocol=https I am brand new to Heroku django, but given how simple the code is, I doubt the issue lays in the python code itself, it must be a configuration somewhere. Ideas? -
Editing profile user Django
i'm trying to edit a profile but I got this error "DoesNotExist at /blog/edit/, User matching query does not exist." def Profil(request, username): if request.user.is_authenticated(): base_template_name = 'blog/base.html' else: base_template_name = 'blog/visitor.html' user = User.objects.get(username=username) logged_in_user_posts = Post.objects.filter(user=user) context = {'base_template_name':base_template_name} return render(request, 'blog/profil.html', {'user':user, 'posts':logged_in_user_posts}) def update_profile(request): if request.method == 'POST': profile_form = ProfileForm(request.POST, request.FILES, instance=request.user.profile) if profile_form.is_valid(): profile_form.save() messages.success(request, ('Your profile was successfully updated!')) return redirect('blog:index') else: messages.error(request, ('Please correct the error below.')) else: profile_form = ProfileForm(instance=request.user.profile) return render(request, 'blog/edit_profile.html', { 'profile_form': profile_form }) In the urls.py: url(r'^(?P<username>\w+)/$', views.Profil, name = 'profil'), url(r'^edit/$', views.update_profile, name='edit_profile'), -
Importing In Django
I have something like this in one of my apps's models.py : class Account(AbstractBaseUser): email = models.EmailField(unique=True) I want to import a class from another app's views.py as below: from anotherapp.views import MyClass The problem, in the first lines of anotherapp.views file, I imported the Account class. So when I want to import MyClass into my models.py file, this error raises : ImportError: cannot import name Account -
Django form not saving model object for user
I've been trying to build an application which will allow users (django-registration + templates) to upload short audio clips. I've recently found a bit of code that will parse the file and do a check to make sure the file doesn't have any fishy file extensions, and is the correct file type. But now, when I try and submit the form, to info doesn't go into the database, and the file isn't uploaded into my media_cdn path. The form just reloads with no error. Anyone know whats up? The form worked just fine previously, however I hadn't incorporated the users/file validation when it was last tested. Here's my forms.py: class PostForm(forms.ModelForm): def clean_sound(self): file= self.cleaned_data.get('sound', False) if file: if file._size > 4*1024*1024: raise ValidationError('Audio file too large(>4mb)') if not file.content_type in ['audio/mpeg', 'audio/wav', 'audio/ogg']: raise ValidationError('Content type incorrect') if not os.path.splitext(file.name)[1] in ['.mp3', '.wav', '.ogg']: raise ValidationError('Wrong extension') return file class Meta: model = Place fields = [ 'title', 'latitude', 'longitude', 'sound', ] and views.py: @login_required(login_url='/accounts/login/') def post_create(request): form= PostForm(request.POST or None, request.FILES or None) if request.method == 'POST': if form.is_valid(): instance = form.save(commit=False) instance.save() #Message success messages.success(request, 'Successfully Created') return HttpResponseRedirect(instance.get_absolute_url()) context= { 'form': form, } return render(request, 'location/post_form.html',context) … -
How to autofocus onto select fields
I'm using an rfid scanner to input two items into the form, RIN and RFID, one after the other. The scanner outputs a string and enter. I want to autofocus onto the first entry of the form and then the second. The enter press on the first does not change the page since it can't submit unless both fields are filled. How do I start the page focus on the first and jump focus to the second? Is there a better solution? views.py def take(request): if request.method == "POST": form = TakeForm(request.POST) if form.is_valid(): take = form.save(commit=False) take.TA = request.user take.Timestamp = timezone.now() tool = Tool.objects.get(RFID=take.RFID.RFID) if tool.Out == False: tool.Out = True take.In_or_Out = 'Out' tool.Out_with = take.RIN tool.Times_used += 1 tool.Last_taken_out = timezone.now() tool.save() take.save() else: tool.Out = False take.In_or_Out = 'In' tool.Out_with = None tool.Last_taken_in = timezone.now() tool.Net_time_out += tool.Last_taken_in - tool.Last_taken_out tool.save() take.save() return redirect('take') else: form = TakeForm() return render(request, 'info/take.html', {'form': form}) forms.py class TakeForm(forms.ModelForm): class Meta: model = Take fields = ('RFID','RIN') take.html {% extends "info/header.html" %} {% load staticfiles%} {% block content %} <h1>Take In or Out</h1> <form method="POST" class="post-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> {% … -
pass daterangepicker new dates to views and call url
I have urls.py like urlpatterns = [ url(r'^$', HomeView.as_view(), name='home'), url(r'^api/chart/data/$', ChartData.as_view()), url(r'^admin/', admin.site.urls), views.py like class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): qs_count = User.objects.all().count() And base.html where I am calling daterangepicker $('#reportrange').on('apply.daterangepicker', function(ev, picker) { startDate = picker.startDate.format('YYYY-MM-DD') console.log(startDate); console.log(picker.endDate.format('YYYY-MM-DD')); }); When I run server and change dates through daterangepicker I can see updated dates in console. But now I'm stuck at, how can I send new dates to views? and call ChartData to render new chart as per dates? Currently my chart is getting rendered like var endpoint = '/api/chart/data/' var defaultData = [] var labels = []; $.ajax({ method: "GET", url: endpoint, success: function(data){ labels = data.labels defaultData = data.default setChart() }, error: function(error_data){ console.log("error") console.log(error_data) } }) And HomeView renders at the start class HomeView(View): def get(self, request, *args, **kwargs): return render(request, 'src/charts.html', {"customers": 10}) -
How to connect Emacs' Elpy in-buffer python interpreter to docker container?
I am getting started working on a Django app that will run within a Docker container. I would like to be able to use interactive python from within Emacs which executes the code within the context of the Docker container and the Django app. Essentially I want the Python interpreter that is used by Emacs to be running within the Docker container. I have managed to achieve this for the most part by creating a modified Dockerfile which is only different from my actual Dockerfile container in that instead of calling a Django command it ends with: CMD ./manage.py shell This means that when I run that Docker container I get a Django interpreter that is actually running within the container. I have Elpy invoke this when starting a python shell by adding: (setq python-shell-interpreter "/path_to_my_script/run_shell.sh") to my .emacs.d/init.el file. Where the "/path_to_my_script/run_shell.sh" script is a script which runs the container. This is actually working for the most part. I am able to highlight a line of code such as from django.utils import timezone and run the Emacs command elpy-shell-send-region-or-buffer and it will execute the code. I can then highlight print(timezone.now()) and it will print the current time. I have … -
Django manytomany unique constraint
Here is my django model: class Reaction(models.Model): first_object = models.ForeignKey(Object, related_name='first_object') second_object = models.ForeignKey(Object, related_name='second_object') result_object = models.ForeignKey(Object, related_name='result_object') class Meta: unique_together = (('first_object', 'second_object',),) I would like to make this unique constraint simultaneously together with unique_together = (('second_object', 'first_object',),) For example, i would not be able to add this object Reaction(first_object__id=2, second_object__id=1) if Reaction(first_object__id=1, second_object__id=2) exists. Any ideas? -
Export related ModelResource in one-to-many relatioship (Django)
Let's say that i have the given models: @python_2_unicode_compatible class Region(models.Model): name = models.CharField(unique=True, max_length=2, blank=False, @python_2_unicode_compatible class State(models.Model): region = models.ForeignKey(Region, on_delete=models.CASCADE) name = models.CharField(unique=True, max_length=2, blank=False, null=False) and i want to export all the states for a give region (and i don't want to go 'field by field', i want something like: class StateResource(resources.ModelResource): class Meta: model = State class RegionResource(resources.ModelResource): states_set = StateResource(many=True) class Meta: model = Region Is it possible? Thanks in advance! -
Django User-Specified Regex Filter
I'm trying to have a search option where users can input a regular expression into a text box and Django can filter the queryset using the user-provided regex. I have provided a simple example below. The user provides str_input1 in a search box and the following code is used in views.py. import re from myProject.models import Exe exe_filtered = Exe.objects.filter(part_number__regex = str_input1) Here's a look at my Django model: class Exe(models.Model): part_number = models.CharField(max_length=128, unique = True) The above example works in the Django shell, but not in practice. Does this have something to do with input formatting and/or escape characters? I am using SQLite currently. -
Django-cms ImportError: No module named sitescms
I am trying install django-cms. But I got following error Traceback (most recent call last): File "/home/savad/virtuals/kw/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "/home/savad/virtuals/kw/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 107, in inner_run autoreload.raise_last_exception() File "/home/savad/virtuals/kw/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 252, in raise_last_exception six.reraise(*_exception) File "/home/savad/virtuals/kw/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "/home/savad/virtuals/kw/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/home/savad/virtuals/kw/local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/home/savad/virtuals/kw/local/lib/python2.7/site-packages/django/apps/config.py", line 119, in create import_module(entry) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named sitescms I used django-cms==3.4.2 and django==1.8.17. -
Is it worth switching from Django's token auth to JWT?
I am building an iOS application (to be published for the app store) that has a sign up/log in system. I have already built the backend on Django using Django's built-in token authentication system. How much refactoring would it require to shift to JWT? And is it worth it? -
How to identify user using cookie?
I'm beginner with web development and I have problem with HTTP request/response system. I want to identify user (UUID) using 1st (from tracking code, passed to my app as parameter), and 3rd party cookies (created my app and passed to my app as cookie header). I have no idea how to do it :/ It's my code (most of it I found on the net): # coding=utf-8 from uuid import uuid4 from django.http.response import HttpResponse def identify_user(request): # checking if uuid is in cookie uuid = request.COOKIES.get('key', None) if uuid is None: # checking if uuid is parameter uuid = request.GET.get('cookie', None) if uuid is None: # generate new if UUID no exists uuid = uuid4() response = HttpResponse('response') set_cookie(response, 'key', uuid) return response def set_cookie(response, key, value): one_year = 365 * 24 * 60 * 60 response.set_cookie(key, value, max_age=one_year) In response I need to JSONP (set received/generated UUID in response header) I will try to handle it after manage with first part of my task. I need advise or help with solve it. -
Django template naming with dashes VS underscores
We are using the Django framework and in the book "2 scoops of django" there is a recommendation to use underscore naming for specific things, should this be included in the naming of templates as well? front end developers here are really locked on dashes and I was just wondering? -
Django custom query extremely slow
I have a custom query I'm running with Django. If I run the query in pgAdmin, the response time is milliseconds. However, the same query in Django takes around 52 seconds. PgAdmin Output: EXPLAIN ANALYZE select t.tag, t.detected_at, a.code as antenna_code, r.code as reader_code, s.slug from tags_tag t inner join sites_antenna a on (t.antenna_id = a.id) inner join sites_reader r on (a.reader_id = r.id) inner join sites_site s on (r.site_id = s.id) where s.slug = 'BVC' and tag ~ '3E7' order by t.id DESC limit 1 "Limit (cost=5.52..53.02 rows=1 width=37) (actual time=254.105..254.107 rows=1 loops=1)" " -> Nested Loop (cost=5.52..87869.88 rows=1850 width=37) (actual time=254.101..254.101 rows=1 loops=1)" " Join Filter: (a.id = t.antenna_id)" " Rows Removed by Join Filter: 2210" " -> Index Scan Backward using tags_tag_pkey on tags_tag t (cost=0.43..83561.74 rows=286729 width=31) (actual time=3.928..247.145 rows=369 loops=1)" " Filter: ((tag)::text ~ '3E7'::text)" " Rows Removed by Filter: 263" " -> Materialize (cost=5.09..7.21 rows=1 width=14) (actual time=0.002..0.009 rows=6 loops=369)" " -> Nested Loop (cost=5.09..7.21 rows=1 width=14) (actual time=0.179..0.237 rows=6 loops=1)" " -> Hash Join (cost=4.95..6.44 rows=1 width=11) (actual time=0.165..0.195 rows=1 loops=1)" " Hash Cond: (r.site_id = s.id)" " -> Seq Scan on sites_reader r (cost=0.00..1.35 rows=35 width=11) (actual time=0.005..0.050 rows=35 loops=1)" " -> …