Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - customized password validator - error in path to my validators.py
I want to add my own password validator in my django project 'MyProject' so I create a validators.py file in my registration app but don't know how to set in my settings? settings.py AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, { 'NAME': 'MyProject.registration.MyValidator', }, ] validators.py from django.core.exceptions import ValidationError from django.utils.translation import gettext as _ class MyValidator: def __init__(self): def validate(self, password, user=None): if password == 'banane': raise ValidationError( _("This password must contain at least 2 special characters."), code='invalid_password', params={}, ) def get_help_text(self): return _( "Your password must contain at least 2 special characters." ) -
REMOTE_USER is empty in the django after redirecting
It seems to me that I do not quite understand the REMOTE_USER variable. I have three instances based on different hosts: nginx, django_auth_server, django_app_server. I am trying to implement "single sign on": the user logs on to the django_auth_server via nginx, is redirected to the django_app_server and continues surfing without authentication. In my case after redirection to the root folder (from '/login' to '/') the REMOTE_USER variable is empty. But it does exists in the request headers: Content-Type: text/html; charset=utf-8 Location: / REMOTE_USER: alfabeta X-Frame-Options: SAMEORIGIN Vary: Cookie Content-Length: 0 Set-Cookie: csrftoken=... Set-Cookie: sessionid=... Code from the authorization view (djangoauth instance): if user is not None: login(request, user) r = redirect('/') r['REMOTE_USER'] = username return r I'm not sure if it is correct to set the variable in this way. part of the nginx config server { listen 8080 default_server; server_name localhost; charset utf8; autoindex off; underscores_in_headers on; proxy_pass_request_headers on; ... location / { include /etc/nginx/uwsgi_params; uwsgi_pass uwsgiapp; uwsgi_read_timeout 300; uwsgi_param Host $host; uwsgi_param X-Real-IP $remote_addr; uwsgi_param X-Forwarded-For $proxy_add_x_forwarded_for; uwsgi_param X-Forwarded-Proto $http_x_forwarded_proto; } location =/login/ { include /etc/nginx/uwsgi_params; uwsgi_pass uwsgiauth; uwsgi_read_timeout 300; uwsgi_param Host $host; uwsgi_param X-Real-IP $remote_addr; uwsgi_param X-Forwarded-For $proxy_add_x_forwarded_for; uwsgi_param X-Forwarded-Proto $http_x_forwarded_proto; uwsgi_param REMOTE_USER $remote_user; } How to … -
Formset using class-based views with multiple instance
I want to use formset to add multiple todo at once, I have been told to use formset, which is exaclty what I am looking for, but all the documentations and video tutorials are using function based view. I have my models.py class Todo(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE,verbose_name="Nom de l'utilisateur") text = models.CharField(max_length=150, verbose_name="Nom de la Todo") content = models.TextField(verbose_name="Description supplémentaire",null=True, blank=True) date_posted = models.DateTimeField(default=timezone.now) complete = models.BooleanField(default=False, verbose_name="Statut de la Todo") urgence = models.BooleanField(default=False,verbose_name="Tâche urgente") def __str__(self): return self.text def get_absolute_url(self): return reverse('dashboard-home') To me, that should be enough because i have author as foreignkey, of course I import formset_factory at the top. But then it's very not clear for the view Views.py class TodoCreateView(SuccessMessageMixin, LoginRequiredMixin, CreateView): model = Todo fields = ['text','urgence'] success_message = 'Votre tâche a bien été ajoutée' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) How everything should work ? The purpose of this is just to add multiple todo at once, nothing too difficult, but I struggle. Just an example : This, but with multiple input. Thanks for your help -
Facing issues while integrating "Klarna" Payment Gateway in Django-Oscar
I'm trying to add the klarna javascript SDK into my site in which I need the client_token.and also created the test environment where I got the API key inside this have got the username and password for my test merchant account. Below is my template file: <script> window.klarnaAsyncCallback = function () { try { Klarna.Payments.init({ client_token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.dtxWM6MIcgoeMgH87tGvsNDY6cHWL6MGW4LeYvnm1JA' // replace this client_token with your }) } catch (e) { // Handle error. } }; </script> <script src="https://x.klarnacdn.net/kp/lib/v1/api.js" async></script> the client_secret is given in the documentation and also it is mentioned in the document that first, we have to create a session. so I tried to create through API but didn't get the proper solution for creating it. so I have few questions about the integration: How can we get the client_token to integrate the javascript SDK in django oscar ?. Is it necessary to create the session to integrate the klarna payment gateway in django oscar ? How can we use the test account credential for creating the session and client_secret A Mockup example to get me started in the right direction will be helpful. -
how can i send JS data to django?
var typingTimer; var doneTypingInterval = 500; var searchedValue; $("#trackName").focusin(function(){ $(this).keyup(function(){ clearTimeout(typingTimer); if($(this).val()){ typingTimer = setTimeout(doneTyping, doneTypingInterval); } }); }); function doneTyping(){ searchedValue = ($("#trackName").val()); return searchedValue; } actually my aim is to get this searchedValue variable in django so that i can use this variable to access some song name from my django database. for eg: if i type "fad" in input element then searchedValue = "fad" then i want this variable in django so that i can use database query to access all the song with name "fad" thanks for the help in advance -
How i can change name of parameters in url routers DRF?
How i can change name of parameters in url? Like this //, but by default name of parametr is "pk" I make request to "api/product/1/rate/1/" and get {'product_pk': '1', 'pk': '1'}. I want to rename "pk" to "person_id". How to make this? router = routers.SimpleRouter() router.register(r'product', ProductViewSet) rate_router = routers.NestedSimpleRouter(router, r'product', lookup='product') rate_router.register(r'rate', RateViewSet, base_name='rate') -
Redirect to absolute URL
I am trying to redirect to a tenant sub-domain after registering a tenant in my site but I am receiving a namespace error. Views.py: domain = Domain() domain.domain = tenant.schema_name + '.localhost:8000' domain.tenant = tenant domain.is_primary = False domain.save() return HttpResponseRedirect(reverse(domain.domain)) Error: NoReverseMatch at /companies/company_registration/ 'company.localhost' is not a registered namespace How do I add a sub-domain, which I do not currently know, as a URL namespace? Or better yet, how to redirect to an absolute URL? -
language independent query with django-modeltranslation
I currently started to use django-modeltranslation in a Django app and I would like to make a query to retrieve the instance of a model, independent of the language set in the system. For example I have the following model: class Product(models.Model): description = models.CharField(max_length=200) sku = models.CharField(unique=True, null=False, max_length=30) price = models.DecimalField(max_digits=8, decimal_places=2) and the following in translation.py: class ProductTranslationOptions(TranslationOptions): fields = ('description', 'sku') translator.register(Product, ProductTranslationOptions) and the Django setting: gettext = lambda s: s LANGUAGES = ( ('en', gettext('English')), ('de', gettext('German')), ) MODELTRANSLATION_LANGUAGES = ('en', 'de') MODELTRANSLATION_DEFAULT_LANGUAGE = 'en' MODELTRANSLATION_FALLBACK_LANGUAGES = ('en',) Let's create a product instance: Product.objects.create(description_en='product en', description_de='product de', sku_en='sku-001', sku_de='sku-002', price=10.0) Now I want to find the instance with the sku sku-002, to retrieve the price of a product (which is independent of the language). Product.objects.filter(sku='sku-002') However this returns an empty MultilingualQuerySet. Only the following returns the correct Product instance. Product.objects.filter(sku_de='sku-002') or from django.utils import translation translation.activate('de') Product.objects.filter(sku='sku-002') I guess this is the intended behavior of django-modeltranslation, but sometimes it would be practical to find an instance independent of the language. A solution could be to iterate through all LANGUAGES and try to find the instance for each language: from django.conf import settings LANGUAGES = … -
Handle .envs in docker and gitlab ci without having it in the repository
I am running a dockerized django app that uses Gitlab CI for automated tests. In my .env/ folder I have a .local and a .production file that contains my environment variables that are read in my setup-file with env = environ.Env() env(...). I think that is pretty standard. Up until now my .env/local file was committed in my repository and the tests need it to run because in my docker compose file I have: env_file: - ./.envs/.local/.django - ./.envs/.local/.postgres and I run my tests in gitlab CI using docker-compose -f local.yml run django pytest. Now I do not want my local env file in my repository. Simply because it is bad practice and I would also like to store some secret keys like AWS etc in there. But then it breaks my tests. Is there any recommended way on how to achieve what I want? Or is that not possible? I tried to add another .secret file, but also this one I have to specify in my compose file. This seems to be related How do I add a .env file in gitlab ci during deployment stage? but there is nothing on how to do this with django, docker and … -
Django MEDIA_URL return https instead of http
I'm using Django 2.2.x and DRF. I have a model with FileField file = models.FileField(upload_to=get_media_upload_path) Files are uploading but on access the obj.file, it gives URL without HTTPS http://example.com/media/image.jpg I want it to be https://example.com/media/image.png Redirect is already setup in nginx config. But I want the response URL with https. -
Django how to annotate manytomany field with count
Considger the following: class ModelA(models.Model): pass class ModelB(models.Model): model_as = models.ManyToManyField(ModelA, db_index=True, related_name="model_bs", blank=True) model_bs = model_a_object.model_bs.all() for model_b in model_bs: print(model_b.model_as.count()) 3 2 So far so good. But I want to created an ordered list of model_bs depending on the count of model_as. My understanding is that simply this should do the trick: model_bs = model_a_object.model_bs.all().annotate(count=Count("model_as")).order_by('count') For some reason that doesn't work. When I print to check, the annotated count is wrong!! for model_b in model_bs: print(model_b.model_as.count(), model_b.count) 3 1 2 1 What did I do wrong? -
django-session-timeout: The current path, accounts/login/, didn't match any of these
I try to implement an autologout after user inactivity (lets says 15 minutes) I have read many things and there is as my understanding at least two possibilities: use the django-session-timeout write a personnalized middleware I try first to use the django-session-timeout but got the error: The current path, accounts/login/, didn't match any of these. in my settings.py I have defined LOGOUT_REDIRECT_URL = 'home' here is my project urls.py: from django.urls import path, include from . import views from django.conf import settings urlpatterns = [ path('', views.home, name='home'), path('registration/', include('django.contrib.auth.urls')), path('monitor/', include('monitor.urls')), path('randomization/', include('randomization.urls')), path('admin/', admin.site.urls), ] -
Retrieving images from Django from rest_framework
models.py: from __future__ import unicode_literals from django.db import models class Photo(models.Model): title = models.CharField(max_length=255, blank=True) file = models.FileField() uploaded_at = models.DateTimeField(auto_now_add=True) serializers.py: from rest_framework import serializers from . models import Photo class imageSerializer(serializers.ModelSerializer): class Meta: model = Photo fields='__all__' views.py: from django.shortcuts import render,redirect from django.http import JsonResponse from django.views import View import time from rest_framework import generics from .forms import PhotoForm from .models import Photo from django.http import HttpResponse from rest_framework.response import Response from django.shortcuts import get_object_or_404 from rest_framework.views import APIView from rest_framework import status from .serializers import imageSerializer import requests class DragAndDropUploadView(View): def get(self, request): photos_list = Photo.objects.all() return render(self.request, 'UploadMulti/drag_and_drop_upload/index.html', {'photos': photos_list}) def post(self, request): form = PhotoForm(self.request.POST, self.request.FILES) if form.is_valid(): photo = form.save() data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url} else: data = {'is_valid': False} return JsonResponse(data) def clear_database(request): for photo in Photo.objects.all(): photo.file.delete() photo.delete() return redirect(request.POST.get('next')) class ImagesList(APIView): def get(self,request): imagelist=Photo.objects.all() serializer = imageSerializer(imagelist,many=True) return Response(serializer.data) def post(self): pass def backend(request): response = requests.get('http://localhost:8000/images/') api_values = response.json() for values in api_values: print(type(values['file'])) return render(request,"home.html",{'data':api_values}) when I print type of values.file which is the image data I am getting as therefore when sending it to frontend the image is not displayed How to retrieve as … -
Django ModelAdmin: how to ask password using two secret fields?
This is my custom user model: class CustomUser(AbstractUser): created = models.DateTimeField(auto_now_add=True) username = models.CharField(max_length=100, unique=True) email = models.EmailField(max_length=200, unique=True) company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='%(class)s_company') Since there is a foreign key field, I have created a custom ModelAdmin: class CustomUserAdmin(admin.ModelAdmin): exclude = ('groups', 'user_permissions', 'date_joined') list_display = ('username', 'email', 'company') Otherwise it works fine, but there is only one, clear-text password field shown. How can I modify it so that Django Admin would ask the password using the default two field approach? -
Djongo issue with "id" field and existing mongo db
I'm trying to use django+djongo and an already existing mondo database. The collection I need to read is like this: { "_id" : ObjectId("5dde69143f664504b7149fed"), "name" : "example_123456", "hash" : { "md5" : "d9feb4e791077aeba4e946696a2fbf8a", "sha256" : "72f7a877db57e43580495d0ac05615138a73e3f8507781188d4469b1bf09389b", "sha1" : "38e600408e141389d0bb0baaf6a2e0594411a34d" }, } So in my models.py I've created these two models: class Hash(models.Model): md5 = models.TextField() sha256 = models.TextField() sha1 = models.TextField() class Meta: db_table = "hash" abstract = True class ExampleCollection(models.Model): name = models.TextField() hash = models.EmbeddedModelField( model_container=Hash ) class Meta: db_table = "example_collection" Now the problem is that when I try to read something from this collection (for example even a ExampleCollection.objects.all()), I get a MigrationError: Exception Type: MigrationError Exception Value: id I've noticed (by creating a "test" model) that django/djongo automatically add an "id" field in my models (that acts as a primary key), but since it doesn't exist in this collection, I get this exception. -
How to run two django apps in same server with different dynamic DJANGO_SETTINGS_MODULE env variables
I'm running two django application in same server, server setup and multi settings file are created. But i have DJANGO_SETTINGS_MODULE env variable as dynamic, i need to set two different values. If i change DJANGO_SETTINGS_MODULE variable name to something else, i'm getting error. Can anyone suggest some solution for this problem. -
Python - Create multiple user types and email as the username field in Django 2
I'm working on a project using Python(3.7) and Django(2.2) in which I have to implement multiple types of users as: Personal Account - below 18 Personal Account - above 18 Parent Account Coach Account Admin along with that, I also need to use email as the username field for login/authentication. The strategy I'm trying to use is to build a custom base model as User inherited from AbstractBaseUser and also created a custom User Manager to make the email as username but it's not working. Here's my complete model code: class UserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): if not email: raise ValueError('Users must have an email address') now = timezone.now() email = self.normalize_email(email) user = self.model( email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email=None, password=None, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) def create_superuser(self, email, password, **extra_fields): user = self._create_user(email, password, True, True, **extra_fields) user.save(using=self._db) return user def generate_cid(): customer_number = "".join([random.choice(string.digits) for i in range(10)]) return customer_number class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) is_personal_above_18 = models.BooleanField(default=False) is_personal_below_18 = models.BooleanField(default=False) is_parent = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD … -
How to stop User Agent Stylesheet from overriding my CSS
I have the following CSS .imagetable{ border-collapse:collapse; width:100%; height:100%; } and HTML: <table class="imagetable"> <tr> <th><img src="{% static "images/myimage1" %}"></th> <th><img src="{% static "images/myimage2" %}"></th> </tr> <tr> <td><a href='myurl'><button>button1</button></a></td> <td><a href='myurl'><button>button2</button></a></td> </tr> </table> But whenever I run this and look in Google Chrome F12 I see not my own CSS but this: table { user agent stylesheet display: table; border-collapse: separate; border-spacing: 2px; border-color: grey; Annoyingly my CSS works everywhere else other than this table. Any ideas? -
How to Install Pillow on Openshift
I'm trying to deploy my django web application on OpenShift. When I try to deploy it I get this error: I have no idea how I can access the terminal in the openshift to install pip. -
Start 'python manage.py runserver' of django within jupyter notebook
I would like to create small application in Django. However, main requirement for this application is to be started within jupyter notebook, as every user will have such application locally. Plotly dash (from which I would like to rewrite this app) allows app.runserver() inside jupyter cell, which afterwards starts the app. However this is not available for django in the jupyter notebook. I could do !python manage.py runserver This spawns server correctly. But this server is not 'killable' using the interrupt button inside jupyter notebook - which is important feature of this approach. Same applies for os.system or subprocess.Popen. I tried also approach from this question: Django runserver from Python script Which does not work in the jupyter notebook unfortunately. This raises zmq.error.ZMQError: Address in use Is there any other approach which I could try? -
Run specific function before executing any code in the view
I haven't worked too much with Django. Let's say I have three views. The url patterns that these views are mapped to all start with string Y. Suppose I want to run specific function X before running code that the views contain. Is there a way to run function X by adding it somewhere only once instead of adding the function call to to the beginning of each of these views separately? Would middleware be the recommended way to do this? -
What is proper way to store data in DateTimeField field
I have a model Fixture Class Fixture(models.Model): event_timestamp = models.DateTimeField(null=True) I have piece of json data for item in piece_json: event_timestamp = item["event_date"] Where in item["event_timestamp"] the following data 1572567600 While i am trying to create object from this model fixture = Fixture.objects.create(event_timestamp= event_timestamp) I got the following error match = datetime_re.match(value) TypeError: expected string or bytes-like object After this error i tried to wrap event_timestamp variable in built-in str() function fixture = Fixture.objects.create(event_timestamp= str(event_timestamp)) After it i got error django.core.exceptions.ValidationError: ["'1572651000' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."] -
Loggedin pages after authintification
I am learning django and make mini project for learning pupose and as example took kidgarden. I have a directorry gun and with two apps inside it accounts and equity apps. I want only registered users to be able to see equity app which requires to get information and after clicking ok button brings a user to another page that bring users info. In accounts i have templates with login signup htmls like following.This section works fine without any problem. Then i created equity app. where i have forms.py: from django import forms from .models import Child class ChildForm(forms.ModelForm): name = forms.CharField(max_length=150, label='',widget= forms.TextInput (attrs={'placeholder':'Ticker'})) class Meta: model = Child fields = ('name',) models.py : from django.db import models from django.contrib import auth class Child(models.Model): name = models.CharField(max_length=150, blank=True) and views.py : from django.shortcuts import render from .forms import ChildForm def home(request): stock = ChildForm() if request.method == "POST": stock = ChildForm(request.POST) if stock.is_valid(): data = stock.save(commit=True) name = data.name context={ 'name':name, } else: stock = ChildForm() return render(request,'equity/search.html',{'stock':stock}) return render(request,'equity/analysis.html',context) return render(request,'equity/search.html',{'stock':stock) in gun /setting.py i inserted this info LOGIN_REDIRECT_URL = 'kids' so if a user is logged in it bring them to kid.html page in main directiory (gun) … -
How to pass class-based view data to django formset
I have a formset that is rendered using a class-based view. I get a 404 error when project_id = kwargs.pop('project_id',None) in the def get_context_data function below. The formset doesn't render at all when project_id = kwargs.pop('project_id',None) in the def __init__(self,*args,**kwargs) function below. project_id is the auto-generated id in the ProjectDetails model. How can get project_id to be passed to the formset? models.py class ProjectDetails(models.Model): project_name = models.CharField(max_length = 50,blank = False) client = models.CharField(max_length = 200,blank = False) class ProjectFinance(models.Model): project_name = models.ForeignKey(ProjectDetails,on_delete = models.CASCADE, null = True,blank=False) finance_item = models.CharField(max_length = 50,null=True,blank=False) forms.py class FianceForm(forms.ModelForm): def __init__(self,*args,**kwargs): project_id = kwargs.pop('project_id',None) super(FianceForm,self).__init__(*args,**kwargs) class Meta: model = ProjectFinance fields = '__all__' FinanceFormSet= inlineformset_factory(ProjectDetails, ProjectFinance, form=FianceForm, fields='__all__',extra=2) views.py class FinanceView(CreateView): template_name = "project.html" model = ProjectFinance form_class = FianceForm def get_form_kwargs(self,*args, **kwargs): form_kwargs = super(FinanceView, self).get_form_kwargs(*args, **kwargs) form_kwargs['project_id'] = self.kwargs.get('project_id') return form_kwargs def get_context_data(self,**kwargs): project_id = kwargs.pop('project_id',None) project = get_object_or_404(ProjectDetails,id=project_id) formset = FinanceFormSet(instance=project) context = super(FinanceView, self).get_context_data(**kwargs) context['project'] = project return context Thanks. -
Django - 'bool' object is not callable
I have a UserProfile Model that looks like this: class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile',on_delete=models.CASCADE) needhelp = models.BooleanField(default=True) def __str__(self): return self.user.username def get_absolute_url(self): return ('user:help', (), {'id': self.id}) Im working on a visual guide for a website and for a start I made a modal that asks the user if he needs help when he logs in. If he clicks "no" I want to change the needhelp bool to False and hide the modal. If he clicks "yes" I want to change the needhelp bool to True and start the guide. This is how far I got: class HelpToggle(RedirectView): def get_redirect_url(self, pk, *args, **kwargs): obj = get_object_or_404(UserProfile, pk=pk) url_ = obj.get_absolute_url() user = self.request.user if user.is_authenticated(): if user in obj.needhelp.all(): user.needhelp = False else: user.needhelp = True return url_ url(r'^help/(?P<pk>\d+)/$', HelpToggle.as_view(),name="help") But when I go to the url, I get 'bool' object is not callable Thank you for any help