Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django : automatic retry of failed database operations
Database operations can fail because of temporary network errors or because the database is temporarily unavailable. Is there a way to automatically retry the operation in these cases ? The documentation of Google's managed database offering states that connection pooling systems should reconnect to the database if a connection is in a bad state, and applications should retry a database transaction if an error app in the middle of a transaction. (See https://cloud.google.com/sql/docs/postgres/manage-connections, section "Exponential backoff") How can I implement this advise using Django? I'm currently having problems with views that successfully perform some database operations but randomly encounter a connection error during a subsequent database operation. How can I retry the database operation so that the view is finally rendered successfully? -
Status code 400 (Bad Request) with Django API tests
I'm working on a project with Django as framework and poetry as manager. Running some tests I found some problems with my viewsets, but I don't know exactly where it is. That is the error traceback I'll paste here the tests, viewsets and models codes: That's the code from my 'test_orderviewset.py' file That's the code from my 'test_productviewset.py' file That's the code from my 'models.py' file And the code from serializers I created: class ProductSerializer(serializers.ModelSerializer): category = CategorySerializer(required=True, many=True) category_id = serializers.PrimaryKeyRelatedField(queryset=Category.objects.all(), write_only=True, many=True) class Meta: model = Product fields = ['title', 'description', 'price', 'active', 'category', 'category_id'] extra_kwargs = {'category': {'required': False}} def create(self, validated_data): category_data = validated_data.pop('category_id') product = Product.objects.create(**validated_data) for category in category_data: product.category.add(category) return product class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = [ 'title', 'slug', 'description', 'active', ] extra_kwargs = {'slug': {'required': False}} class OrderSerializer(serializers.ModelSerializer): product = ProductSerializer(required=True, many=True) products_id = serializers.PrimaryKeyRelatedField(queryset=Product.objects.all(), write_only=True, many=True) total = serializers.SerializerMethodField() # Model function method def get_total(self, instance): total = sum([product.price for product in instance.product.all()]) return total def create(self, validated_data): products_data = validated_data.pop('products_id') user_data = validated_data.pop('user') order = Order.objects.create(user=user_data) for product in products_data: order.objects.add(product) return order class Meta: model = Order fields = ['product', 'total', 'user', 'products_id'] extra_kwargs = … -
Change the main database to Test when using Pytest
Help me solve the problem Here is my settings.py: DATABASES = { "default": { "ENGINE": "django.db.backends.mysql", "NAME": ENV.MYSQL_DSN.path.lstrip("/"), "USER": ENV.MYSQL_DSN.user, "PASSWORD": ENV.MYSQL_DSN.password, "HOST": ENV.MYSQL_DSN.host, "PORT": ENV.MYSQL_DSN.port, }, 'test': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'test_db', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '5432', } } Here is my test_api.py: import json import pytest from django.urls import reverse from rest_framework import status from rest_framework.test import APIClient @pytest.fixture def api_client(): return APIClient() def test_proxys(api_client): url = reverse("gelet") response = api_client.get(url) assert response.status_code == status.HTTP_200_OK assert response["Content-Type"] == "text/html; charset=utf-8" assert b"<html>" in response.content @pytest.mark.django_db def test_generate_report(api_client): url = reverse("generate_report") data = { "dates": "01/01/2021 - 03/01/2021", "ip": "127.0.0.1", } response = api_client.post( url, data=json.dumps(data), content_type="application/json", ) assert response.status_code == status.HTTP_200_OK assert response.json() == {"status": "started"} How can I force autotests to use the test database test? It is important for me to understand which method can work. Please advise something. If there is an option with separate creation of a Postgres database, for example, this is also a suitable option I tried to use sqlite3 by creating it directly in the program code, but something didn’t work out import sqlite3 def run_sql(sql): conn = sqlite3.connect(':memory:') cur = conn.cursor() cur.executescript(sql) conn.commit() conn.close() @pytest.fixture(scope='session') def django_db_setup(): … -
Django - Naive datetime field to time zone
I'm using Django to build an web app and I have a shift in datetime datas when I upload them. In settings.py I specify : TIME_ZONE = 'CET' USE_TZ = True When I upload data like 29/01/2024 14:00:00 , I have this message : DateTimeField my_table.date received a naive datetime while time zone support is active In the PostgreSQL database, datas are stored in UTC not CET, in my example: 2024-01-29 13:00:00+00 Django interpret naive datetime in UTC not in CET (UTC+1) despite my settings.py TIME_ZONE parameter. How can I define that datas are CET and store 2024-01-29 13:00:00+01 ? -
Problems with virtual env on django project
.venv/bin/activate : O termo '.venv/bin/activate' não é reconhecido como nome de cmdlet, função, arquivo de script ou programa operável. Verifique a grafia do nome ou, se um caminho tiver sido incluído, veja se o caminho está correto e tente novamente. No linha:1 caractere:1 .venv/bin/activate That, and more functions that i type when i started my project in django. I started a new project and i simply dont know what is happening. i tried to activate with ~.venv/bin/activate~ and all, but everything gives me the same error message -
form post function is not working django python
am new to python and starting with Django Blog project, with admin area the blog post submit successfully, trying to design a page outside admin control area with limited functionality. so far i try with this code View.py from blog.forms import BlogPostForm def new_post(request): if request.method == 'POST': form = BlogPostForm(data=request.POST, files=request.FILES) if form.is_valid(): blgpstfrm = form.save(commit=False) blgpstfrm.author = request.user blgpstfrm.slug = f"{(blgpstfrm.title)}" blgpstfrm.save() obj = form.instance return render(request, "blog/in/new_post.html", {'obj':obj}) else: form = BlogPostForm() return render(request, "blog/in/new_post.html", {'form':form}) Forms.py class BlogPostForm(forms.ModelForm): body = forms.CharField(widget=CKEditorUploadingWidget()) class Meta : model = BlogPost fields = {'title', 'slug', 'body', 'features_image','tags'} New_post.html <form method="POST">{% csrf_token %} <h1>Add New Blog</h1> {{form.media}} <div class="new-post-title">{{form.title}}</div> <div class="sidebar"> <div class="new-post-feature-image">{{form.features_image}}</div> <div class="new-post-tags">{{form.tags}}</div> </div> <div class="new-post-content">{{form.body}}<br/>{{form.slug}} </div> <button type="submit" class="button">publish</button> </form> </div> their is no error in terminal or pages after submit. but when checking in post page no post present other then the admin area posts. -
cropping image only works by triggering second time save method
I have a django application. And I try to crop an high resolution image to a smaller resolution image. The problem I am facing is that cropping the image only works when the save method is triggered for the second time. So not the first time when I trigger the save method. So in models.py I have an image property: images = models.ImageField( upload_to="media/photos/animals", blank=True, null=True, verbose_name="Foto") And the save method looks like: def save(self, *args, **kwargs): self.slug = slugify(self.name) if self.pk is not None: orig = Animal.objects.get(pk=self.pk) if self.images: if orig.images != self.images: # Perform the crop if the image is updated with a different image im = Image.open(self.images) # To standardize your color space if not already RGB im = im.convert("RGB") exif = None if 'exif' in im.info: # Exif data records orientation, among other things exif = im.info['exif'] output = BytesIO() square = 200 # Set the dimension x_final, y_final = square, square # Get image dimensions width = im.size[0] height = im.size[1] if width > height: # crop the largest square out of the center of a landscape image and resize x1 = (float(width/2)-float(height/2)) y1 = (height - height) x2 = ((float(float(width/2)-float(height/2))) + height) y2 = … -
How to make a proxy model's relationships return proxy models themselves
I've got a simple model relationship: class Author(models.Model): ... class Book(models.Model): author = models.ForeignKey(Author) ... but I've also got some proxy models building on top of those models: class ProxyAuthor(Author): class Meta: proxy = True class ProxyBook(Book): class Meta: proxy = True Is there a way to get ProxyAuthor.objects.get(pk=123).books() to return ProxyBook objects rather than Book objects? -
accesing request.user in a tabularinline
I have a ModelForm with multiple TabularInlines that I want to use in the admin. I want to know which user changed something using the inlines. class ResourceForm(forms.ModelForm): resource = forms.FileField(widget=CustomImageFile, ...) class Meta: model = Resource fields = ["resource"] def __init__(self, *args, **kwargs): self.user = kwargs.pop("user") super().__init__(*args, **kwargs) self.fields["resource"].widget.form_instance = self def clean(self): # i need the request.user here class ResourceTabularInline(TabularInline): model = Resource form = ResourceForm def get_formset(self, request, obj=None, **kwargs): formset = super().get_formset(request, obj, **kwargs) formset.user = request.user # <-- I hoped this would be in the kwargs later on return formset class FooAdmin(admin.ModelAdmin): inlines = [ResourceTabularInline,] unfortunately the key user is not in the kwargs of the __init__() method this way -> KeyError. How can I access the user -
Filter queryset based on values in the other queryset
I have the following model in django: class EmailSubscriber(BaseSubscriber): email = models.EmailField() name = models.CharField() Now let's say I made a queryset from EmailSubscriber Like below: queryset1 = EmailSubscriber.objects.all() Now I create another queryset like below: queryset2 = EmailSubscriber.objects.filter(some filters) I want to exclude those fields in queryset1 that have their email and name in queryset2. I mean, if a record in queryset1 has {"email": "john@gmail.com", "name": "john"} and there is a record in queryset2 with {"email": "john@gmail.com", "name": "john"}, the record in queryset1 must be excluded. So they must be unique together. How can I do that in an efficient way? Thanks in advance -
Django Beanstalk connection refused Error 502 no module named application
Ive been going back and forth with this. Like many in this context, I followed this guide. It worked when creating a skeleton django app but when applied to my existing local app, Im getting this error ModuleNotFoundError: No module named 'application' platform: Python 3.9 running on 64bit Amazon Linux 2023 this is my working directory pytrade .(Project Directory) ├── .ebextensions │ └── django.config ├── .elasticbeanstalk │ ├── config.yml │ ├── .gitignore ├── README.md ├── api (created app) │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── dataMethods │ ├── migrations │ ├── models.py │ ├── questrade_api │ ├── serializers.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── db.sqlite3 ├── manage.py ├── pytrade │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── requirements.txt wsgi.py """ For more information on this file, see https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pytrade.settings') application = get_wsgi_application() django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: pytrade.wsgi:application The WSGIpath is pointing to the right directory and file as far as I can tell. -
celery task not running when an object is declared , I am using def save_model function to call celery task as per requirement upon save
[2024-01-29 07:23:52,962: ERROR/MainProcess] Process 'ForkPoolWorker-16' pid:2871 exited with 'signal 11 (SIGSEGV)' [2024-01-29 07:23:54,730: ERROR/MainProcess] Task handler raised error: WorkerLostError('Worker exited prematurely: signal 11 (SIGSEGV) Job: 0.') Traceback (most recent call last): File "/Users/asim/Django/Practice-tool-ai-backend/ptenv/lib/python3.12/site-packages/billiard/pool.py", line 1264, in mark_as_worker_lost raise WorkerLostError( billiard.einfo.ExceptionWithTraceback: """ Traceback (most recent call last): File "/Users/asim/Django/Practice-tool-ai-backend/ptenv/lib/python3.12/site-packages/billiard/pool.py", line 1264, in mark_as_worker_lost raise WorkerLostError( billiard.exceptions.WorkerLostError: Worker exited prematurely: signal 11 (SIGSEGV) Job: 0. """ The above mentioned is an error I am getting in celery task I have a requirement to call openai API in django admin save_model function So when an admin user adds a listening task , I retrieve the transcript and pass it to the openai API to generate questions and store them in database. Which was previously workin perfectly fine , since openai takes a lot of time to return response I put that part of the code in the celery background task to save admin time .. but ran into that issue More over if i remove that code #tasks.py @shared_task def sleeptime(time, obj_id): sleep(time) try: obj = ListeningTask.objects.get(id=obj_id) # Continue with processing using the retrieved object transcript = obj.transcript print(transcript) except ObjectDoesNotExist: print(f"Object with ID {obj_id} does not exist.") and just leave the function … -
Python Django custom 404 page not working
I have essentially tried 2 solutions here. The first one: Created 404.html inside root templates directory which was supposed to be recognized by django. By the way have defined it in settings.py: 'DIRS': [BASE_DIR / 'templates'], The second solution i have tried: In urls.py: from django.conf.urls import handler404 handler404 = 'pdfapp.views.not_found' in views.py: def not_found(request, exception): return render(request, 'partials/not_found.html', status = 404) None of these solutions have worked. Neither youtube videos nor the other forms could help my case. -
SyntaxError: invalid syntax in manage.py in django and python project
I run python program in Django framework that showed error below it. File "manage.py", line 26 ) from exc ^ SyntaxError: invalid syntax command is python manage.py test. manage.py: """Django's command-line utility for administrative tasks.""" import os import sys import io from django.db.backends.mysql.schema import DatabaseSchemaEditor sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'xxxxx.settings') DatabaseSchemaEditor.sql_create_table += " ROW_FORMAT=DYNAMIC" try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() -
Unable to retreive data for profile page (possible authentication problem)
When I login, and then use the nav bar to go to profile page, it does not retreive any information. I am only trying to retreive the user's username for now to simplify the problem. Errors after clicking on 'Profile': GET http://localhost:8000/accounts/login/?next=/profile/ 404 (Not Found) UserProfile.vue:37 Error fetching user profile: Error: HTTP error! status: 404 at fetchUserProfile (UserProfile.vue:30:17) On the network tab, there are 2 names present for the profile: "profile/" has status code of 302 Found and "login/?next=/profile/" has status code of 404 Not Found. "profile/" preview tab shows this: "login/?next=/profile/" preview tab shows this: Here are the relevant parts of my code: views.py from django.contrib.auth import authenticate, login from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from .serializers import CustomUserSerializer from django.views.decorators.csrf import csrf_exempt from django.contrib.auth.decorators import login_required from django.http import JsonResponse @api_view(['POST']) def signup_view(request): if request.method == 'POST': serializer = CustomUserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({ 'response': "Successfully registered a new user.", 'username': serializer.data.get('username') }) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['POST']) def login_view(request): if request.method == 'POST': username = request.data.get('username') password = request.data.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return Response({ 'response': "Successfully logged in.", 'username': username }) … -
AttributeError at /blog/tag/security/. 'TaggableManager' object has no attribute 'get_reverse_joining_fields'
when I run the code i get 'TaggableManager' object has no attribute 'get_reverse_joining_fields'. I have read django documentation it suggests doing it in the same way but I have no idea what went wrong. I would really appreciate any help. *models.py * from taggit.managers import TaggableManager class Post(models.Model): tags = TaggableManager() title = models.CharField(max_length=200) body = models.TextField(max_length=200) publish = models.DateTimeField(default=timezone.now) slug = models.SlugField(blank = True, max_length=200) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="author_post")``` *admin.py* from .models import Comment, Post # Register your models here. @admin.register(Post) class PostAdmin(admin.ModelAdmin): list_display = ('title','slug','body', 'slug','author', 'created', 'publish','updated','status') search_fields = ('author__username','title') list_filter = ('title','author__username','created') search_help_text="Search by author username or title" prepopulated_fields = {'slug':('title',)} raw_id_fields = ['author'] *views.py* def post_list(request, tag_slug=None): post_list = Post.objects.filter(status=Post.Status.PUBLISH) tag = None if tag_slug: tag = get_object_or_404(Tag, slug = tag_slug) post_list = post_list.filter(tags__name__in=[tag]) paginator = Paginator(post_list, 100) page_number = request.GET.get('page',1) try: posts=paginator.page(page_number) except EmptyPage: posts=paginator.page(paginator.num_pages) except PageNotAnInteger: posts = paginator.page(1) return render(request, 'blog/post/list.html', context={"posts":posts, 'tag':tag}) *urls.py* --> app level from django.urls import path from . import views app_name='blog' urlpatterns=[ path('', views.post_list, name='post_list'), path('<int:id>/share/', views.post_share, name='post_share'), path('tag/<slug:tag_slug>/', views.post_list, name='post_list_by_tag'), path('<int:id>/comment/', views.post_comment, name='post_comment'), path('post/<int:id>/', views.post_detail, name='post_detail'), ] -
Django Report Builder - Override Toolbar Header
Is there anyway to override the Django Report Builder toolbar header? Ive isoloated it down to this: span _ngcontent-chv-c159="">Welcome to Django Report Builder </span But don't understand how to override it? I've tried overriding the elements within the template but it doesn't seem to change anything...good chance I'm way off with my thinking here. -
PLEASE, The QuerySet value for an exact lookup must be limited to one result using slicing
It displays a table with reports and I would like to display additional information according to the report, how can I do this? e.g. a table with the details of the report is displayed, and in the browser I want to display additional information, displaying the report itself works, but when I add additional information to the code, an error appears models.py class Submissions(models.Model): submissions_number_id = models.CharField(max_length=10,blank=True, unique=True, default=create_new_ref_number,editable=False) contents = models.TextField() class AdditionalInfo(models.Model): submission = models.ForeignKey(Submissions, on_delete=models.CASCADE, related_name='additional_info', default='') contents = models.TextField() I tried this but I get an error views.py def Schedule(request): date = datetime.date.today() report=Submissions.objects.filter(execution_date=date) info=AdditionalInfo.objects.filter(submission=report) context={ 'date':date, 'report':report, 'info':info, } return render(request, 'staff/work_schedule.html', context) html <tbody> {% for qs in report %} <tr style="font-size: 10px;text-align: center;"> <th style="width: 8%;">{{qs.client.user.get_full_name}}, tel.: {{qs.client.phone_number}}</th> <th style="width: 8%;">{{qs.client.post_code}} {{qs.client.city}}, ul.{{qs.client.street}}</th> <th style="width: 40%;">{{qs.contents}}</th> <th style="width: 40%;">{{info.contents}}</th> </tr> {% endfor %} </tbody> -
Why aren't the environment variables working inside my Django Docker container?
I'm encountering an issue where Django doesn't seem to be reading environment variables when running in a Docker-compose environment. Strangely, the environment variables work fine for PostgreSQL but not for Django. I've tried both the env_file and environment options in my Docker-compose file, and I've also experimented with django-dotenv without success. Here's a snippet of my code: print(f" {os.environ.get('SECRET_KEY')} {os.environ.get('DEBUG')} {os.environ.get('DATABASE_NAME')} ") # The above print statement outputs None for all environment variables SECRET_KEY = os.environ.get("SECRET_KEY") # ... version: '3.9' services: db: # ... web: build: ./src command: gunicorn myapp.wsgi:application --access-logfile /logs/gunicorn/access.log --error-logfile /logs/gunicorn/error.log --bind 0.0.0.0:8000 volumes: # ... # env_file: #not working # - .env environment: - SECRET_KEY=${SECRET_KEY} - DATABASE_NAME=${DATABASE_NAME} # ... (other environment variables) nginx: # ... SECRET_KEY=3df-81ioo^5cx(p9cl$)s%m3mlu3t7*yh#1lr5h0po4_sab3*5 DATABASE_NAME=mydb DATABASE_USER=postgres DATABASE_PASS=postgres DATABASE_HOST=db DATABASE_PORT=5432 DEBUG=0 -
How do I add fields to the django_rest_auth response object?
I am extending the default django rest auth Login class in order to add 2 fields to the response object; the user's subscription and email addresses. from dj_rest_auth.serializers import LoginSerializer class CustomLoginSerializer(LoginSerializer): subscription = SubscriptionSerializer(read_only=True) email_addresses = EmailAddressSerializer(read_only=True, many=True) class Meta: model = User # fields = ['pk', 'username', 'email'] fields = ['pk', 'username', 'email', 'subscription', 'email_addresses'] def to_representation(self, instance): print('instance: ' + instance) data = super(CustomLoginSerializer, self).to_representation(instance) data['subscription'] = instance.user.subscription data['email_addresses'] = instance.user.email_addresses.all() data['lol'] = 'lmao' return data This is the response object. Note the added fields aren't present. { "access": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzA2NTYxNjQyLCJpYXQiOjE3MDY0NzUyNDIsImp0aSI6ImFhYTg5OTNlODQ5MTRjODJhOGRjNGU3MDE5MjE4YzNkIiwidXNlcl9pZCI6NH0.1l7RtT8G1qL6Tq5RVzLe5ceu_mnNVJV8oW64An_-hHk", "refresh": "", "user": { "pk": 4, "username": "user102", "email": "user102@email.com", "first_name": "", "last_name": "" } } Since overriding the to_representation method doesn't seem to work, how do I add related fields to the response object? -
Skipping a step in a WizardView based on data entered in that step
I'm trying to build a formtools Wizard where a confirmation form is shown in one of the steps. The confirmation form is only show in specific cases (e.g. if a user has previously ordered the same item before), and it should no longer be shown after the user has confirmed. Basically, my code looks like this: def ask_confirmation(wizard): # Database conditions go here return user.has_ordered_same_item_before class ItemWizard(SessionWizardView): condition_dict = { "confirm": ask_confirmation, } ... Obviously, the step where the user is asked to confirm is never passed, because the condition is always True. I don't want to store the user's response in the database, it's just something that the wizard needs to "remember" and that I can check in the condition function. How can I test whether the user has confirmed and skip the form once they did? -
I couldn't get the CompoundSearchFilterBackend class in the django-elasticsearch-dsl-drf library to work properly
I'm using the CompoundSearchFilterBackend class in the django-elasticsearch-dsl-drf library to perform queries. However, I'm receiving all queries. Django==4.2.9 django-elasticsearch-dsl==7.3 django-elasticsearch-dsl-drf==0.22.5 Below is an example of cached data from Elasticsearch along with other relevant classes. { "took": 4, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 1, "relation": "eq" }, "max_score": 1, "hits": [ { "_index": "betik_app_municy_citizen_municipal_council", "_id": "1", "_score": 1, "_source": { "party_name": "party", "title": "title", "full_name": "erhan koçlar", "email": "test@hotmail.com", "id": 1, "substitute": false } } ] } } documents.py @registry.register_document class MunicipalCouncilDocument(Document): class Index: name = f"{APP_LABEL}_municipal_council" settings = { 'number_of_shards': 1, 'number_of_replicas': 0 } class Django: model = MunicipalCouncilModel fields = [ 'id', 'substitute' ] party_name = fields.TextField() title = fields.TextField() full_name = fields.TextField() email = fields.KeywordField() def prepare_full_name(self, instance): return f"{instance.person.name} {instance.person.last_name}" def prepare_email(self, instance): return instance.person.email def prepare_party_name(self, instance): return instance.political_party.name def prepare_title(self, instance): return instance.title.exp def get_queryset(self): # visible return super().get_queryset() \ .filter( visible=True ) \ .order_by('order_no') views.py class PaginateDocumentView(DocumentViewSet): """ Paginate municipal councils (cache) Paginate cached municipal councils """ document = MunicipalCouncilDocument serializer_class = MunicipalCouncilDocumentSerializer pagination_class = StandardPagination authentication_classes = [] filter_backends = [ CompoundSearchFilterBackend, ] search_fields = ( 'full_name', 'email' ) When … -
Signin Fails With Custom Errors
Signin is working flawlessly but, Signup returns with {"non_field_errors": ["Incorrect creds"]} Which I have specified in LoginSerializer. I think it's happening due to authenticate function but, I am not able to pinpoint the issue as when I print it, it returns None. Does anybody knows what could be the issue? I have given the whole code but, I reckon the problem is created in LoginSerializer.I have also, added the AUTHENTICATION_BACKENDS in settings.py and after then, it's still gives that error. Models: from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser class UserManager (BaseUserManager): def create_user(self, username, password, **extra_fields): if not username: raise ValueError("Username should be provided") user = self.model(username=username, **extra_fields) user.set_password (password) user.save() return user def create_superuser(self, username, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(username, password, **extra_fields) class User (AbstractBaseUser): id = models.AutoField (primary_key=True) name = models.CharField(max_length=100) email = models. CharField (max_length=60) password = models. CharField (max_length=16) username = models. CharField (max_length=100, unique=True) USERNAME_FIELD = 'username' objects = UserManager() Serializers: from rest_framework import serializers from .models import User from django.contrib.auth import authenticate class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) email = serializers.CharField(required=False) name = serializers.CharField(required=False) class Meta: model = User fields = ('username', 'password', 'email', 'name') def create(self, validated_data): user = … -
Value error on custom log filter when importing unrelated module
I have the setup below that I'm using to inject extra data from the request object into each log message and it works fine. I recently needed to import a urls.py file from another app into the auth_middleware.py file to check all registered DRF routes and redirect appropriately, but I immediately got ValueError: Unable to configure filter 'session_context' each time I attempt to start the application. The import statement that is triggering this error (called from auth_middleware.py) looks like this: from apps.app_name.api.urls import router proj/middleware/auth_middleware.py import threading local = threading.local() class CheckUserLogin: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): setattr(local, "uip", request.META.get("REMOTE_ADDR")) setattr(local, "sid", request.session.session_key or "n/a") if request.user.is_anonymous and request.path != reverse("auth_service_login"): # apply redirect login and send to url_login return HttpResponseRedirect(url_login) return self.get_response(request) services/log_ctx.py import logging from proj.middleware.auth_middleware import local class ExtraLogCtx(logging.Filter): def filter(self, record): defs = "n/a" record.uip = getattr(local, "uip", defs) record.sid = getattr(local, "sid", defs) return True proj/settings.py MIDDLEWARE = [ ... "proj.middleware.auth_middleware.CheckUserLogin", ] LOGGING = { "filters": { "session_context": { "()": "services.log_ctx.ExtraLogCtx", }, }, "handlers": { "console": { ... "filters": ["session_context"], ... }, }, } I have __init__.py in the services and middleware folders and am unsure where else to look. Any … -
Stream Zeros with Django with StreamingHttpResponse
I have to send an amount of Zeros as response, defined by the request. They have to be plain zeros. (I know, a rather odd task...) so, for example, you need 100mb of zeros, you query ?size=100&unit=mb, you will get a stream of 100mb only zeros. Since it can be up to 16gb of zeros, I do not want to generate them at first, rather generate a stream of zeros and send this "line by line". This is what I came up with, but it does not behave like I want because it first gathers the full data and then sends it. class CreateImageAndResponseView(View): line_count = 0 def get(self, request): size_str = request.GET.get('size', '') unit = request.GET.get('unit', '').lower() if unit not in ('gb', 'mb'): return HttpResponse(status=400) try: size = float(size_str) if unit == 'gb': size_bytes = int(size * 1024**3) else: size_bytes = int(size * 1024**2) except ValueError: return HttpResponse(status=400) self.line_count = size_bytes // 1024 return StreamingHttpResponse((b'0' * 1024 for _ in range(0, self.line_count)), content_type='application/octet-stream',) I already saw Problem with Django StreamingHttpResponse, but I do not know which middleware could block this. Also, I am not running nginx or apache, just django from my console.