Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I have upload a django project on server in public html folder
When creating a Python application on a server, I put the folder name or project name in the application root. However, the issue is that the folder is creating outside the public HTML folder. I want the folder to be created in the public HTML folder only. How can I ensure that the folder is created in the desired location? -
401 unauthorized on post request
serializer/login.py class LoginSerializer(TokenObtainPairSerializer): def validate(self, attrs): data = super().validate(attrs) refresh = self.get_token(self.user) data['user'] = UserSerializer(self.user).data data['refresh'] = str(refresh) data['access'] = str(refresh.access_token) if api_settings.UPDATE_LAST_LOGIN: update_last_login(None, self.user) return data viewsets/login.py class LoginViewSet(ViewSet): permission_classes = (AllowAny,) serializer_class = LoginSerializer http_method_names = ['post'] def create(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) try: serializer.is_valid(raise_exception=True) except TokenError as e: raise InvalidToken(e.args[0]) return Response(serializer.validated_data, status=status.HTTP_200_OK) I cant login with right credentials using post request, it says 401 unauthorized. but when I try to register or refresh token using post request (using the same crediatials I tried to login with), it works fine. serializer/register.py class RegisterSerializer(UserSerializer): #making the pass min 8 charecter and max 128 #and can't be read password = serializers.CharField(max_length=128, min_length=8, write_only=True, required=True) class Meta: model = User fields = ['id', 'email', 'username', 'first_name', 'last_name', 'password'] # 'bio', 'avater', #used the create_user method that we wrote def create(self, validated_data): return User.objects.create_user(**validated_data) viewsets/register.py class RegisterViewSet(ViewSet): serializer_class = RegisterSerializer permission_classes = (AllowAny,) http_method_names = ['post'] def create(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() refresh = RefreshToken.for_user(user) res = { "refresh" :str(refresh), "access": str(refresh.access_token), } return Response({ "user": serializer.data, "refresh":res['refresh'], "token":res['access'] }, status=status.HTTP_201_CREATED) viewsets/refresh.py class RefreshViewSet(viewsets.ViewSet, TokenRefreshView): permission_classes = (AllowAny,) http_method_names = ['post'] def create(self, … -
React gets non responsive when data from Django is used to display a Nivo line chart
I have been trying to display a nivo line charts using data from my backend (Django). However, when the data is inserted into the nivo line chart, the react window gets unresponsive. The backend sends the timestamps and the values like this -- Example -- timestamp = "2023-05-12 16:10:53.000000000" Values -- "39.520004" class AddView(APIView): from django.views.decorators.csrf import csrf_exempt from rest_framework import status import json @staticmethod @csrf_exempt def post(request): from awsfetch.rpm import rpm timestamps, values = rpm() return Response({"timestamps": timestamps, "values": values}) This is the nivo charts component -- import { ResponsiveLine } from "@nivo/line"; const MyResponsiveLine = ({ data }) => ( <ResponsiveLine data={data} margin={{ top: 50, right: 160, bottom: 50, left: 60 }} xScale={{ format: "%Y-%m-%dT%H:%M:%S.%L%Z", type: "time" }} xFormat="time:%Y-%m-%dT%H:%M:%S.%L%Z" yScale={{ type: "linear", stacked: true, min: 0.0, max: 1.0 }} curve="monotoneX" axisTop={null} axisRight={{ tickValues: [0.0, 0.2, 0.4, 0.6, 0.8, 1.0], tickSize: 5, tickPadding: 5, tickRotation: 0, format: "0.2", legend: "", legendOffset: 0 }} axisBottom={{ tickValues: "every 1 second", tickSize: 5, tickPadding: 5, tickRotation: 0, format: "%S.%L", legend: "Time", legendOffset: 36, legendPosition: "middle" }} axisLeft={{ tickValues: [0.0, 0.2, 0.4, 0.6, 0.8, 1.0], tickSize: 5, tickPadding: 5, tickRotation: 0, format: ".2", legend: "CPU", legendOffset: -40, legendPosition: "middle" }} enableGridX={false} colors={{ scheme: … -
Django REST framework prefetch not working on model with multiple foreign keys to the same target
I'm writing an endpoint to fetch data from the "Term" model in Django REST framework and I'm trying to reduce queries by prefetching data. Specifically there is a model "TermRelation", that saves vector relation scores between individual terms that I would like to prefetch data from. Simplified, the models look as follows: models.py class Term(models.Model): term = models.CharField(max_length=255, verbose_name=_('Term'), null=True, db_index=True) class TermRelation(models.Model): src_term = models.ForeignKey(Term, on_delete=models.CASCADE, verbose_name=_('Source term'), related_name='src_term_relation') trg_term = models.ForeignKey(Term, on_delete=models.CASCADE, verbose_name=_('Target term'), related_name='trg_term_relation') vector_sim = models.FloatField(blank=True, null=True, default=0.0, verbose_name=_('Vector similarity'), help_text=_('Cosine vector similarity.')) And here's the simplified view: views.py class TermsList(generics.ListCreateAPIView): def get_queryset(self): queryset = Term.objects.prefetch_related( 'src_term_relation', 'trg_term_relation', 'note_set', 'usage_set' ).all() return queryset There are other models related to term such as "Note" and "Usage" for which prefetch is working, only for relations it still makes a bunch of queries. I've included a screenshot of the Django SQL debug results, or rather the first few lines as this goes on for a while with the same queries. You can see that Django does run the prefetch operation, but then still makes the same queries as if it didn't happen. What am I doing wrong? Could this be related to "TermRelation" having two ForeignKey fields pointing to … -
Implementation of the post filter page in django
I am trying to filter blog posts using this model: class Post(models.Model): is_podcast = models.BooleanField(default=False) category = models.ManyToManyField(Category) title = models.CharField(max_length=500) slug = models.SlugField(allow_unicode=True , unique=True , null=True , blank=True) body = RichTextUploadingField() likes_count = models.IntegerField(default=0 , help_text="amount of likes") vip_members_only = models.BooleanField(default=False) def __str__(self): return self.title And I am using this view to filter the posts: def Index_view(request , slug=None): posts = Post.objects.filter() kind = request.GET.get('type') order = request.GET.get('order') author = request.GET.get('author') search = request.GET.get('search') if slug: cat = get_object_or_404(Category , slug=slug) posts.filter(category = cat) if search != '' and search is not None: posts.filter(Q(title__icontains = search)) if kind != '' and kind is not None: if kind == 'podcast': posts.filter(is_podcast=True) if kind == 'all': pass if kind == 'post': posts.filter(is_podcast=False) con = {'posts' : posts} return render(request , 'Weblog/posts.html' , con) Here is the urls.py too: path('posts/', Index_view), re_path(r'^posts/(?P<slug>[\w-]+)/$', Index_view), When I use this URL (http://127.0.0.1:8000/blog/posts/some-slug/?search=test), I receive all the posts and the filtering does not work. What is the problem? -
how do I call a djago admin delete fuction
I am trying to use the Django admin delete function to ensure that the corresponding quantity is deleted from the associated page when the delete function is clicked. For example, I have a class called RestockModel. When I add a new Restock item, the restock quantity can be automatically added in the StockListModel. However, when I need to delete the Restock item, the quantity in StockListModel is not deleted immediately. How can I call the django admin delete function to this statement? Here is the code that how I made the quantity can be added when I create a new restock item: class restockInfo(admin.ModelAdmin): list_display = ["product", "delivery_order_no","restock_quantity", "supplier_name", "created_date"] readonly_fields = ["created_date"] search_fields = ['created_date'] def save_model(self, request, obj, form, change): product = obj.product restock_quantity = obj.restock_quantity if restock_quantity and product.quantity_in_store: if restock_quantity >= 0: obj.product.quantity_in_store = product.quantity_in_store + restock_quantity # don't forget to save stock after change quantity obj.product.save() messages.success(request, 'Successfully added!') super().save_model(request, obj, form, change) else: messages.error(request, 'Invalid Quantity, Please Try Again!!!') return restockInfo This is my restock models: class restockList(models.Model): product = models.ForeignKey("stockList", on_delete=models.CASCADE, null=True) delivery_order_no = models.CharField(max_length=255, null=True) restock_quantity = models.IntegerField(null=True) supplier_name = models.CharField(max_length=255, null=True) created_date = models.DateTimeField(auto_now_add=True, blank=True, editable=False) class Meta: db_table = "restocklist" -
Getting object index in django object list
I have a list in context of one of my pages called comments and when I'm iterating on it i want to know the index of item; i want to know the index of comment in this for loop: <!-- comment list section --> <div class="card shadow my-3 p-5"> <h3>Comments:</h3> <!-- checking if any comment exist on this post --> {% if comments.count < 1 %} No comments. write the first one! {% else %} <!-- iterating on comments and showing them --> {% for comment in comments %} <div id="comment-div"> <span id="Comment-name">by: {{ comment.name }}</span> <span id="Comment-date">{{ comment.datetime_created|date:'M d Y' }}</span> <p id="Comment-body">{{ comment.body }}</p> </div> {% endfor %} {% endif %} </div> view: class PostDetailView(FormMixin, generic.DetailView): model = Post template_name = 'blog/post_detail.html' context_object_name = 'post' form_class = CreateComment def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) # get the default context data context['comments'] = Comment.objects.filter(accepted=True) # add extra field to the context return context model: class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') email = models.EmailField(max_length=35) name = models.CharField(max_length=50) body = models.TextField() datetime_created = models.DateTimeField(auto_now_add=True) accepted = models.BooleanField(default=False) -
White space stripped from Django Template tags in PrismJS code blocks
When I render Django template code in a prismjs block, it strips white space {{}} and {%%}. For example, pre-render, the code might be {% image self.search_image thumbnail-400x200 as img %} <img src="{{ img.url }}" alt="{{ img.title }}"> But the rendered code block will be {%image self.search_image thumbnail-400x200 as img%} <img src="{{img.url}}" alt="{{img.title}}"> It's not a case of css, the space is missing from the html. I can set the language to HTML, or even python etc, the same issue remains. Does anyone know of a way to prevent this? -
How Can I implement User Sent Message and Receive Message in Django
I am working on a Django project where I have three types of users: Landlord, Agent, and Prospect. I want the Prospect user to be able to contact the Property Owner by sending a message while on the Property Detail view, and the Property Owner to be able to reply back to the Prospect using the same view. I also want all these users to maintain an Inbox and Sent Message items. I'm struggling to figure out whether my logic is sound and how to implement the functionality using Django. Is there a library that will make user messaging within Django easier? In my code, I maintain different Models for these users with a OneToOneField and use signals for automatic profile creation upon registration. I also have a Profile Model connected through the same relationship, and Message Model. I tried passing the Property Owner ID as the Recipient ID and Property ID on url from the Property Detail view to the send_message function view, but I get the error "No 'User matches the given query'." Here are my views: def property_detail(request, property_id): user = request.user #Check if user is authenticated if not user.is_authenticated: logout(request) messages.warning(request, 'Session expired. Please log in … -
Annotating a value in Django using Extract and OuterRef (or F) leads to TypeError
I'm building an application where users can create posts. If the user don't post anything after some specific time of the day, the server will send a push notification to remember the user to post something. In order to create this query I planned to run a scheduled celery beat task to filter the posts created in the current day, list the user's id and use a simply exclude these IDs from the active users in order to get a queryset with the users that should be notified. The user has a timezone field, which is updated via a middleware that checks some headers frontend send, checks the user saved timezone and update it if necessary. This timezone is the result of running the tzname() method in the datetime that comes in this header. The issue is that the users are spread across multiple timezones, so I need to actually annotate the created_at field in Posts (which are saved taking in consideration the server timezone) with the User's timezone. In Django we have the Extract function that simply does exactly what I need. The issue here is that it would work perfectly if I could use a F expression or … -
What kind of security should I implement in my Django REST API if it doesn't require authentication?
It's my first time building an API and it only processes GET requests. What kind of security would be necessary for this project? Other than using the .gitignore file and making sure my database key is hidden do I need to further secure the database for production? My project uses Django, Django REST, and PostgreSQL. I haven't yet found a host I like enough to deploy to so any recommendations would be appreciated. -
django.db.utils.OperationalError: (2002, "Can't connect to local server through socket '/run/mysqld/mysqld.sock' (2)")
I am trying to dockerize my Django project which includes a MySQL database and nginx. When I run the command docker-compose up --build, I receive the following error: django.db.utils.OperationalError: (2002, "Can't connect to local server through socket '/run/mysqld/mysqld.sock' (2)"). This is my docker-compose.yml file: version: '3.7' services: app: build: ./app env_file: - .env container_name: app restart: always expose: - 8000 command: bash -c "python3 manage.py collectstatic --noinput && python3 manage.py migrate --noinput --fake-initial && \ gunicorn -b 0.0.0.0:8000 veblog.wsgi" environment: - MYSQL_DATABASE=${NAME} - MYSQL_USER=${USER_NAME} - MYSQL_PASSWORD=${PASSWORD} - MYSQL_HOST=sqldb mem_limit: 1g depends_on: - sqldb # - nginx volumes: - ./volumes/app:/app - type: bind source: ./volumes/media target: /app/media - type: bind source: ./volumes/static target: /app/static nginx: build: ./nginx container_name: nginx restart: always ports: - 8000:80 sqldb: image: mysql:latest container_name: sqldb restart: always depends_on: - nginx expose: - 3306 environment: - MYSQL_DATABASE=${NAME} - MYSQL_USER=${USER_NAME} - MYSQL_PASSWORD=${PASSWORD} - MYSQL_ROOT_PASSWORD=${ROOT_PASSWORD} - MYSQL_INITDB_SKIP_TZINFO=true - MYSQL_INIT_COMMAND=SET GLOBAL host_cache_size=0; volumes: - type: bind source: ./volumes/dbdata target: /var/lib/mysql - /usr/share/zoneinfo:/usr/share/zoneinfo:ro This is my Dockerfile in the app directory: FROM python:3 ENV PYTHONDONTWRITEBYCODE 1 ENV PYTHONUNBUFFERED 1 RUN mkdir -p /app WORKDIR /app COPY . . RUN apt update RUN apt install gcc python3-dev musl-dev -y RUN pip install --upgrade … -
How to find overlapping with a given start_time and end_time (Weekday/Hour format)
I am attempting to determine overlapping availability for a specialist based on their stored availability, which is stored as a datetime due to timezone changes, but only the weekday and time portion is used. When searching for availabilities, I search them as isoweekday and time. However, I am facing issues when the start time is greater than the end time or the start day is greater than the end day. Here is my SpecialistAvailability model: class SpecialistAvailability(BaseModel): """ Model to store the availability of a specialist """ specialist = models.ForeignKey(Specialist, on_delete=models.CASCADE, null=False, blank=False) start_time = models.DateTimeField(null=False, blank=False) end_time = models.DateTimeField(null=False, blank=False) objects = SpecialistAvailabilityManager() I am using pytz and Django to filter for overlapping availability for a specialist as such: import pytz from django.db import models from django.db.models import Q, F class SpecialistAvailabilityManager(models.Manager): """ Manager for SpecialistAvailabilityDay model """ def get_overlapping_availability(self, specialist, start_time, end_time): """ Method to get overlapping availability of a specialist """ start_day = start_time.isoweekday() end_day = end_time.isoweekday() start_time = start_time.time() end_time = end_time.time() initial_availabilities = self.filter(specialist=specialist) if start_day > end_day: day_availabilities = initial_availabilities.filter( Q(start_time__iso_week_day__gt=F('end_time__iso_week_day')) | Q(start_time__iso_week_day__lte=end_day) | Q(end_time__iso_week_day__gte=start_day) ) else: day_availabilities = initial_availabilities.filter( Q(start_time__iso_week_day__gt=F('end_time__iso_week_day'), start_time__iso_week_day__lte=end_day) | Q(start_time__iso_week_day__gt=F('end_time__iso_week_day'), end_time__iso_week_day__gte=start_day) | Q(start_time__iso_week_day__lte=end_day, end_time__iso_week_day__gte=start_day) ) if start_time > end_time: availabilities … -
New to django, django server not loading home page
I started a Django project and went through the regular setup process: I used the "startproject" command to create a project named "social_clone_project", and I used "startapp" to create an app named "accounts". Then I created a "views.py" file and set up the "urls.py" file. Here's what it looks like: from django.contrib import admin from django.urls import path, include, re_path from . import views urlpatterns = [ re_path(r'^$', views.HomePage.as_view(), name='home'), path("admin/", admin.site.urls), ] Recently, I switched to Ubuntu Debian with the sublime-text editor. I'm new to the Ubuntu OS, and whenever I run the "runserver" command, the default "Congratulations!" page loads instead of my home page. I've created an "index.html" file, which is supposed to load as the home page, but it's not working. Can someone help me solve this issue? -
how to get values from a context (object ) dinamically in django templates
I'm a newbie in django and I'm trying to get values from an object dynamiclly in the template directly, but nothing seems to work: this is what I have in the django template: {% for key, value in edit.changes.items %} <p>{{ translator.get(key) }}</p> I also tried this: {% for key, value in edit.changes.items %} <p>{{ translator[key] }}</p> this is the view: def medical_record_edit_list(request, pk): translator = { "appointment_date" :"Fecha", "diagnosis_type" : " Tipo de Diagnóstico", "main_diagnosis" : "Diagnóstico Principal (CIE-10)", "related_diagnosis" : "Diagnóstico Relacionado (CIE-10)", "objective" : "Objetivo", "mental_exam" : "Exámen Mental", "development" : "Desarrollo", "employed_interventions" : "Intervenciones Utilizadas", "evaluation_instruments" : "Instrumentos de Evaluación", "agreements" : "Acuerdos", "therapeutic_work" : "Expectativas de la Consulta", "evaluation_instruments" : "Instrumentos de Evaluación", "remission" : "Remisiones y Contrarremisiones", "finality" : "Finalidad", "external_cause" : "Causas Externas", "conduct" : "Conducta", "exit_state" : "Estado de Salida", "exit_diagnosis" : "Diagnóstico de Egreso (CIE-10)", "exit_condition" : "Condición de Salida" } medical_record_entry = MedicalRecordEntry.objects.get(pk=pk) edit_list = MedicalRecordEdit.objects.filter(medical_record_entry=medical_record_entry).order_by("edit_date") return render(request, 'medical_record/medical_record_edit_list.html', {'edit_list':edit_list, 'medical_record_entry':medical_record_entry, 'translator': translator}) I'm just trying to get what something like: {{ context.appointment_date }} outputs but for each key of the for loop that I have above -
Define database models for webapp about event in django
I'm trying to build an web app about events in python django. Basically, users can see which events will happen or happened and also their dates, locations, etc. But the problems are in relations. So, I've created accounts, events, boardgames, frp, mtg apps in django. Here is the I've coded models. ## for accounts class User(auth.models.User, auth.models.PermissionsMixin): def __str__(self): return f"{self.username}" ## for events class Event(models.Model): name = models.CharField(max_length=256, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) description = models.CharField(max_length=256, unique=True) organizer = models.ForeignKey(User, on_delete=models.CASCADE, related_name='organized_events') date = models.DateTimeField() location = models.CharField(max_length=256, unique=True) attendees = models.ManyToManyField(User, through='EventMember') situation = models.BooleanField(default=True) def get_absolute_url(self): return reverse('events:single', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): self.slug = slugify(self.name) super().save(*args, **kwargs) def __str__(self): return self.name class EventMember(models.Model): event = models.ForeignKey(Event, related_name='event_memberships', on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='user_events', on_delete=models.CASCADE) def __str__(self): return self.user.username Bu I want to build the models roughly like this: diagram How can I build these models and how can I code views for them ? I also think you dream what kind of webapp is this. I'm open to every kind of suggestions. Thanks. -
Styling the can_delete form checkbox in model formset factory django
forms.py from .models import Bacteria, Citation from django.forms import ModelForm, modelformset_factory, from django import forms class CitationForm(ModelForm): citation = forms.CharField(label=False) citation.widget.attrs.update({'class' : 'form-control','placeholder': 'Source'}) class Meta: model = Citation fields = ('citation',) widgets = {'citation': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Add Reference'}) } CitationFormset = modelformset_factory(Citation, form=CitationForm, extra=0, can_delete=True) For each form instance in the model form set factory, the check box which sets a form in the formset works perfectly fine but has default styling. Is there any way to style the check box and I know the input field is named "DELETE" but I do not know how to style and give the class (for the checkbox for each form) that I want. -
How to properly generate thumbnail image in Django project?
In my Django project, I need to generate thumbnail images to display them on the main page to avoid a long loading page. But somewhy I got the error Exception class django.db.utils.DataError when adding a new post. Could someone advise me on what's wrong and how to solve it? In my code, first, I save a new post, then I generate a thumbnail as well as resize the original image because it may be huge especially uploaded from iPhone. Here is the code: class Post(models.Model): title = models.CharField(max_length=100, validators=[profanity]) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content = models.TextField(validators=[profanity]) image = models.ImageField(upload_to='diary/images/', blank=True) thumbnail = models.ImageField(upload_to='diary/images/thumbnails/', blank=True, null=True, editable=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) published = models.BooleanField(default=True) def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.image: # Load the image using OpenCV img = cv2.imread(self.image.path) # Generate the thumbnail image thumbnail_size = (200, 200) thumbnail_image = cv2.resize(img, thumbnail_size) thumbnail_path = self.image.path.replace('diary/images/', 'diary/images/thumbnails/') cv2.imwrite(thumbnail_path, thumbnail_image) self.thumbnail.name = thumbnail_path super().save(*args, **kwargs) # Get the dimensions of the image height, width = img.shape[:2] # Set the maximum size of the image max_size = 2000 # Determine the scaling factor to use for resizing the image if height > max_size or width > max_size: scale_factor = max_size … -
ResultMissing when performing a Dramatiq task
For my project (Django-based online shop backend) I implemented a simulated order payment. For practice I decided to use Dramatiq to practice with asynchronous task execution. Here is my code (app_payment/views.py): from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from tasks import post_func_for_payment, backend class PaymentAPIView(APIView): def post(self, request, *args, **kwargs): result = post_func_for_payment.send(request.data, kwargs['id']) response = result.get_result(backend=backend) data_dict = response['data'] return Response(data=data_dict, status=status.HTTP_200_OK) app_payment/tasks.py: import os import django from rest_framework.response import Response from dramatiq.results import Results from dramatiq.results.backends import RedisBackend import dramatiq backend = RedisBackend() broker = dramatiq.get_broker() broker.add_middleware(Results(backend=backend)) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "megano.settings") django.setup() from app_order.models import Order @dramatiq.actor(store_results=True) def post_func_for_payment(data, id): order = Order.objects.get(pk=id) number = data['number'] if int(number[-1]) % 2 != 0 or len(number) != 16: order.status = 'Unpaid' return Response(status=400) data_dict = { "number": number, "name": data['name'], "month": data['month'], "year": data['year'], "code": data['code'] } order.status = 'Paid' order.save() return {'status': order.status, 'data': data_dict} Part of the settings.py code: DRAMATIQ_BROKER = 'dramatiq.brokers.rabbitmq.RabbitmqBroker' DRAMATIQ_BROKER_URL = 'amqp://guest:guest@localhost:5672//' DRAMATIQ_RESULT_BACKEND = "dramatiq.results.backends.redis.RedisBackend" REDIS_HOST = 'localhost' REDIS_PORT = 6379 DRAMATIQ_REDIS_BACKEND_CONFIG = { "url": f"redis://{REDIS_HOST}:{REDIS_PORT}", } However, I get the following error when I try to pay for the order: Internal Server Error: /api/payment/26 Traceback (most recent call last): File "/mnt/c/Users/Victor/PycharmProjects/python_django_diploma/my_venv/lib/python3.10/site-packages/django/core/handlers/exception.py", … -
Many to many field for multiple user type in Django
I am trying to create multiple User types where a single user can be of multiple types. This is the model class I am using: class Role(models.Model): ''' The Role entries are managed by the system, automatically created via a Django data migration. ''' STUDENT = 1 TEACHER = 2 SECRETARY = 3 SUPERVISOR = 4 ADMIN = 5 ROLE_CHOICES = ( (STUDENT, 'student'), (TEACHER, 'teacher'), (SECRETARY, 'secretary'), (SUPERVISOR, 'supervisor'), (ADMIN, 'admin'), ) id = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, primary_key=True) def __str__(self): return self.get_id_display() class User(AbstractUser): roles = models.ManyToManyField(Role) When I create user from the django admin panel, the roles field should allow me to select multiple user types but instead, it shows me a blank box.Image of the admin panel. -
django all auth file path installed locally?
I am trying to locate the location of django all auth package within my project. I installed it with an active virtual environment and ran a command to see the file path and its file path is /usr/local/lib/python3.11/site-packages/allauth/init.py. This looks like its installed locally. I tried installing with pip3 install django-allauth when virtual environment was active. Why isnt this installed within the lib folder in my virtual environment along with django? -
How to efficiently manage nested serializer in DRF?
This is my overrided get method inside APIView, that returns post's detail page: def get(self, request, *args, **kwargs): post_instance = self.get_object() comments = Comment.objects.detail().filter(post=post_instance, comment_to_reply=None)[:5] post_serializer = self.serializer_class(post_instance) comments_serializer = self.comment_serializer_class(comments, many=True) return Response({ 'post': post_serializer.data, 'comments': comments_serializer.data }) It creates only 13 queries in DB without duplicates, but I want to serialize comments inside PostSerializer without overriding it in APIView every time. detail() here is method inside custom manager that select_related and prefetch_related my query. This is the most important part of my PostSerializer: class PostSerializer(TaggitSerializer, serializers.ModelSerializer): author = LightUserSerializer(read_only=True) ... other fields def get_comments(self, instance): comments = Comment.objects.detail().filter(post=instance, comment_to_reply=None)[:5] comments_serializer = CommentSerializer(comments, many=True) return comments_serializer.data def to_representation(self, instance): representation = super().to_representation(instance) representation['comments'] = self.get_comments(instance) return representation It basically the same lines of code from APIView, but in serializer. I get comments inside get_comments function and include it inside Response object through to_representation. It works, but the problem is that this method creates 16 duplicating queries. 25 queries overall. If I use it like SerializerMethodField it works the same way. -
Backend Deveopment practice project
How can we create a project that can be used to store notes which can be textual, audio or video. Where the system can have many users who can share notes amongst them.Should create a backend project for pratacticing the fucntional REST apis. The database can be sqlite for testing the api functionality.The major functionality i need is to store the notes and query the stored notes. I have been trying to do build a project and need some ideas which will help me to prepare a better product -
Django CustomUser with OneToOne realtion has no USERNAME_FIELD when creating a new one
So I have a CustomUserModel and I'm using that to create my extended models models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' class Role(models.TextChoices): ADMIN = 'ADMIN', 'Admin', COMPANY = 'COMPANY', 'Company', STUDENT = 'STUDENT', 'Student' base_role = Role.ADMIN role = models.CharField(max_length=50, choices=Role.choices) objects = CustomUserManager() def save(self, *args, **kwargs): if not self.pk: self.role = self.base_role return super().save(*args, **kwargs) def __str__(self): return self.email class UserCompanyManager(BaseUserManager): def get_queryset(self, *args, **kwargs): results = super().get_queryset(*args, **kwargs) return results.filter(role=User.Role.COMPANY) class UserCompany(User): base_role = User.Role.COMPANY company = UserCompanyManager() class Meta: proxy = True class Company(models.Model): user = models.OneToOneField(UserCompany, on_delete=models.CASCADE) company_name = models.CharField(max_length=50, blank=True, null=True) def __str__(self): return self.company_name My form looks like this class CompanySignUpForm(UserCreationForm): company_name = forms.CharField(widget=forms.TextInput) password1 = forms.CharField(label="Password", widget=forms.PasswordInput) password2 = forms.CharField( label="Password confirmation", widget=forms.PasswordInput ) class Meta: model = UserCompany fields = ['email', 'company_name'] def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise ValidationError("Passwords don't match") return password2 @transaction.atomic def save(self, commit=True): # Save the provided password in hashed format user = super().save(commit=False) user.is_active = True user.set_password(self.cleaned_data["password1"]) print('User created! ', user) if commit: user.save() … -
Is it possible to extend or override Wagtail views?
I'm interested in adding some functionality to my wagtail blog to automatically post to social media when a post is published. Normally, the place to do this would be in the view. I did find an app on github called wagtail_share_social but it has not been updated in 2 years, and I would rather not be reliant on a third party solution. The Wagtail documentation has notes on extending views, but they seem to be limited to extending admin views, or views used in the dashboard rather than for serving up pages to non-logged in users. Is it possible to extend or override the Wagtail views for serving non admin pages? If not, what would be the correct approach to add functionality when a page is served via Wagtail?