Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error when using elasticsearch with django
I'm trying to use elasticsearch for my django project and following this tutorial with my own model: https://django-elasticsearch-dsl.readthedocs.io/en/latest/quickstart.html#populate My model: class Product(models.Model): STATUS = ( ('True', 'True'), ('False', 'False'), ) title = models.CharField(max_length=150) keywords = models.CharField(max_length=255) description = models.TextField(max_length=255) price = models.DecimalField(max_digits=12, decimal_places=2,default=0) image=models.ImageField(blank=True) amount=models.IntegerField(default=0) minamount=models.IntegerField(default=3) slug = models.SlugField(null=False, unique=True) status=models.CharField(max_length=10,choices=STATUS) create_at=models.DateTimeField(auto_now_add=True) update_at=models.DateTimeField(auto_now=True) rating = models.IntegerField(default=0) def __str__(self): return self.title my documents.py: # documents.py from django_elasticsearch_dsl import Document from django_elasticsearch_dsl.registries import registry from .models import Product @registry.register_document class CarDocument(Document): class Index: # Name of the Elasticsearch index name = 'products' # See Elasticsearch Indices API reference for available settings settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = Product # The model associated with this Document # The fields of the model you want to be indexed in Elasticsearch fields = [ 'title', 'keywords', 'status', 'description', ] # Ignore auto updating of Elasticsearch when a model is saved # or deleted: # ignore_signals = True # Don't perform an index refresh after every update (overrides global setting): # auto_refresh = False # Paginate the django queryset used to populate the index with the specified size # (by default it uses the database driver's default setting) # queryset_pagination = 5000 … -
Minor trouble installing mod_wsgi into venv
I thought this question would help me understand my file system and how mod_wsgi installs on my macOS (even though i am also stuck). Simply i am experimenting with django and apache. i have two different django projects (very basic tutorials) with venv's and one basic web app in each. I have pip installed mod_wsgi into one and it has added the package to the venv successfully and runs fine. When i tried the other venv it replied: - Requirement already satisfied: mod_wsgi in /Users/mjwallis/opt/anaconda3/lib/python3.7/site-packages (4.8.0) I must have installed mod_wsgi more globally prior in this case (can't remember what i did). Guess this is v basic of me to ask for help but i have been hitting a wall for some reason! Also this my first StackOverflow question! If anyone has time to reply it would be a relief!! -
How to check if an object has more than constant number of many to many field objects
I have 2 tables say "A" and "B" having ManyToMany relationship with one of the field with table "A", I have created a Model Admin from where I am creating both the tables object. I have a constraint that I have to create constant number of "B" object for each fields (relation) I have written below code but it gives an error: ValueError: “needs to have a value for field ”id“ before this many-to-many relationship can be used count = 10 class A(models.Model): field_a = models.CharField(max_length=100) class B(models.Model): field_b = models.CharField(max_length=100) fields = models.ManyToManyField(A, related_name="bs") def save(*args, **kwargs): for item in self.fields.all(): if item.bs.count() > count: raise ValidationError( "item count is exeeded" ) return super(B, self).save(*args, **kwargs) Please suggest how to handle this case. -
How can I make a separate database in django and not use the default database?
Okay, so I am a complete newbie and this might be a silly question but I couldn't find any answer related to this. I have created a login page using google authentication and it works perfectly but the problem it saves the user data directly into default database but I want it to be stored in my own mysql database. I want it to store the information that google authentication gave and store it in mysql database i.e email,name,etc . -
How to use cryptography to get private key of x509 certificate
As title, I have google many different way to get the private key from X509 certificate but unfortunately none of the solutions work for me. I have try solution from https://pyjwt.readthedocs.io/en/latest/faq.html but when I try to retrieve the private key, it give me the error message of '_Certificate' object has no attribute 'private_key' -
Django: Override SimpleListFilter get_queryset method (super(type, obj): obj must be an instance or subtype of type)
I'm trying to make a filter for users to filter them by created drafts. I'm stuck inside overriding the get_queryset. This is the error I get: super(type, obj): obj must be an instance or subtype of type What am I missing? class DraftFilter(SimpleListFilter): title = _('created drafts') parameter_name = 'user_drafts' def lookups(self, request, model_admin): return( ('has_drafts', 'Yes'), ('no_drafts', 'No'), ) def queryset(self, request, queryset): def get_drafts(status): return super().get_queryset(request).annonate( is_draft=Exists(Operation.objects.all().filter( company_id=OuterRef('active_company_id'), is_draft=status)) ) if not self.value(): return queryset if self.value().lower() == 'has_drafts': return get_drafts(True) if self.value().lower() == 'no_drafts': return get_drafts(False) -
Is there a way to call a django model function from a template inside an javascript function?
I am trying to trigger my note.send function (from a method) whenever I call a javascript function. Here is my Javascript code. function send_mail(){ {{ note.send }} } I then call the function send_mail() whenever an specific action happens on the website, however the django template function is called each time I reload the website even if I don't call the javascript function at all. Please help -
Here, i want to achieve that I want to take my current site's URL (not using forms) and convert those into short urls and display it here
in this picture I have written what i wanted to achieve. I am trying to use hashlib, but i am not able to do the following. This is my views. def SaveURL(request): full_url = request.META['HTTP_HOST'] obj = create_short_url('full_url') url = full_url=full_url, obj=obj url.save() return render(request, 'link.html', {"full_url": obj.full_url, "short_url": request.get_host()+'/'+obj.short_url}) #generating short link def create_short_url(self, request, full_url): temp_url = md5(full_url.encode()).hexdigest()[:8] try: obj = self.objects.create(full_url=full_url, short_url=temp_url) except: obj = self.objects.create(full_url=full_url) return render(request, 'link.html', {"obj": obj}) This is my html template, its just not so clean , plz help. #this is my original url {{ request.scheme }}://{{ request.META.HTTP_HOST }}{{ request.path }} #IT DISPLAYS - http://127.0.0.1:8000/product/product_view/10001 But i have not achieved the soln. -
Error 400 when adding Google Analytics Script
I put a Google Analytics tag in the header of my website: <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=G-V51YR2QF7N"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-V51YR2QF7N'); </script> But even after reloading the website in my pythonanywhere integrated development environment, still no statistics appear. I ran this code locally and here are the errors: (dja_env) C:\Users\antoi\Documents\Programming\Projects\django3-personal-portfolio>python manage.py runserver Looks like no local file. You must be on production Looks like no local file. You must be on production Performing system checks... System check identified some issues: WARNINGS: blog.Blog: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the BlogConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'. portfolio.Project: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the PortfolioConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'. System check identified 2 issues (0 silenced). May 30, 2021 - 21:20:44 Django version 3.2.3, using settings 'personal_portfolio.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [30/May/2021 21:22:47] "GET / HTTP/1.1" 400 143 … -
Set different logout time for different users in django?
Can anyone know how to set session timeout per user in Django? I'm building a system where I need to set a user timeout session, if a user is failed to perform any action till a timeout setting then he will be logout of the system. Is this possible in Django? -
Django Rest Framework Create New Data If Not Exist
I have been created a new user to user messaging app on Django. I want to if there is no User1i and User2ii created ever create new one and if it exist return the ID of this conversation. views.py class ConversatViewSet(viewsets.ModelViewSet): serializer_class = ConversatSerializer authentication_classes = (JSONWebTokenAuthentication,) permission_classes = (IsAuthenticated,) def get_queryset(self): queryset = Conversation.objects.all() return queryset models.py class Conversation(models.Model): User1i = models.ForeignKey(User, related_name='u1', on_delete=models.CASCADE) User2ii = models.ForeignKey(User, related_name='u2', on_delete=models.CASCADE) class Meta: unique_together = ('User1i', 'User2ii') JSON output [ { "id": 1, "User1i": 1, "User2ii": 2 }, { "id": 2, "User1i": 3, "User2ii": 1 }, { "id": 3, "User1i": 3, "User2ii": 2 } ] For example if "POST" to '1' as "User1i" and '2' as "User2ii" return the ID of conversation ("id": 1,) and if "POST" TO '4' as "User2i" and '2' as "User2ii" create a new conversation and return it's ID. -
supervisord/celery/python - "dynamic" environment variables - "global" versus "local" - DRY
Let's imagine I have the following /etc/supervisord.conf main file: [unix_http_server] file = /tmp/supervisor.sock [supervisord] <snip> environment = STATIC_VAR="foo", DYNAMIC_VAR="bar_%%s" [include] files = /etc/supervisord.d/worker1.conf /etc/supervisord.d/worker2.conf The worker1 and 2 files: [program:worker1] environment = WORKER_1_VAR_1"toto", WORKER_1_VAR_2="toto_too" [program:worker2] environment = WORKER_2_VAR_1"toto", WORKER_2_VAR_2="toto_too" (skipping the other file contents as they are not relevant) My supervisor version is 3.4.0 on Centos 7.9. This runs within a virtualenv on the back on Python 3.9.0 MAIN GOAL: Somewhere in the code run by one of the workers, something like this will occur (the "%%s" turned into "%s" will be replaced by a dynamic value): from django.conf import settings final_value = settings.DYNAMIC_VAR % ('replacement_string_of_some_kind') What happens is the above always results in an error upon supervisor startup: Error: Format string <snip> for 'supervisord.environment' is badly formatted: not enough arguments for format string HOWEVER, if I remove the supervisord.environment section from the main configuration file, and copy its contents to the individual worker files, startup occurs normally. For example: [program:worker1] environment = STATIC_VAR="foo", DYNAMIC_VAR="bar_%%s", WORKER_1_VAR_1"toto", WORKER_1_VAR_2="toto_too" Am I doing something wrong? Is there some kind of "double parsing" happening upon startup? Can this even be made to work. Asking because my list of "global env variables" is quite long, … -
Render dynamic value inside content django template
Please, I would like to render a varible in django template, kind of {{ user.name }} inside of a textfield from database, that I filled up on the django admin. like this how can I manage to achieve it please, thank you all, have a good day. -
Django Simple POST Class View Not Working
I am experimenting with Django class based views and for some reason this simple post view does not seem to be working. When looking at my terminal it gets stuck on the GET method / validation of the csrf token. It is either not being validated or not saving to the database and therefore not being redirected to the thank-you page. I am not sure how to solve this issue. It definitely is not being saved to the DB, but as far as I am aware everything is correct here. I also am using a class based form which is why I am simply just calling form.save() The code is as follows: class ReviewView(View): def get(self, request): form = ReviewForm() return render(request, 'reviews/review.html', { 'form': form }) def post(self, request): form = ReviewForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/thank-you') return render(request, 'reviews/review.html', { 'form': form }) Any help or ideas is greatly appreciated! -
Django Admin Custom User password not getting hashed+salted
I've created a custom user to use email instead of the username. This is the code that works models.py # Overriding the default users model from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ from django.db import models from django.contrib.auth.models import AbstractUser class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ 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 Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user 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) extra_fields.setdefault('is_active', 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 CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email and registered it to the admin modal for a more flexible list. (admin.py) from django.contrib import admin from .models import CustomUser @admin.register(CustomUser) class CustomUserADM(admin.ModelAdmin): list_display = ("email", "is_staff", "is_active") … -
how to deal with __init__ in serializers.ModelSerializer?
I need to create a dynamic serializer and inside it I need to get the method (GET/PUT/..) and the pk value if the url look like this url/1/ or url/2/ where 1 and 2 are pks. class DynamicSerializer(QueryFieldsMixin, serializers.ModelSerializer): def __init__(self, * args, **kwargs): super(DynamicSerializer, self).__init__(*args, **kwargs) modelname = self.Meta.model.__name__.lower() method = '' is_owner = False pk = None user = self.user class Myser(DynamicSerializer): class Meta: model = models.Model fields = '__all__' Myser(Mode).data I think there is somthing like slef.list, self.delete, self.create in the views where it looks like this class ItemView(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): MyModel = None def get_object(self, pk,): try: return self.MyModel.objects.get(id=pk) except self.MyModel.DoesNotExist: raise status.HTTP_404_NOT_FOUND def get(self, request, pk, format=None): item = self.get_object(pk) serializer = self.serializer_class(item, many=False) return slef.item(request) #<= this -
Send message using Django Channels from outside Consumer class from new Process
I am building an REST Api in Django for training and predict some data. I have a websocket connection with the purpose of having bidirectional communication. For non-blocking server when someone wants to train a new model I decide to use a new Process from multiprocessing. All work good but i can't send back a message when training is over from that Process. This is my consumer.py class import json from asgiref.sync import sync_to_async from channels.generic.websocket import AsyncJsonWebsocketConsumer, AsyncWebsocketConsumer import time import asyncio from multiprocessing import Process from .train import train from threading import Thread from channels.layers import get_channel_layer class Consumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.channel_layer.group_add("gossip", self.channel_name) await self.accept() async def disconnect(self, close_code): pass # Receive message from WebSocket async def receive(self, text_data): print(text_data) await self.send(text_data=json.dumps({ 'message': text_data })) data = "Works good" p = Process(target=train, args=(data,)) p.start() # Receive message from room group async def chat_message(self, event): message = event['message'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message })) async def sendMessageTrain(self): await self.send(text_data=json.dumps({ 'message': "Model success trained" })) async def notify(self, event): print("In notify method: Notify") print(event["content"]) await self.send(text_data=json.dumps({ 'message': event["content"] })) Channles layer settings: CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" # "BACKEND": "channels_redis.core.RedisChannelLayer", # "CONFIG": … -
How to solve unsupported locale setting in pandas
Error at ... unsupported locale setting cats = ['Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота', 'Воскресенье'] cat_type = CategoricalDtype(categories=cats, ordered=True) locale.setlocale(locale.LC_ALL, 'rus_rus' if sys.platform == 'win32' else 'ru_RU.UTF-8') df['w_date_to'] = df['w_date_to'].dt.day_name(locale='Russian').astype(cat_type) My Ubuntu server local settings: *locale -a* C C.UTF-8 POSIX ... en_US.utf8 ... ru_RU.utf8 ru_UA.utf8 *locale* LANG=en_US.UTF-8 LANGUAGE=en_US:en ... LC_ALL=C Thanks in advance. -
How to manage Postgres Enum type in Django?
I had used django-mysql to manage MySQL enum type from Django. Recently I am using the Postgres database for my Django project. To manage the Postgres Enum, I could not able to find any library. There is a db_type() method in Django to manage custom type. But the problem is Postgres enum must be created first at database and after that, I can use it. Here is a code sample for Postgres enum. CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy'); CREATE TABLE person ( name text, current_mood mood ); Is there present a library at all? If not, how could I be able to achieve the Postgres enum management from Django? -
I want to create work schedule for employees for crm system in django REST
**I could not find any helpful resource or any libs related to this.I have tried this library :https://github.com/rodrigoamaral/django-fullcalendar but it didnt help me ** -
What do I return if I override dispatch() method in Django?
So I am trying to write controller logic for my page search field. It suppose to search posts by title and display them. I am trying to implement a verification that the search field isn't empty and while at it I am also trying to let user know if there weren't posts to display. I am trying to do so via HttpResponses. The problem is I can't place'em in get_queryset method because it's supposed to return querysets not http responses, so I placed them in "view" part of CBV i.e. dispatch method and it works fine. But now I don't understand what to do to display the result when there's actually some posts found. I get Exception Value: The view blog.views.Search didn't return an HttpResponse object. It returned None instead. So what do I do to display posts when there are actually some to display? Thanks beforehand! My search field: <div class="email" align="right" style="margin: 100px 0 0 150px"> <h2 class="sidebar-title" align="center">Search Post</h2> <form action="{% url 'search' %}" method="get"> <input type="text" name="s" placeholder="Search Post"> <input type="submit" value="look up"> </form> </div> My view: class Search(ListView): """Searching Posts""" template_name = 'blog/posts_by_search.html' context_object_name = 'posts_found' paginate_by = 2 def dispatch(self, request, *args, **kwargs): """HttpResponse … -
Authentication fails during login testing
I am trying to test custom login (with pytest) but authentication fails returning None. Here is views.py from rest_framework.authtoken.views import ObtainAuthToken from my_auth.api.serializers import UserLoginSerializer class LoginAuthToken(ObtainAuthToken): serializer_class = UserLoginSerializer serializers.py from django.contrib.auth import authenticate from django.utils.translation import gettext_lazy as _ from rest_framework import serializers from rest_framework.authtoken.serializers import AuthTokenSerializer class UserLoginSerializer(AuthTokenSerializer): username = None email = serializers.EmailField( label=_("Email"), ) def validate(self, attrs): email = attrs.get('email') password = attrs.get('password') if email and password: user = authenticate(request=self.context.get('request'), email=email, password=password) # returns None if not user: msg = _('Unable to log in with provided credentials.') raise serializers.ValidationError(msg, code='authorization') # raises else: msg = _('Must include "email" and "password".') raise serializers.ValidationError(msg, code='authorization') attrs['user'] = user return attrs tests.py import pytest from django.urls import reverse from rest_framework import status from rest_framework.authtoken.models import Token from rest_framework.test import APIClient @pytest.fixture def test_user(): user = MyUser.objects.create( email='test@m.com', first_name='Firstname', last_name='Lastname' ) user.set_password('pass5678') return user @pytest.mark.django_db def test_login(test_user): client = APIClient() response = client.post( path=reverse('login'), data={ 'email': 'test@m.com', 'password': 'pass5678', }, format='json', ) assert(response.status_code == status.HTTP_200_OK) token = Token.objects.get(user=test_user) assert(token.key == response.data['token']) Terminal output: ========================================================================================================== test session starts ========================================================================================================== platform linux -- Python 3.8.5, pytest-6.2.4, py-1.10.0, pluggy-0.13.1 django: settings: news_project.settings (from ini) rootdir: /home/andrei/NEWS/news_project, configfile: pytest.ini plugins: lambda-1.2.4, Faker-8.4.0, common-subject-1.0.5, … -
Why is the Post model that I create in the admin panel not showing in the admin panel?
I do not understand why when I create a Post model in the admin panel, it is not displayed on my server in the admin panel enter image description here here is the code admin.py `from django.contrib import admin from .models import Post admin. site.register(Post)`, here is the code models.py `from django.db import models class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey( 'auth.User', on_delete=models.CASCADE, ) body = models.TextField() def __str__(self): return self.title` I will be glad to any of your advice and help -
TypeError at /ap1/checkbooks/ 'type' object is not iterable; return [auth() for auth in self.authentication_classes] TypeError: 'type' object is
I am getting django Error while using rest django concept. How to solve the below error of django i can't able to open the webpage in my browser. please let me know how to solve the issue.All the codes are below. Any help appreicatable . TIA Settings.py """ Django settings for pro1 project. Generated by 'django-admin startproject' using Django 3.2.3. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-_=f2k%yr6l&3sbcz#dpt5ec8t+7aw_i^2p*$$z0kt0iq!u0iag' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'ap1', ] 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 = 'pro1.urls' ''' REST_FRAMEWORK={ 'DEFAULT_PERMISSION_CLASSES':( 'rest_framework.permissions.IsAuthenticated', # for restriction ) }''' # for restriction access REST_FRAMEWORK={ 'DEFAULT_PERMISSION_CLASSES':( 'rest_framework.permissions.AllowAny', ), } TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { … -
Django Form to Model Before Save
I have a Django model called Family, and a Django form called FamilyForm. I save the form in a view as follows: if request.method == 'POST': form = FamilyForm(request.POST) if form.is_valid: form.save() messages.success(request, 'Successfully added the family') else: messages.error( request, 'There was a problem with adding the family') However, my problem is that I would first like to convert this form to a Family object before saving it as I would like to assign some missing properties. Any idea how to convert the form to a Model object so that I can make the changes before saving?