Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model class vs a dictionary for storing reference values
I'm fairly new to Django, and while creating a project, I've been going back and forth between using a fixed value dictionary for certain reference values, or using another model class which is referred using a Foreign Key field. A part of the code using the model class option is as follows: Models with reference values: class MaterialCategory(models.Model): name = models.CharField(max_length=32, unique=True, help_text="A primary class of materials.") class Meta: verbose_name_plural = 'Material categories' constraints = [ UniqueConstraint( Lower('name'), name='materialcategory_name_case_insensitive_unique', violation_error_message="Material category already exists in " "the database!" ), ] class ComponentType(models.Model): """Model for key component types of a water supply scheme.""" name = models.CharField(max_length=100, unique=True, help_text="Main categories of a water system") def __str__(self) -> str: return self.name class Meta: ordering = ["name", "id",] An example model referring to above: class Chlorinator(models.Model): """Model representing a chlorinator.""" CHOICES_YES_NO = {"yes": "Yes", "no": "No", "na": "Not applicable"} CHLORINATOR_TYPES = { 'cc' : 'Constant head chlorinator', 'nc' : 'Simple tank (non-constant head)', 'dp' : 'Chlorine dosing pump', 'gc' : 'Gas chlorination system', 'o' : 'Other', } id = models.UUIDField( primary_key=True, default=uuid.uuid4, help_text="Unique ID for the chlorinator instance", ) component_type = models.ForeignKey( ComponentType, on_delete=models.RESTRICT, limit_choices_to=Q(name__istartswith='treatment'), default='' ) chlorinator_type = models.CharField("Chlorinator type", max_length=2, choices=CHLORINATOR_TYPES) material = … -
Django post comments not working correctly
I'm trying to create a system for my Django project that allows users to post comments on specific posts. However, this isn't working. I tried to enter code into forms.py, views.py, urls.py and index.html in order to handle post entries. However, this has instead resulted in the submit button on index.html being without input boxes, and when it's clicked the page reloads with no update to the database. forms.py: class PostCommentForm(forms.ModelForm): class Meta: model = PostComment fields = ['post_comment'] views.py: from .forms import PostCommentForm from .models import * def post_comment(request, post_id): post = get_object_or_404(Post_Data, pk=post_id) if request.method == 'POST': form = PostCommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.user = request.user comment.post = post comment.save() return redirect('/', pk=post_id) else: form=PostCommentForm() return render(request, 'index.html', {'form': form}) urls.py: from .views import create_post urlpatterns = [ path('post/<int:post_id>/comment/', views.post_comment, name='post_comment'), ] index.html: <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit Comment</button> </form> models.py: class PostComment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post_Data, on_delete=models.CASCADE) post_comment = models.CharField(max_length=500) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return f"Comment by {self.user} on {self.post}" -
How can I make a nested Serializer available inside the create() of a ModelSerializer without making the nested Serializer read_only=False
I'm in a bit of a dilemma. The task is to take in a json that has some Info about a Bunny Litter and the Birthed Bunnies. I got a ThrowInfoSerializer with the Throw Model (Throw = Litter, non-english speaking country). Inside the create of the ThrowInfoSerializer I want to save a new Litter and the corresponding new Bunnies so I call new_bunnies = validated_data.pop('new_bunnies') and want to extract the new Bunny data from the validated_data. The problem is: since the new Bunny data is stored inside another ModelSerializer that is linked to the Bunny Model, and is BunnySerializer(many=True, read_only=True) read_only it isn't available in the validated_data inside the create(). But if I want to make new_bunnies read_only=False to make the info part of the validated_data inside create() i get this error: AttributeError: Got AttributeError when attempting to get a value for field `new_bunnies` on serializer `ThrowInfoSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Throw` instance. Original exception text was: 'Throw' object has no attribute 'new_bunnies'. Which makes sense since the the ThrowInfoSerializer is tied to the Throw Model. I can't really make another serializer and put ThrowInfoSerializer and the BunnySerializers … -
How to change parent class from models.Model to PolymorphicModel
I have two django models, Tomato and Potato. Both are being referenced multiple times across my project. I recently created a foreign key field in a third model, ShoppingBag, which should be allowed to contain one instance from either Tomato or Potato. My first approach was to create an empty (since Tomato and Potato have no fields in common) superclass Buyable, which inherits PolymorphicModel. I then set the referenced model in ShoppingBag.myforeignkey to accept instances of Buyable and I thought that would be it. I am now facing lots of errors, mostly because Potato.id and Tomato.id are being replaced by .buyable_ptr and the already existing foreign key and m2m fields to Potato and Tomato don't really like that. I wanted to ask if there's an official way to face this switch between parents or an alternative, easier way to tackle this issue. I created a function that generates a new instance of the super class and returns its id. I then set that function as the default value in the migration file. The solution didn't work, as the generated id was always 1. import Buyable def generate_id(): new_instance = Buyable() new_instance.save() return new_instance -
How to Customize Validation Error Response in Django REST Framework?
I am developing a RESTful API using Django REST Framework (DRF) and I need to implement a common error handling mechanism for various validation errors that occur throughout the application, including but not limited to JWT authentication failures. when validation errors occur, DRF returns default error responses that may not be user-friendly or consistent across different endpoints. For example, a JWT token validation error produces a response that looks like this: { "detail": "Given token not valid for any token type", "code": "token_not_valid", "messages": [ { "token_class": "AccessToken", "token_type": "access", "message": "Token is invalid or expired" } ] } I would like to standardize the error responses throughout my application to improve the user experience. Specifically, I want to create a common function that can return a structured error response for all validation errors in the following format: { "status": false, "responseCode": 0, "message": "Validation ", "data": {} } I tried by creating custom_exception_handler def custom_exception_handler(exc, context): response = exception_handler(exc, context) if response is not None: custom_response_data = { 'status': False, 'responseCode': 0, 'message': 'Validation error', 'data': {} } if isinstance(response.data, dict): errors = {} for field, detail in response.data.items(): if isinstance(detail, list): errors[field] = detail[0] if detail else 'Invalid … -
Django Progress bar for the backend to later integrate with frontend
I want to implement a progress bar since the request takes some time to give out the response when the api request is called i want the progress bar to start from 0 to 100 when the response loads views.py: class AllNodeReportView(View): def get(self, request, *args, **kwargs): start_date = request.GET.get('start') end_date = request.GET.get('end') format_type = request.GET.get('format', 'json') try: start_datetime = datetime.strptime(start_date, '%Y-%m-%d') end_datetime = datetime.strptime(end_date, '%Y-%m-%d') + timedelta(days=1) except ValueError: return JsonResponse({"error": "Invalid date format. Use 'YYYY-MM-DD'."}, status=400) nodes = Node.objects.only('mac', 'location', 'unicast') response_data = [] node_unicasts = nodes.values_list('unicast', flat=True) loc_tag_relations = LocTagRelation.objects.filter( unicastAddr__in=node_unicasts, uuid__gte=start_datetime.timestamp(), uuid__lt=end_datetime.timestamp() ).values('unicastAddr', 'tagMac').annotate( intime=Min('uuid'), outtime=Max('uuid') ).order_by('tagMac', 'intime') loc_tag_relation_map = {} for relation in loc_tag_relations: if relation['unicastAddr'] not in loc_tag_relation_map: loc_tag_relation_map[relation['unicastAddr']] = [] loc_tag_relation_map[relation['unicastAddr']].append(relation) tag_macs = [relation['tagMac'] for relation in loc_tag_relations] tag_data = TagHistory.objects.filter( mac__in=tag_macs, lastUpdated__gte=start_datetime.timestamp(), lastUpdated__lt=end_datetime.timestamp() ).order_by('mac', 'lastUpdated') tag_data_map = {} for entry in tag_data: if entry.mac not in tag_data_map: tag_data_map[entry.mac] = [] tag_data_map[entry.mac].append(entry) for node in nodes: if node.unicast in loc_tag_relation_map: for relation in loc_tag_relation_map[node.unicast]: tag_mac = relation['tagMac'] if tag_mac in tag_data_map: tag_entries = tag_data_map[tag_mac] current_location = None entry_time = None entry_date = None # Capture the actual date of entry last_exit_time = None ongoing_entry = None for tag_entry in tag_entries: timestamp = datetime.fromtimestamp(float(tag_entry.lastUpdated)) … -
Apache Superset embed Dashboard with Guest Token in DJango
I have the following setup. I'm running a Django Application with Postgres and Apache Superset on the same network (through docker-compose). The setup works fine; I can access my data (Postgres) from both the Django application and Superset. I have created a dashboard in Superset with some data and want to embed it on a DJnago page. I have already enabled dashboard sharing and I can use an iFrame to do so. However, this works because I have an active tab in the same browser with Superset, which I'm logged in to. If I go to another browser, the embedded Superset dashboard will show the login page. This is logical. However, how can manage a guest login from my Django application to the Superset so my users won't receive Superset's login page? I've tried the following code, in which I'm using Superset Guest Token API, I managed to receive a token successfully but every time I'm going to access the following URL, I'm redirected to Superset's login page with a red message "Access Denied". http://localhost:8088/superset/dashboard/1/?access_token=TOKEN/?standalone=4 <- 1 is the dashboard ID import requests import json url = "http://127.0.0.1:8088/api/v1/security/login" headers = { 'Content-Type': 'application/json' } payload = json.dumps({ "username": "guest_username", "password": … -
Django: Custom BaseInlineFormSet. Extra forms
I'm trying to implement an inline for the Product model admin, so that in addition to the forms for existing ProductAttribute relationships, forms for all attributes of the category of the product currently being edited are also added by default. The problem is that while the forms are there, saving doesn't result in creating the ProductAttribute relationship in the database, and the cleaned_data of these forms is empty. My code: admin.py ... class ProductAttributeInline(admin.TabularInline): model = ProductAttribute formset = ProductAttributeInlineFormset extra = 0 fields = ('attribute', 'value') readonly_fields = ('attribute',) can_delete = False def has_add_permission(self, request, obj=None): return False @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ( 'name', 'category', 'price', 'sku', 'created_at', 'updated_at' ) search_fields = ('name', 'sku') list_filter = ('category',) inlines = (ProductAttributeInline,) ... forms.py from django import forms from .models import ProductAttribute class ProductAttributeInlineFormset(forms.models.BaseInlineFormSet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.instance and self.instance.pk: category = self.instance.category if category: attributes = category.attributes.all() existing_attributes = set( self.queryset.values_list('attribute', flat=True) ) for attribute in attributes: if attribute.id not in existing_attributes: form_index = ( len(self.forms) + len(existing_attributes) - 1 ) form = self._construct_form( instance=ProductAttribute( product=self.instance, attribute=attribute, ), i=form_index ) self.forms.append(form) self.total_forms = len(self.forms) I noticed that 'attributes-TOTAL_FORMS' in form.data is equal to 1, but … -
Getting "Page not found (404) No Product matches the given query." error
I've started getting this error after deleting all my products from my database (I did this because it was dummy data just for testing). When I runserver and go to localhost I see this error The error states that this issue was raised in "home.views.index" despite the fact that the products are not called on the home page. I feel like my app is looking for the products and crashing when it cant find them. here is the code for my app urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', include('home.urls')), path('admin/', admin.site.urls), path('products/', include('products.urls')), path('checkout/', include('checkout.urls')), path('bag/', include('bag.urls')), path('contact/', include('contact.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Here is my product/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.all_products, name='products'), path('<int:product_id>/', views.product_detail, name='product_detail'), ] Here is the code for products/views.py from django.shortcuts import render from .models import Product def all_products(request): products = Product.objects.all() context = { 'products': products, } return render(request, "products/products.html", context ) def product_detail(request, product_id): product = get_object_or_404(Product, pk=product_id) context = { 'product': product, } return render(request, 'products/product_detail.html', context) Any help you can offer is greatly appreciated and sorry if I'm … -
raise ValueError( ValueError: Cannot assign "'TJFIDEL2401'": "Order.discount_code" must be a "DiscountCode" instance
I'm trying to implement a checkout page using Django framework. I have DiscountCode model linked to the Order model as "discount_code = models.ForeignKey(DiscountCode, on_delete=models.SET_NULL, null=True, blank=True)". When I proceed to click on the place order button on the checkout page, an error message occurs that is, "raise ValueError(ValueError: Cannot assign "''": "Order.discount_code" must be a "DiscountCode" instance." - I have spent already a couple of hours trying to resolve this issue. The problem occurs when the form.is_valid() is triggered Models: class DiscountCode(models.Model): code = models.CharField(max_length=50, unique=True) # Unique discount code discount_amount = models.DecimalField(max_digits=5, decimal_places=2) # e.g., 10.00 for a fixed amount discount discount_percent = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) # e.g., 10.00% for percentage discount valid_from = models.DateTimeField() valid_until = models.DateTimeField() max_uses = models.PositiveIntegerField(default=1) # Number of times the discount can be used users = models.ManyToManyField(Account, blank=True) # Assign to specific users or leave empty for all users is_active = models.BooleanField(default=True) # Active status def __str__(self): return self.code def is_valid(self): now = timezone.now() return self.is_active and self.valid_from <= now <= self.valid_until and self.max_uses > 0 class Order(models.Model): STATUS_CHOICES = ( ('New', 'New'), ('Processing', 'Processing'), ('Shipped', 'Shipped'), ('Delivered', 'Delivered'), ('Cancelled', 'Cancelled'), ) user = models.ForeignKey(Account, on_delete=models.SET_NULL, null=True) payment = models.ForeignKey(Payment, on_delete=models.SET_NULL, blank=True, … -
Djongo y Django REST Framework
Actualmente trabajo en el desarrollo de una red social y estoy usando Django para crear el back de la aplicación, pero la estoy conectando con Mongo usando el paquete de Djongo: https://www.djongomapper.com/using-django-with-mongodb-array-reference-field/ para el tema de los likes quiero referenciar con otra colección pero tengo problemas al usar REST framework para crear las API's de este modelo El post ya lo puedo crear sin problema pero a la hora de enviar un like o un comentario no se incrustan o no se referencian he usado ArrayField y actualmente estoy usando ArrayReferenceField -
assert not sociallogin.is_existing error when logging in using google with allauth
So I have been trying to login using google to my website but when I try to login it gets an assert error. I tried to add a presocial adapter to override it but I still get it. My settings are good I think. Even if I take off the adapter I try to login and get the same error. This is the error. AssertionError at /accounts/google/login/callback/ No exception message supplied Request Method: GET Request URL: http://127.0.0.1:8000/accounts/google/login/callback/?state=F6gfXDcxDejwMv6J&code=4%2F0AQlEd8z3snMAR_7qPFDabY-q_zHedLdND40cQdWn7AH_Akjs3q7R8hx0cjOlB_K0LrQBJQ&scope=email+profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&authuser=0&hd=afreebird.org&prompt=none Django Version: 4.2.13 Exception Type: AssertionError Exception Location: C:\Users\TinaPC\Documents\GitHub\afreebird_website_2.0\env\lib\site-packages\allauth\socialaccount\internal\flows\login.py, line 36, in pre_social_login Raised during: allauth.socialaccount.providers.oauth2.views.view Python Executable: C:\Users\TinaPC\Documents\GitHub\afreebird_website_2.0\env\Scripts\python.exe Python Version: 3.8.10 Python Path: ['C:\\Users\\TinaPC\\Documents\\GitHub\\afreebird_website_2.0', 'C:\\Users\\TinaPC\\.pyenv\\pyenv-win\\versions\\3.8.10\\python38.zip', 'C:\\Users\\TinaPC\\.pyenv\\pyenv-win\\versions\\3.8.10\\DLLs', 'C:\\Users\\TinaPC\\.pyenv\\pyenv-win\\versions\\3.8.10\\lib', 'C:\\Users\\TinaPC\\.pyenv\\pyenv-win\\versions\\3.8.10', 'C:\\Users\\TinaPC\\Documents\\GitHub\\afreebird_website_2.0\\env', 'C:\\Users\\TinaPC\\Documents\\GitHub\\afreebird_website_2.0\\env\\lib\\site-packages'] Server time: Mon, 30 Sep 2024 09:11:33 -0500 Traceback Switch to copy-and-paste view C:\Users\TinaPC\Documents\GitHub\afreebird_website_2.0\env\lib\site-packages\django\core\handlers\exception.py, line 55, in inner response = get_response(request) … Local vars C:\Users\TinaPC\Documents\GitHub\afreebird_website_2.0\env\lib\site-packages\django\core\handlers\base.py, line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … Local vars C:\Users\TinaPC\Documents\GitHub\afreebird_website_2.0\env\lib\site-packages\allauth\socialaccount\providers\oauth2\views.py, line 103, in view return self.dispatch(request, *args, **kwargs) … Local vars C:\Users\TinaPC\Documents\GitHub\afreebird_website_2.0\env\lib\site-packages\allauth\socialaccount\providers\oauth2\views.py, line 152, in dispatch return complete_social_login(request, login) … Local vars C:\Users\TinaPC\Documents\GitHub\afreebird_website_2.0\env\lib\site-packages\allauth\socialaccount\helpers.py, line 67, in complete_social_login return flows.login.complete_login(request, sociallogin) … Local vars C:\Users\TinaPC\Documents\GitHub\afreebird_website_2.0\env\lib\site-packages\allauth\socialaccount\internal\flows\login.py, line 46, in complete_login pre_social_login(request, sociallogin) … Local vars C:\Users\TinaPC\Documents\GitHub\afreebird_website_2.0\env\lib\site-packages\allauth\socialaccount\internal\flows\login.py, line 36, in pre_social_login assert not sociallogin.is_existing … Local vars … -
DRF Custom Generic View
I tried create a complete generic view with mixins to automate my app, and write less code. When i try make a 'POST' request i receive a 405 error = code(method_not_allowed) I cant find the error I also want to know if is this a good aproac to improve my code. `class BaseGenericView(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView): serializer_class = YourModelSerializer permission_classes = [IsAuthenticated] # Adapte conforme necessário def get_queryset(self): return YourModel.objects.all() def list(self, request, *args, **kwargs): queryset = self.get_queryset() serializer = self.get_serializer(queryset, many=True) return Response({'message': 'Dados encontrados', 'data': serializer.data}, status=status.HTTP_200_OK) def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(raise_exception=True): self.perform_create(serializer) return Response({'message': 'Criado com sucesso!', 'data': serializer.data}, status=status.HTTP_201_CREATED) return Response({'message': 'Erro na validação', 'data': serializer.errors}, status=status.HTTP_400_BAD_REQUEST) def retrieve(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance) return Response({'message': 'Dados encontrados', 'data': serializer.data}, status=status.HTTP_200_OK) def update(self, request, *args, **kwargs): partial = kwargs.pop('partial', False) instance = self.get_object() serializer = self.get_serializer(instance, data=request.data, partial=partial) if serializer.is_valid(raise_exception=True): self.perform_update(serializer) return Response({'message': 'Atualizado com sucesso!', 'data': serializer.data}, status=status.HTTP_200_OK) return Response({'message': 'Erro na validação', 'data': serializer.errors}, status=status.HTTP_400_BAD_REQUEST) def destroy(self, request, *args, **kwargs): instance = self.get_object() self.perform_destroy(instance) return Response({'message': 'Removido com sucesso!'}, status=status.HTTP_200_OK)` -
How Can I Setup Celery in my Flask Project
So I've been working on a project for a couple months now and I've been trying to implement Celery into my flask project and it has not gone well. I thought maybe it's my computer or windows or something like, and all the responses I've seen are from a couple years ago and I don't think that they would still work because those were the ones I tried using. So thank you for any responses in advance. I tried using the celery config from the documentation and some chat gpt tutorials but they haven't been of help. And I'm running redis on the localhost -
Modifing ticket creating in django helpdesk
im tring to figure out how can i modify the field that are in the creating ticket area im modifed my admin.py code, i succsed to ad custom fields, but not in the desired way im just wondering if it possible to customize it in my own way without creating new model -
How to Attach Files from a web app to Local Outlook Client?
I'm working on a task where I need to implement a button in the frontend that opens the local Outlook client to compose an email. The user selects files (.dat or .csv) in the frontend, and upon clicking the button, Outlook should open with a default message and the selected files already attached, allowing the user to review the email before sending it. I understand that it might be easier to send the emails directly from the application, but that’s not the desired approach for this project. Can you please let me know if this is even possible, and if so, how I could implement it? I’ve tried using the Outlook API, but it didn’t meet my needs because it doesn’t open Outlook before sending the email, which is a key requirement for this project. Additionally, I cannot use links; the files must be attached directly as they are. -
creating a category system with MVT in django
I am working on a project and I created a system that has cars model and some user models . I want to create another model for user's skills and give the user model a relation to skill model . But I don't know how to do this optimize? for example , some users may can't fix the gearbox of one car But others Can , And some users may can fix some engine problems with some cars that others can't! So with this I need to have ralations to 'Car' model and also I have to save the skills with cars in the database . But there is more than 2000 cars in database! What do you think I can do? -
Logs are not transferred correctly
I have a logger set up to save logs to a file, but I'm encountering an issue with log rotation. Not all logs are being transferred during the rotation process, and the majority of logs are missing. What could be the problem? Why are many of my logs not being transferred during log rotation, and how can I resolve this? Here’s my logger configuration: LOGGING = { "version": 1, "disable_existing_loggers": False, "filters": {"correlation_id": {"()": "django_guid.log_filters.CorrelationId"}}, "formatters": { "standard": { "format": "[%(levelname)s] %(asctime)s [%(correlation_id)s] %(name)s: %(message)s", }, }, "handlers": { "file": { "level": "ERROR", "class": "logging.handlers.TimedRotatingFileHandler", "formatter": "standard", "filters": ["correlation_id"], "filename": "logging_view/logs/server-logs/server.log", "when": "midnight", "interval": 1, "backupCount": 30, "encoding": "utf-8", "delay": True, "utc": True, "atTime": None, "errors": None, }, "custom_mail_admins_handler": { "level": "ERROR", "class": "logging_view.logger.CustomAdminEmailHandler", "formatter": "standard", }, "js_file": { "level": "ERROR", "class": "logging.handlers.TimedRotatingFileHandler", "formatter": "standard", "filters": ["correlation_id"], "filename": "logging_view/logs/client-logs/client.log", "when": "midnight", "interval": 1, "backupCount": 30, "encoding": "utf-8", "delay": True, "utc": True, "atTime": None, "errors": None, }, }, "loggers": { "": { "handlers": ["file", "custom_mail_admins_handler"], "level": "ERROR", "propagate": False, }, "js_logger": { "handlers": ["js_file"], "level": "ERROR", "propagate": False, }, }, } settings.py # log_viewer LOGGING = LOGGING LOG_VIEWER_FILES_DIR = "logging_view/logs/server-logs" LOG_VIEWER_FILES_CLIENT_DIR = "logging_view/logs/client-logs" LOG_VIEWER_PAGE_LENGTH = 25 LOG_VIEWER_MAX_READ_LINES = 1000 LOG_VIEWER_FILE_LIST_MAX_ITEMS_PER_PAGE = … -
Unable to create superuser after creating CustomUser
After creating Custom user when i tried to create a superuser it gave error TypeError: UserManager.create_superuser() missing 1 required positional argument: 'username' Then after creating CustomUserManager its showing Expression of type "CustomUserManager" is incompatible with declared type "UserManager[Self@AbstractUser]" "CustomUserManager" is incompatible with "UserManager[Self@AbstractUser]" Expression of type "CustomUserManager" is incompatible with declared type "UserManager[Self@AbstractUser]" "CustomUserManager" is incompatible with "UserManager[Self@AbstractUser]" class CustomUserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('The Email field 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_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(email, password, **extra_fields) class CustomUser(AbstractUser, PermissionsMixin): username = None email = models.EmailField(unique=True) daily_reminders = models.IntegerField(default=0) start_at = models.TimeField(null=True, blank=True) end_at = models.TimeField(null=True, blank=True) notification_status = models.IntegerField(null=True, blank=True) device_type = models.CharField(choices=DIV_CHOICES, max_length=10, null=True, blank=True) device_token = models.CharField(max_length=255, null=True, blank=True) categories = models.JSONField(default=list, null=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email I BaseUserManager imported from django.contrib.auth.base_user import BaseUserManager but still showing error -
Django RestFramework make lookup_field accept special characters (".")
I am working on a DRF viewset which has a custom query (using annotate to group data), for this I want to implement list, retrive and delete functions based on a field called "batch" which contains a string with special characters like "-" and ".". I am able to make the viewset to list and retrive data but the data retrival fails when special characters (".") are present in the batch string. How can I setup viewset router to allow "." in the batch name? class BatchViewSet(viewsets.ModelViewSet): queryset = Product.objects.values('batch', 'customer', 'order_number').annotate( total_quantity=Sum('total_quantity'), ready_quantity=Sum('ready_quantity') ).filter(deleted_at__isnull=True).all() serializer_class = BatchSerializer lookup_field = 'batch' filter_backends = [filters.SearchFilter, filters.OrderingFilter] search_fields = ['batch', 'customer', 'order_number'] ordering_fields = ['batch', 'customer', 'order_number', 'total_quantity', 'ready_quantity'] ordering = ['batch'] def create(self, request, *args, **kwargs): raise MethodNotAllowed('POST') router.register(r'batches', BatchViewSet, basename="batches") These are the routes generated to get the batch details products/ ^batches/(?P<batch>[^/.]+)/$ [name='batches-detail'] products/ ^batches/(?P<batch>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='batches-detail'] which is not working on my batch TEATECH.01427964.11.08 but working on TEATECH. I tried making a custom router to get the batch number but it is also not working and I can't create a regex which can process the batch. Similarly I can't setup lookup_field_regex to catch the batch string. I can navigate my … -
Django Server URL not running [closed]
I am trying to run the django backend server using the intergrated terminal but the url is not running it is saying Not found tried to open it in the browser but it wasnt running still.I was expecting it to say welcome to the student task tracker -
django factory boy, image fields not created?
I tried to follow the standard recipe for image fields for django factory boy: class ConfigurationSingletonFactory(DjangoModelFactory): class Meta: model = Configuration django_get_or_create = ("id",) id = 1 custom_theme = ImageField(color="blue", width=200, height=200) class GeneralConfiguration(SingletonModel): custom_theme = PrivateMediaImageField("Custom background", upload_to="themes", blank=True) However whenever I try to test it: def test_config(self): conf = GeneralConfigurationSingletonFactory( custom_theme__name="image.png" ) print(conf.custom_theme.width) self.assertEqual(conf.custom_theme.width, 200) The following error pops up: ValueError: The 'custom_theme' attribute has no file associated with it. What am I misunderstanding, I thought I did exactly what https://factoryboy.readthedocs.io/en/stable/orms.html#factory.django.ImageField says? -
Removing success message after deleting was denied
Given the fact, that this is already some years old and no perfect answer was provided: How do I overwrite the delete_model/queryset functions in the admin, so the success message is not shown if the deletion was denied? class BookAdmin(admin.ModelAdmin): def delete_queryset(self, request, queryset): if not can_delete(): messages.error(request, "cannot delete ...") return super().delete_queryset(request, queryset) The logic works, but I get a success AND an error message which is confusing for the user. I know I can go the long way and implement a whole custom logic, but then I would face the issue of not seeing the "are you sure ..." page? I have the same problem I show here for delete_queryset() also with the delete_model(). -
Django Channels: WebSocket Consumer event handling method doesnt get trigerred
I'm working on a Django project using Django Channels with Redis as the channel layer. My setup allows WebSocket connections, and I am able to send and receive data from Redis without issues. However, when I try to send data to specific WebSocket channels using self.channel_layer.send, the send_online_users method in my AsyncWebsocketConsumer is not triggered. I’ve verified that my Redis server is working and communicating with the Django server. The channels and users are being stored correctly in Redis. The self.channel_layer.send() function runs without throwing errors, but the send_online_users method is never triggered (the print statements inside send_online_users do not show in the logs). Here is my Consumers.py code: from channels.generic.websocket import AsyncWebsocketConsumer import redis from django.conf import settings import redis.client from asgiref.sync import sync_to_async import json from channels.layers import get_channel_layer redis_client = redis.StrictRedis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=0) class UserActivityConsumer(AsyncWebsocketConsumer): async def connect(self): self.user = self.scope['user'] if self.user.is_anonymous or not self.user.is_authenticated: await self.close() else: self.channel_name = f'user_activity_{self.user.username}' await sync_to_async(redis_client.sadd)('online_users', self.user.id) await sync_to_async(redis_client.sadd)("online_channels",self.channel_name) await self.accept() await self.send_to_all() async def disconnect(self,close_code): user_id = self.scope['user'].id await sync_to_async(redis_client.srem)("online_users", user_id) await sync_to_async(redis_client.srem)("online_channels", self.channel_name) await self.send_to_all() async def send_to_all(self): try: online_users = await sync_to_async(redis_client.smembers)("online_users") online_users = [int(user_id) for user_id in online_users] online_channels = await sync_to_async(redis_client.smembers)("online_channels") channel_layer = get_channel_layer() … -
Why in the Django + Tailwindcss project, styles are used in one file and not in another?
Here is the project's file system: enter image description here All classes work in this file: file: navbar.html <nav class="bg-white shadow-lg"> <div class="max-w-6xl max-auto px-4"> <div class="flex justifly-between"> <div class="space-x-7"> <div class="flex"> <a href="#" class="flex items-center px-2 py-4"> <img class="h-8 w-8" src="{% static 'myapp/images/logo.png' %}" alt="logo"> <span class="font-semibold text-xl"> Shop </span> </a> </div> <div class="items-center flex space-x-1"> <a href="#" class="py-4 px-2 font-semibold border-b-4 border-black ">Sell</a> <a href="#" class="py-4 px-2 font-semibold ">Sold</a> <a href="#" class="py-4 px-2 font-semibold ">Home</a> </div> </div> </div> </div> </nav> In this file tailwind classes for some reason do not work. Why is this happening??? file: contacts.html <div class=" p-10 grid grid-cols-1 sm:grid-cols-1 md:grid-cols-3 xl:grid-cols-3 lg:grid-cols-3 gap-3 "> {% for item in items %} <a href="{% url 'site:detail' item.id %}"> <div class=" px-10 py-10 rounded overflow-hidden shadow-lg"> <img src="{{item.images.url}} " alt="img"> {{item.name}} {{item.price}} <br> </div> </a> {% endfor %} </div> Why does tailwind work in one part of the code and not in another? Even though both files are in the same folder. You need to make tailwind work in the contacts.html file.