Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No ProcessListView endpoint and ArchiveListView variable
I created simple workflow based on cookbook/custom-ui example. My process is working, but I wanted to add list of all processes(using process_list.html in example) and after checking available endpoints with show_urls command i noticed i don't have ProcessListView endpoint listed there. So i tried with archive (which was listed along queue and tasks). But no matter what variable i use in {% for task in archive %} the list is empty. So first question is what should i do to see endpoint or get the list of all processes with custom_ui. And second what variable should i use to get list of archived processes and when process is archived (when it's finished or later on) Also if answers for my questions are in some documentation please give me a link, because i cannot find them Thank you for your help -
Possible jQuery messing up pagination in Django
I have trouble setting up my pagination right. I have a Course model which holds courses and a Faculty model which holds faculties, to whom specific courses belong to. I am switching between all courses display and all courses that belong to a specific faculty by simple click and no other page, just by using a jQuery to hide/show items on page. Now I tried to set up pagination for courses that belong to a specific faculty, and every time I try to change page, it redirects me to the main page which contains all courses. Also, for my first faculty I have only 2 courses, but pagination will show that a 3rd page is available for some reason. I think it's either my view, either my jQuery. https://imgur.com/7Br1a0o <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script> $(document).ready(function () { $('.btnClick').on('click', function () { $('.col-md-9').find('[id^="dep"]').hide(); var faculty_id = $(this).attr('id'); $('#' + faculty_id + '_tab').show().siblings('div').hide(); }); $('.btnClick2').on('click', function () { $('.col-md-9').find('[id^="std"]').hide(); var study_id = $(this).attr('id'); $('#' + study_id + '_tab').show().siblings('div').hide(); }); $('.btnClick3').on('click', function () { var a = $('.col-md-9'); a.find('[id^="fac"]').hide(); a.find('[id^="std"]').hide(); a.find('[id^="crs"]').show(); }); }); </script> <div class="row"> <div class="col-md-3"> <div class="jumbotron"> <h4>Search courses</h4> <hr> <br> <p onClick="window.location.reload()" class="btnClick3">Show all courses</p> <br> <ul> {% for faculty in … -
related_name='hourlys' corresponds to empty list
I have three Django models namely User, Project and Hourly. User model: which represents a standard Django user, which can start a new project. Project model: Represents a project, containing project specifc constants such as Time Zone, site latitude, site longitude, etc… Hourly model: Which represents all the hourly values (clock-time, solar time, solar hour angle, etc…) for a certain project. To simplify the problem the Hourly model has only two fields, namely project and clock_time. Eventually I would like to use fields to store all the hourly values (declination, solar hour angle, etc…) to the database. In addition I override the Project.objects.create(….) method using the ProjectManager() class. Whenever a new project is created, there will be 8760 new hourly value instances also created which stores all the hourly values for declination, solar hour angle. The Project and Hourly models and ProjectManager are defined as follows: User = settings.AUTH_USER_MODEL class ProjectManager(models.Manager): """""" def create(self, owner, project_name, TMZ, lat, lon): project = super().create(owner=owner, project_name=project_name, TMZ=TMZ, lat=lat, lon=lon) project.save() hourlys = Hourly.objects.filter(project=project) hourlys.delete() hourlys = [] for i in range(0, 8760): clock_time=i*3600 hourlys.append(Hourly(project=project, clock_time=clock_time)) Hourly.objects.bulk_create(hourlys) return project class Project(models.Model): objects = ProjectManager() owner = models.ForeignKey('auth.User', related_name='projects', on_delete=models.CASCADE) project_name = models.CharField(max_length=200) TMZ = … -
Django taggit, tags owned by users
By default django-taggit adds tags to objects, visible by any user. I want user to add tags and these tags to belong to that user. Only visible and modified by owner user. Same tag maybe used by different users. There are 2 things to be done , saving tags belong to user and filtering tags per user. I don't know what is the correct way to do that. -
Getting Permissions issue on sending the authenticated request to OAuth2.0 Django rest Framwork
I Have integrated the OAuth2.0 with django-rest-framework. When I send the authenticated request to my class based view I got this { "detail": "You do not have permission to perform this action." } settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } views.py from rest_framework import permissions from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope class LogoutView(APIView): """ This will help in logout of user. """ authentication_classes = () permission_classes = (permissions.IsAuthenticated, TokenHasReadWriteScope) def get(self, request): return Response({'s': 'd'}) urls.py from django.urls import path, re_path from accounts.views import SignUpView, LoginView, LogoutView urlpatterns = [ path('signup/', SignUpView.as_view()), path('login/', LoginView.as_view()), path('logout/', LogoutView.as_view()), ] And this is what my headers look like Content-Type:application/json Authorization:Bearer 4A7qGgmHpbEWlJn5w4wCwxJ9jWfTZ5 This is the access token that I generated. -
How add columns from a list?
(This is my first post on StackOverFlow and it's a great ressource and community <3) I develop a website and i use django_tables2 to display my result. My problem is that i have my table model here (very simple)... class myTable(TableReport, ColumnShiftTable): column_default_show = ['select']; class Meta: attrs = {'class': 'table table-bordered table-striped table-condensed'}; and i want to display dynamically a set of columns... data = []; #Tuples of data listColumnsName = ['columnsName1', 'columnsName2',......]; table = myTable(data=data) ; ...but i dont know how adding the columns because the list of columns is not stable. I hope that i have been understable. -
Django ORM - Get N random records, and then split them in 2 groups
I have a Post model: class Post(models.Model): headline = models.CharField(max_length=255) ... What I am, unsuccessfully, trying to achieve, is to get two random groups of 5 posts each, where the 2nd group records that the 1st group does NOT have. Now I know how to do this using Python, but I was wondering if there is a more elegant, ORM-like solution. I have tried the following: posts = Post.objects.all().order_by('?') first_group = posts[:5] second_group = posts[5:] But this will, sometimes, return the same posts in both groups. I have also tried to trick the system doing the following: posts = Post.objects.all().order_by('?') first_group = posts[:5] second_group = Post.objects.exclude(id__in=posts) But again no luck. Can someone give me a few pointers so I don't have to loop over the records in pure Python? -
How to change the config file in TravisCI to run Django?
I am new to TravisCI and have written the following text in .travis.yml: language: python python: - 3.6 env: - DJANGO=2.0.2 script: - python manage.py test I am trying to run a build for a Django-project. The build runs, but for some reason it fails because TravisCI thinks it is a Ruby-project. This is not strange as, when I press "view config", I see that it is written for Ruby (also see screenshot below): { "language": "ruby", "group": "stable", "dist": "trusty", "os": "linux" } Does anyone know how to change this config-file to fit for Django? So that my .travis.yml file can run correctly? -
Django Admin DateTime field - combine now/today?
On Django Admin, if your model has a DateTimeField, this is displayed as 2 inputs, one for date and one for time, with a Today link next to the date which sets to current day, and a Now link next to time, which sets the current time. This means if a user wants to set the date & time to the current date and time, they have to click 2 links. Is there any way to just have one link that sets both? -
Django unique_together is not working
class model_name(models.Model): pk = models.AutoField(primary_key=True, auto_created=True) field1 = models.ForeignKey(model1, on_delete=models.CASCADE) field2 = models.ForeignKey(model2, on_delete=models.CASCADE) field3 = models.ForeignKey(model3, on_delete=models.CASCADE) field4 = models.IntegerField() class Meta: unique_together= (('field1', 'field2', 'field3'),) db_table = "table_name" whenever I give data from Django admin app it says that it already exists. it works fine there but when I give it manually it starts taking duplicates. I have added the unique_together constraint but it still takes the duplicates for particular fields. what should I do to stop taking the already existing data? I use mysql database Any solution is appreciated. Thanks. -
Django Rest Framework updating nested m2m objects. Does anyone know a better way?
I have a case when user needs to update one instance together with adding/editing the m2m related objects on this instance. Here is my solution: class MySerializer(...): def update(self, instance, validated_data): actions_data = validated_data.pop('actions') # Use atomic block to rollback if anything raised Exception with transaction.atomic(): # update main object updated_instance = super().update(instance, validated_data) actions = [] # Loop over m2m relation data and # create/update each action instance based on id present for action_data in actions_data: action_kwargs = { 'data': action_data } id = action_data.get('id', False) if id: action_kwargs['instance'] = AdditionalAction.objects.get(id=id) actions_ser = ActionSerializerWrite(**action_kwargs) actions_ser.is_valid(raise_exception=True) actions.append(actions_ser.save()) updated_instance.actions.set(actions) return updated_instance Can anyone suggest better solution? P.S. actions can be created or updated in this case, so i can't just use many=True on serializer cause it also needs instance to update. -
Configure OIDC with Google Oauth
I am trying to use the Oauth server from google with mozilla-django-oidc. However I don't know exactly what should I use in these parameters OIDC_OP_AUTHORIZATION_ENDPOINT = "" OIDC_OP_TOKEN_ENDPOINT = "" OIDC_OP_USER_ENDPOINT = "" Currently I am trying this: OIDC_OP_AUTHORIZATION_ENDPOINT = "https://accounts.google.com/o/oauth2/auth" OIDC_OP_TOKEN_ENDPOINT = "https://accounts.google.com/o/oauth2/token" OIDC_OP_USER_ENDPOINT = "http://127.0.0.1:8000/oidc/callback/" But I am getting HTTPError: 400 Client Error: Bad Request for url: https://accounts.google.com/o/oauth2/token Any idea what I am doing wrong? -
How to Conditionally render a Link Column with Django Tables 2?
With the following table when returning the BoundColumn it is plain text and not html. class CarHistoryTable(tables.Table): edit = tables.LinkColumn( 'Car:update', kwargs={'pk': A('id')}, orderable=False, text='Edit' ) def render_edit(self, record, value, bound_column): if record.state != Car.NEW: return '' return super().render_edit() Ideally I want to return an empty text for Cars that are not NEW state. For other cars I would like to render the edit link. -
Django account_activation_token.check_token always return False in constant_time_compare()
I have an ActivationTokenGenerator that create a token that will be used for account verification that will be send by email. For example I configured it like this with parameters including timestamp, id, and user active status: from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils import six class ActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active) account_activation_token = ActivationTokenGenerator() Then I use the account_activation_token for generating token in a verification email I sent with a send_mail. @classmethod def send_email(cls, request, user): current_site = get_current_site(request) mail_subject = 'Activate your Poros account.' message = render_to_string('email_verification.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': account_activation_token.make_token(user), }) to_email = user.email email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() Everything looks perfect email sent with a token that included inside a url with pattern like this: url(r'activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', activate, name='activate'), and looks like this in the email: http://{{ domain }}{% url 'activate' uidb64=uid token=token %} then when the link clicked it will call this activate view: from django.http import HttpResponse from django.contrib.auth import login from django.utils.encoding import force_text from django.utils.http import urlsafe_base64_decode from accounts.utilities import account_activation_token from accounts.models import User def activate(request, uidb64, token): try: id = force_text(urlsafe_base64_decode(uidb64)) print(id) user = User.objects.get(pk=id) print(user) except(TypeError, ValueError, … -
Django pagination erorr, getting redirected to first page
I have been struggling with this for few days now. I finally found the issue. I have a Course model from which I display all my courses. I also have a filter of those courses with whom I can display them sorted by faculty. I wanted to have a pagination for those courses filtered by faculty, so I added it. Problem is, if I click on next page, I get redirected to all courses page. Why is that happening ? Can my jQuery script have something to do with that ? I use it to display courses by faculty. https://i.imgur.com/Ft4qeX2.png <div class="jumbotron"> <div id="crs"> <h3>All courses</h3> <ul> {% for course in courses %} <li><a href={{ course.slug }}>{{ course.name }}</a></li> {% endfor %} </ul> </div> {% if courses1 %} {% for faculty in faculties %} <div id="fac_{{ faculty.pk }}_tab" style="display:none;"> <h3> {{ faculty.name }} Courses</h3> <ul> {% for department in faculty.department_set.all %} {% for study in studies %} {% if study.department == department %} {% for course in courses1 %} {% if course.study_programme == study %} <li> <a class="first" href={{ course.slug }}>{{ course.name }}</a> </li> {% endif %} {% endfor %} {% endif %} {% endfor %} {% endfor %} </ul> … -
Django admin search by foreign key too slow
I have two models in Django: class Dog(models.Model): nick = models.CharField(max_length=30, db_index=True) class Bark(models.Model): date_of_bark = models.DateTimeField(default=datetime.utcnow) pet = models.ForeignKey('Dog', related_name='bark_dog', on_delete=models.CASCADE) In admin form, I want to search all the Barks of a specific Dog: class BarkAdmin(BaseAdmin, BaseActions): paginator = MyPaginator list_display = ('id', 'date_of_bark', 'pet') search_fields = ('pet__nick, ) In my database, every Dog has millions of Barks. The problem is that every search takes a lot of time: Load times (aprox): Load of table : Instant Search results: 15 seconds In order to improve the time, I ordered the search field: class BarkAdmin(BaseAdmin, BaseActions): paginator = MyPaginator list_display = ('id', 'date_of_bark', 'pet') search_fields = ('pet__nick, ) ordering = ('pet__nick',) And now we have these load times (aprox): Load of table : 15 seconds Search results: Instant How can I improve both times simultaneously? -
python3+django2: attempted relative import beyond top-level package
I have a directory structure as: -code |-helper.py |-django_site |-manage.py |-polls |-views.py In views.py I did: import sys sys.path.append("..") from ..helper import * def index(request): do_something So when I run python manage.py runserver, I have the error "ValueError: attempted relative import beyond top-level package". How should I resolve the problem? Thanks a lot, -
How to add the operations before the result
I have 338 classes and for each classes 6 operations. If i am clicking on any class name it is directly showing the data of only one operation. How can I add the option so after clicking on the operation it will give me the respective data related to that operation. I'm working on Django and HTML. Below is my code: <nav1> <ul> {% block content1 %} {% for class in response_data %} <li><a href= "/{{class}}/" name='class' value={{class}}>{{class}}</a></li> {% endfor %} {% endblock %} </ul> </nav1> <div class="btn-group btn-group-lg"> <button type="button" class="btn btn-primary">Enumerate</button> <button type="button" class="btn btn-primary">Get</button> <button type="button" class="btn btn-primary">Invoke</button> </div> -
Django select a valid choice error when populate select in the template
I get a validate error when I create a form with an empty select field: area_sp = forms.ChoiceField(widget=forms.Select(attrs={'class': 'form-control', 'id':'area_select'})) then I populate the select in the template using ajax: $.ajax({ url: '/endpoint/load_areas/', type: 'post', dataType: 'json', data: { 'postcode': postcode }, headers: { 'X-CSRFToken': "{{ csrf_token }}" }, success: function (data) { var ret = JSON.parse(data.result); for (x in ret) { $("#area_select").append(new Option(x, ret[x])); } }, error: function(data) { alert("error"); } }); Finally, when I submit the form I get the following error: area_sp: Select a valid choice. 26835 is not one of the available choices. Any idea? -
How to incorporate data from two distrinct sources in a single serializer?
I'm trying to serialize some objects whose data is stored in 2 databases, linked by common UUIDs. The second database stores personal data, so is run as a segregated microservice to comply with various privacy laws. I receive the data from db2 as a decoded list of dicts (rather than an actual queryset of model instances) How can I adapt the ModelSerializer to serialize this data? Here's how I can get the data: # returns a list of dict objects, approx representing Person.__dict__ personal_data_list = Microservice.objects.custom_filter(uuid__in=uuids) Here's an example serializer that I'm trying to use, with ??? showing where I don't know how to link the personal_data_list into the source attribute: class PersonSerializer(serializers.ModelSerializer): personal_stuff = serializers.CharField(source='???', read_only=True) class Meta: model = Person fields = ('uuid', 'personal_stuff') def get_personal_stuff(self, obj): return obj.get('personal_stuff') I've shown the microservice field I'm interested in above as personal_stuff. I don't know if there's a nice DRF way to link the two. I definitely don't want to be sending (potentially thousands of) individual requests to the microservice by including a single request in get_personal_data. The actual view just looks like this: class Persons(generics.ListAPIView): model = Person serializer_class = PersonSerializer def get_queryset(self): self.kwargs.get('some_filter_criteria') return Person.objects.filter(some_filter_criteria) Where should the … -
Can't able Retrieve data from JSON file using Angular js
I am not able Retrieve data from JSON file using Angular js. Am trying to get the json data from URL using click function in angular js and also i got the empty row output in table . var app =angular.module('sampleapp', []) app.controller("tablejsonCtrl", function ($scope, $http) { $scope.jsonclick = function () { var url = "http://127.0.0.1:8000/static/waste/test.json"; $http.get(url).then( function(data) { $scope.students = data; }); } }); <!doctype html> <html lang="en" ng-app="sampleapp"> <head> {% load staticfiles %} <!-- <meta charset="utf-8"> --> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css"> <script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script type="text/javascript" src="{% static 'waste/angular.min.js'%}"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script> <script type="text/javascript" src="{% static '/bootstrap/js/app_ang.js'%}"></script> <div class="col-sm-12" ng-controller="tablejsonCtrl"> <button class="clickbutton" value="10" ng-click="jsonclick();">Show-json</button> <table rule="all" class="table table-bordered table-hover "> <tr> <th>Name</th> <th>Price</th> <th>Description</th> <th>Calories</th> <th>isbest</th> </tr> <tr ng-repeat="stuednt in students"> <td>{{stuednt.name}}</td> <td>{{stuednt.price}}</td> <td>{{stuednt.description}}</td> <td>{{stuednt.calories}}</td> <td>{{stuednt.isbest}}</td> </tr> </table> </div> </body> </html> -
trying to convert this mssql query to django
I've been trying to convert this query SELECT coalesce(SUM( PortFixedIncApp.PrincipalBalance + (PortFixedIncApp.PrincipalBalance * PortFixedIncApp.DailyInterestrate * DATEDIFF(day, PortFixedIncApp.LastDateOfInterestAccruals,'2016-02-05')) + PortFixedIncApp.InterestBalance),0 ) AS MarketValue FROM PortFixedIncApp WHERE (PortFixedIncApp.TransStatus = 'Active') AND PortFixedIncApp.AccountNo='3051010000401' AND (PortFixedIncApp.EndDate <='2016-02-05') and this is what I tried to do in django Portfixedincapp.objects.filter(Q(transstatus="Active")& Q(accountno="{0}".format(custaccountno))& Q(enddate__lte=today)).aggregate(market_value=\ Coalesce(Sum(F("principalbalance")+(F("principalbalance") * F("dailyinterestrate") * arrow.get(F("lastdateofinterestaccruals")).date() - today) + F("interestbalance"), output_field=models.IntegerField()),0)) I get this error when i run can't parse single argument type of '<class 'django.db.models.expressions.F'>' -
Securing production Django App
I am new to the deployment aspect of Django applications. I will probably use Heroku or PythonAnywhere for eventual deployment of my application. However, before I do this I need to achieve two specific tasks. When in deployment the python files in fact any files must not be able to be modified externally. (So compression?) If possible I'd like to be able to package my Django project into one .exe file. (If even possible at all). I have read about .pyc files I think this may be an option but if anybody could offer up some options to me and or explain the ins and outs of .pyc files that would be a great help. -
django2 + python3: TemplateDoesNotExist
I know there are multiple questions on this site about this problem, but I cannot find a solution. I am using Python 3.6 (anaconda) + django 2.0.2 on Windows 10. I am following the tutorial: https://docs.djangoproject.com/en/2.0/intro/tutorial03/ Here is my views.py from django.shortcuts import render # Create your views here. from django.http import HttpResponse from .models import * def index(request): content = 'abcxyz' context = {'content': content} return render(request, 'polls/index.html', context) I created a file index.html in the folder polls\templates\polls My settings.py: INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'django_site.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'django_site.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } I have a problem of 'TemplateDoesNotExist' - it seems to me that django tries to look for a template in django.template.loaders.app_directories.Loader: /mnt/e/workspace/capec-processing/code/django_site/polls/templates/polls/templates/polls/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/user_name/anaconda3/envs/capec/lib/python3.6/site-packages/django/contrib/admin/templates/polls/templates/polls/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/user_name/anaconda3/envs/capec/lib/python3.6/site-packages/django/contrib/auth/templates/polls/templates/polls/index.html (Source does not exist) I am not sure what did I do wrong, because I followed the tutorial on … -
Set value of a model field that is not part of model form
I have a model like this class Income(models.Model): value = models.DecimalField(max_digits=10, decimal_places=2) remitted = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) I have a form like this class EditIncomeForm(forms.ModelForm): class Meta: model = Income fields = ("value", ) def clean_value(self): value = self.cleaned_data["value"] if self.value < self.remitted: raise forms.ValidationError("Error message") return value Now in the modelform, how do I update the value of the remitted field? I can't seem to be able to access the remitted field this way. I'm on Django 2.0