Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Kerberos gives permission denied error
While authenticating a user against kerberos, I'm getting a permission denied error. checkPassword breaks with permission denied . Any ideas why it might be giving me this error? Any kerberos expert please help. ` from django.conf import settings from django_auth_kerberos.backends import KrbBackend kerb = KrbBackend() result = kerb.authenticate(settings.KRB5_TEST_USER,settings.KRB5_TEST_PASSWORD) Failure during authentication Traceback (most recent call last): File "/var/www/adlm_python/venv/lib/python3.4/site-packages/django_auth_kerberos/backends.py", line 60, in check_password **kerberos.checkPassword(username.lower(), password, getattr(settings, "KRB5_SERVICE", ""), getattr(settings, "KRB5_REALM", ""), getattr(settings, "KRB5_VERIFY_KDC", True))** kerberos.BasicAuthError: ('Permission denied', 13) ` My settings.py file has the following kerberos settings: ` INSTALLED_APPS= [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', 'project', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'kronos', 'django_auth_kerberos', ] KRB5_REALM = "AURITASAPP.COM" KRB5_SERVICE = 'feroze@AURITASAPP.COM' KRB5_DEBUG = True KRB5_VERIFY_KDC = True KRB5_USERNAME_MATCH_IEXACT = True LOGIN_REDIRECT_URL = '/' AUTHENTICATION_BACKENDS = ( 'django_auth_kerberos.backends.KrbBackend', ) KRB5_TEST_USER = 'feroze' KRB5_TEST_PASSWORD = '*******' ` -
django2/angular4 url (re_path and path)
i can`t solve problem with new django url path... when i try to navigate to another url like localhost/bla/bla/ #file urls.py path(r'^api/', admin.site.urls), path('', TemplateViews.as_view(template_name='index.html')) this will show django Page not found (404) and if i use old re_path syntax: #file urls.py path(r'^api/', admin.site.urls), re_path(r'^.*', TemplateView.as_view(template_name='index.html')) this will show angular4 Page not found (404) how i can solve this issues with new django path? -
How to cache all site pages with Redis in Django?
Is it possible to cache all site pages automatically with Redis in Django? I'm using django-redis package. How could I implement a function to scan all urls and cache each one? -
Django takes too long to render dictionary
Am using django to render a dictionary to the template. The dictionary have some 150k records. It takes more than 30 secs to render the template. I cannot lazy load the data and I need that entire data to be passed to my template in once. Is there any way to render the template in lesser time? This is my view. def report(request): data = mydict() #returns my dictionary return render(request,'app/report.html',{ 'content' : data}) -
Django Administration: Combine admin application model
I am using all auth and created another model ambassadors. I have currently the issue that Django Administration shows me these both models now in two different boxes. Does anyone know how to combine these? Preview My goal is to have Accounts: Email-Addresses Ambassdadors -
AttributeError: 'AnonymousUser' object has no attribute '_meta'
I am experiencing an issue with my Django code whenever I try to sign up with a new normal user'. Which states the following error, with the traceback: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/Ethan/mysite/polls/views.py", line 57, in normalsignup login(request, user) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/auth/__init__.py", line 154, in login request.session[SESSION_KEY] = user._meta.pk.value_to_string(user) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/utils/functional.py", line 239, in inner return func(self._wrapped, *args) AttributeError: 'AnonymousUser' object has no attribute '_meta' Here are my views.py from django.http import HttpResponse from django.shortcuts import get_object_or_404, render, render_to_response, redirect from django.contrib.auth.decorators import login_required from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect from polls.forms import NormalSignUpForm, VenueSignUpForm, BLSignUpForm, BMSignUpForm, ProfileForm from django.contrib.auth import get_user_model from django.views.generic.detail import SingleObjectMixin from django.views.generic import UpdateView, TemplateView from django.utils.decorators import method_decorator from django.db.models.signals import post_save from polls.models import User user = get_user_model() def signup(request): return render(request, 'signup.html') def normalsignup(request): if request.method == 'POST': form = NormalSignUpForm(request.POST) if form.is_valid(): raw_password = form.cleaned_data.get('password1') email = form.cleaned_data.get('email') user = authenticate(email=email, password=raw_password) login(request, user) return redirect('home') else: form = NormalSignUpForm() return render(request, 'normalsignup.html', {'form': form}) … -
task queue in celery
I have a service that processes data. It is written in Python (Django) and uses Celery for making it asynchronous. Processing our data uses credits. You can also buy credits and this is triggered by a Stripe-webhook. Each action that involves credit changes is listed as a "job". I have 2 Celery tasks all adding a job to a certain JobId database. I use the "job" concept to keep track of which data is processed at which job. models.py: class JobId(models.Model): user = models.ForeignKey(User, blank=True, null=True, default=None) job_time = models.DateTimeField(auto_now_add=True) # current credit level credits = models.IntegerField(default=0, null=True, blank=True) # credit impact / delta of this job credit_delta = models.IntegerField(default=0, null=True, blank=True) tasks.py: task_1_buy_credits(user): # credit level of user is searched in jobs_database (the users last job) # adds one line in the JobId database with the users new credit balance task_2_use_credits(user,data): # upfront unknown amount of data get processed # credit level of user is searched in jobs_database (the users last job) # decide to process job completely or stop if credit level is insufficient My current issue is that when people start multiple jobs at a time, the previous job is not finished yet. As my final credit … -
Key (user_id)=(7) is not present in table "auth_user"
i am using djoser's create token end point to login user but i am getting following error. I have tried google search but could not find any useful answer. -
How to prevent creation of a record based on a related django-guardian permissions?
How do you prevent a model from being created by a specific user in the django admin if the user does not have a specific permission of a related object. So the object has an object level permission with django-guardian: CHANGE_RATE_PERM = 'change_rates' class Project(models.Model): ... class Meta: permissions = ( (CHANGE_RATE_PERM, 'Change Rates'), ) Permissions are assigned with: assign_perm( CHANGE_RATE_PERM, instance.account_manager, instance ) Then I have a related model called Rate that is related to the project: class Rate(models.Model): project = models.ForeignKey( Project, on_delete=models.PROTECT ) rate = MoneyField( max_digits=10, decimal_places=2, default_currency='ZAR' ) So I want to ensure that when a rate is created on django admin a check is made to see whether the user requesting the rate checks for the CHANGE_RATE_PERM for the the project. If there is no permission, an error is given. -
login_required decorator in Django doesn't work
I'm working on a Django(1.10) project in which I need to load a template only for logged in users, which is coming from profile template.I need to load generateCert.html only for logged in user, this template should display the same navbar as profile template because both of these templates have the same header. Here's my generateCert.html template: {% load staticfiles %} {% load static from staticfiles %} {% load mathfilters %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>NAMI Montana | User's Dashboard</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <meta name="description" content=""/> <meta name="author" content="http://webthemez.com"/> <!-- css --> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"/> <link href="{% static 'css/fancybox/jquery.fancybox.css' %}" rel="stylesheet"> <link href="{% static 'css/flexslider.css' %}" rel="stylesheet"/> <link href="{% static 'css/style.css' %}" rel="stylesheet"/> <script src="https://www.paypalobjects.com/api/checkout.js"></script> <!--Pulling Awesome Font --> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <!-- HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]><![endif]--> <style> input[type="image"] { padding-left: 30%; padding-top: 5%; font-size: 1em; color: #fff; background: transparent; border: 1px solid #fff; font-weight: bold; width: 70%; } </style> </head> <body> <div class="topbar"> <div class="container"> <div class="row"> <div class="col-md-12"> <p class="pull-left hidden-xs"><i class="fa fa-envelope"></i><span>matt@namimt.org </span></p> <p class="pull-right"><i class="fa fa-phone"></i>Tel No. (406) 443-7871</p> </div> </div> </div> </div> <!-- start header --> <header> <div class="navbar … -
Django 1.11 - child template not inheriting from parent
I've read through similar stackoverflow problems and checked that I wasn't making the same mistake. I don't think this is an issue with URLs or Views as the Django-debug-toolbar shows that it's picking up the parent template, but the child template isn't extending that. I have the following project structure: project templates base.html index.html apps charts templates chart_base.html charts.html project/templates/base.html <body> {% block wrapper %} <div id="wrap"> {% endblock %} <div class="container" id="container-main"> {% block body %} {% endblock %} </div> <footer class="footer"> <div class="container"> {% block footer %} {% endblock %} </container> </footer> ....(scripts).... {% block extrajs %} {% endblock %} </body> project/apps/charts/templates/chart_base.html {% extends 'base.html' %} {% block body %} <!-- chartjs container --> <div class='container'> <!-- charts.js code --> {% block chart %} {% endblock chart %} <!-- / charts.js code --> </div> <!-- /chartjs container --> {% include 'base/js.html' %} <script> $(document).ready(function(){ {% block jquery %}{% endblock %} }) </script> {% endblock %} project/apps/charts/templates/charts.html {% extends 'chart_base.html' %} <!-- charts.html jquery --> <script> {% block jquery %} var labels = [] var defaultData = [] var endpoint = '/api/chart/data/' $.ajax({ method: "GET", url: endpoint, success: function(data){ labels = data.labels defaultData = data.default setChart() }, error: function(error_data){ … -
Django with Postgres - ProgrammingError, migrations not updating the database
Recently, I changed a model called 'Objects' by adding a 'description' field (which has null set to True). Ever since I migrated to the Postgres database hooked up to the Django project, I have received the following error whilst trying to access the 'Objects' model. ProgrammingError at /objects/results/ column objects_objects.description does not exist LINE 1: ...1, "objects_objects"."mapped_product_id" AS Col2, "objects_o... Objects model... class Objects(models.Model): mapped_product = models.ForeignKey(Product,related_name='p_objects',verbose_name='Product',null=True,blank=True,on_delete=models.SET_NULL) description = models.CharField(max_length=1000,null=True,blank=True) slug_key=models.SlugField(unique=True) is_active=models.BooleanField(verbose_name='Active',default=False) In the console, Django says migrations are all successful, and when running the local server it does not show that there are unapplied migrations. Any ideas on how to sync the database up with the models from scratch? I do not mind clearing my development database for this, and have already tried removing all of the previous migrations. I understand that this is somewhat vague at this point since I'm unsure what code I should post here - let me know if there is some code I should post here. -
How to save the first 10entries with a default value
Assuming we have an Article model with is_published BooleanField. How can I save the first 20entries with is_published value as True? -
Python/Django how to set model datetime field with html date field value
I want to assign values form a simple html form(I dont want to use Django model forms or widgets in this case). All of the fields work fine except the datetime one. Lets say the html form is as simple as this: <form action="{% url 'main:create' %}" method="post" class="row form"> {% csrf_token %} <div class="expense-block" id="expense-block-0" data-block="0"> <div class="col-md-2"> <div class="form-group"> <label for="id_name">Name:</label> <input type="text" name="name" class="form-control" required id="id_name"> </div> </div> <div class="col-md-2"> <div class="form-group"> <label for="id_created_at">Date:</label> <input type="datetime-local" name="created_at" class="form-control" required id="id_created_at"> </div> </div> </div> <input type="submit"> </form> As you can see for the date input i am using type="datetime-local" because I want to select both date and time. The model is simple: class Expenses(models.Model): name = models.CharField(max_length=200) created_at = models.DateTimeField() However when i save model I get error: The Expenses could not be created because the data didn't validate. Now the reason I am getting this error is because the 'create_at' value that i get from the post looks like this: 2018-03-09T11:11 So the question is, is it possible with Python to format this date to a normal datetime object? If not, what else can I do in my case? -
Django createsuperuser error in console
I start new project with two app (customuser and client). In customuser I redefine default User model and in client make UserProfile with OneToOne field to User. Then I run makemigartions customuser makemigrations client migrate In this point all Ok Bun then I run createsuperuser The error is appear return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: NOT NULL constraint failed: client_profile.position_id customuser/models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class User(AbstractUser): """User … -
Django AJAX call/url from template after dropdown change
Trying to learn/implement AJAX and in django url/router url(r'^recipe/AJAX/(?P<recipe_pk>[a-zA-Z0-9]+)/?', views.newRecipeAJAX, name='newRecipeAJAX'), in the template {% block script_inline %} $(function(){ $('#form-dropdown').change(function () { var recipe_pk = $(this).val(); {# This one doesn't know the recipe_pk yet, so it throws a NoReverseMatch error #} request_url = {% url 'recipes:newRecipeAJAX' recipe_pk=recipe_pk %}; {# This one will too, since it doesn't have the argument #} request_url = {% url 'recipes:newRecipeAJAX' %}; {# Tried to get a valid link, then JS remove it and add the correct pk, but it throws a JS console error of 'Uncaught SyntaxError: Invalid regular expression flags'#} request_url = "'' + {% url 'recipes:newRecipeAJAX' recipe_pk=1 %} + "'"; alert(requst_url) // AJAX Land }); }); {% endblock script_inline %} view def newRecipeAJAX(request, recipe_pk): if request.method == 'POST': return HttpResponseRedirect('/dashboard') # GET else: recipe_requested = get_object_or_404(Recipe, pk=recipe_pk) related_recipes = Recipe.related_recipes.all() return { 'recipe_requested': recipe_requested, 'related_recipes': related_recipes, } How do I properly have django tell me the url to send it to, so I can avoid hardcoding it, and how do I do it in JS, once its been served (like can i get the url with everything but the recipe_pk and then concat in JS later?) -
Override Django Base Widget
It is possible to modify the Django Base Widget <django.forms.widgets.Widget>? I want to add a new data attribute for every single field that I render in the front-end. Exemple: CharField(max_length=50) DecimalField(max_digits=50) # And then in the render I want to add attribute data-max-length=50 <input type="text" max-length="50"> For that I want to override the base Widget to generate others masks and validations using JQuery masks, based on my ModelField or FormField. -
django-urls browser preview error
Using the URLconf defined in WisdomPets.urls, Django tried these URL patterns, in this order: admin/ ^$ [name='home'] ^adoptions/(\d+)/ [name='pet_detail'] The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. when I run server there was a warning WARNINGS: ?: (2_0.W001) Your URL pattern '^$' [name='home'] has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path(). ?: (2_0.W001) Your URL pattern '^adoptions/(\d+)/' [name='pet_detail'] has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path(). Here is the code.. from django.contrib import admin from django.urls import path from adoptions import views urlpatterns = [ path('admin/', admin.site.urls), path(r'^$', views.home, name='home'), path(r'^adoptions/(\d+)/', views.pet_detail, name='pet_detail'), ] -
Writing a test for a Django View get_context_data() method
I am writing a test for a View where I update context to pass additional information to the template. Problem In writing the test, I'm having trouble accessing context from the RequestFactory. Code View class PlanListView(HasBillingRightsMixin, ListView): """Show the Plans for user to select.""" headline = "Select a Plan" model = Plan template_name = "billing/plan_list.html" def get_context_data(self, *args, **kwargs): context = super(PlanListView, self).get_context_data(**kwargs) context.update({ "customer": self.get_customer() }) return context Test class TestPlanListView(BaseTestBilling): def setUp(self): super(TestPlanListView, self).setUp() request = self.factory.get('billing:plan_list') request.user = self.user request.company_uuid = self.user.company_uuid self.view = PlanListView() self.view.request = request self.response = PlanListView.as_view()(request) def test_get_context_data(self, **kwargs): context = super(self.view, self).get_context_data(**kwargs) context.update({"customer": self.view.get_customer()}) self.assertEqual( self.view.get_context_data(), context ) Question How can I test the view's get_context_data() method? -
I want to convert decimal numbers from western arabic (0,1,2,3,4,5,6) to eastern arabic(٠, ١, ٢, ٣))
Is there any package available in python library or any way that I can convert decimal numbers (99.3) to (٩ ٩ .٣ ) I can convert the simple integers to eastern Arabic but the issue is with decimal. -
Django: Get previous value in clean() method
I have a model CustomModel with an IntegerField. class CustomModel(models.Model): count = models.DateTimeField() When I create a new instance of CustomModel in the admin, I have to do validation, so I use the clean method and have access to the value with def clean(self): value = self.count ... My problem: When I change the instance of CustomModel, I only have access to the new, changed value but not to the original value. However, for my validation I have to compare the new value and the value before the instance got edited. I could not found a solution how to get access. Does somebody know? -
Django-url cmd server error
from django.contrib import admin from django.urls import path from adoptions import views urlpatterns = [ path('admin/', admin.site.urls), path(r'^$', views.home name='home'), path(r'^adoptions/(\d+)/', views.pet_detail, name='pet_detail'), ] this is my code when I run python manage.py runserver... It returns a syntax error.. saying third line in urlpatterns "name" error which is (name='home') here.. -
edit/update functionality on a page in django which also has ajax calls
Problem I want to provide edit functionality to user on a page which was created by him/her. This page also has few ajax calls. The main issue is how can I show the values as selected/marked which were previously chosen by the user and now while editing he can unselect those and choose new values if he wants? Details A teacher can make worksheet, which will be shared with other teachers and the creator of worksheet might need to edit that as per the feedback from others. Right now the worksheet creation flow is on two pages: First page to filter questions based on class, topic, difficulty etc. Second page to preview questions and put extra details like due_date, duration, sharing with others etc and save to database. views.py 1st page view def question_filter(request): if request.method == 'POST': request.session['question_pk'] = request.POST.getlist('question_pk') ## other values stored in request.session ## return HttpResponseRedirect(reverse('qapp:question_preview')) else: form = QuestionFilterForm() return render(request, 'apps/qapp/question_filter.html', {'form':form}) 2nd page view def question_preview_and_save_worksheet(request): question_pk_list = request.session['question_pk'] ## retrieve values stored in request.session ## if request.method=='GET': // some logic for get request // return render(request,'apps/qapp/question_preview.html',some_context}) elif request.method == 'POST': worksheet_data = {} worksheet_data['classroom'] = classroom [#other data required for worksheet creation#] … -
Build a webpage by Django ,funcitons dose not work
here's my html code: <span> <button onclick="indexOBJ.clear();return false;" class="resetButton">清空</button> </span> here's my js code: var indexOBJ={ clear: function () { $('#devSvnURL').val(''); $('#devVersion').val(''); $('#testExampleUrl').val(''); $('#testReportDemoUrl').val(''); $('#resultLocation').val(''); $('#username').val(''); $('#userpwd').val(''); $('#commitTextArea').val(''); $('#note').val(''); } }; function clearAA() { alert() } it works fine but when I change my html code to : <span> <button onclick="clearAA();return false;" class="resetButton">清空</button> </span> the function named clearAA() will never be called. I don't know why . PLZ tell me the reason. Thanks a lot Environment : Django 2.0.2 jquery-3.3.1.js -
Django: Minimum disqus comments integration example in development
I want to test disqus comments in development mode. I know that django-disqus is the package that helps integrate disqus comments but can't really figure out the way forward. I have a Post model in models.py as follows. class Post(models.Model): title = models.CharField(max_length=250) slug = models.SlugField(max_length=300, unique_for_date='publish') author = models.ForeignKey(settings.AUTH_USER_MODEL) body = models.TextField() publish = models.DateTimeField() In my templates I have, {% extends "blog/base.html" %} {% block title %} Blog | {{post.title}} {% endblock %} {% block content %} <p> <b>{{post.title}}</b> </p> <p> {{post.body}}</p> <p>Written by: {{ post.author }} on {{ post.publish }}</p> <hr> {% endblock %} {% block domready %} {% endblock %} So, my question is: Is it possible to integrate Disqus in development on my local machine? If yes, please provide reference/blog/hints so that I can integrate disqus comments in my blog.