Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to override a SerializerMethodField for an inherited Serializer?
Is it possible to override a SerializerMethodField from an inherited Serializer? E.g. # serializers.py class BaseSerializer(serializers.ModelSerializer): custom = serializers.SerializerMethodField() class Meta: model = Item fields = ["pk", "custom"] def get_custom(self, obj): return "Base"; class ExtendedSerializer(BaseSerializer): custom = serializers.SerializerMethodField() class Meta: model = Item fields = ["pk", "custom"] def get_custom(self, obj): return "Extended"; Obviously the above code doesn't work. I've currently had to create another Serializer and declare a new SerializerMethodField for the inheriting Serializers: # serializers.py class DefaultSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ["pk"] class BaseSerializer(DefaultSerializer): custom = serializers.SerializerMethodField() class Meta: model = Item fields = ["pk", "custom"] def get_custom(self, obj): return "Base"; class ExtendedSerializer(DefaultSerializer): custom = serializers.SerializerMethodField() class Meta: model = Item fields = ["pk", "custom"] def get_custom(self, obj): return "Extended"; But it would be neater for my use case if I could just override an existing SerializerMethodField as in my first code block. -
HTML not linking to CSS file django
I know there are so many questions on this but I'm yet to find a solution. I have the below folder structure for my django app: I then reference the styles.css file from my index.html page, like so: <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous"> {% load static%} <link rel="stylesheet" href="{% static 'css/styles.css' %}"> but no matter what I change in my css file it doesn't affect my webpage. css file if useful: .form-details { text-align: center; color: Tomato; background-color: red;} -
Count objects in queryset by value in a field. Django
Imagine I have a model which looks something like following: class Car(models.Model): TYPE_CHOICES = [ (1: 'Hatchback') (2: 'Saloon') type = models.CharField(choices=TYPE_CHOICES, ...) color = models.CharField() owner = models.ForeignKey(User, ...) And I want to count objects by specific values. Say black saloons owned by Johns or white hatchbacks owned by Matts. The best what I came up so far is: Car.objects.annotate( black_saloons_owned_by_John=Count( 'type', filter=( Q(type=2) & Q(owner__first_name='John') ) ) ).aggregate( aggregated_black_saloons_owned_by_John=Sum( 'black_saloons_owned_by_John' ) ) Is there a better way to get the desired result? Thanks. -
cPanel: Django Admin Portal not loading Static/CSS files
I'm trying to deploy my Django App on cpanel and the static files for django admin page won't show up but its working fine for the rest of the project. I even tried to run python manage.py collectstatic but it just gives me an error that something's wrong with my manage.py A little help would be appreciated. Thank you! -
Corsheaders in django admin
I'm using django-cors-headers and it's working fine with django rest, but in Django admin doesn't. In Django I've a model: class Animation(models.Model): code = models.CharField(max_length=50, unique=True) name = models.CharField(max_length=500, default='') time = models.DecimalField(default=0.0, max_digits=6, decimal_places=2) animation = models.CharField(max_length=500) The animation field has the URL of a Lottie animation, and in the admin template has: {% if adminform.form.instance.animation %} <script src="https://unpkg.com/@lottiefiles/lottie-player@latest/dist/lottie-player.js"></script> <lottie-player id="animationPlayer" src="{{ adminform.form.instance.animation }}" background="transparent" speed="1" style="width: 300px; height: 300px;" loop controls autoplay> </lottie-player> {% endif %} I'm having CORS problems inside django admin because the admin is in https://example.com/admin and the animation in https://static.example.com/animation.json -
How can I add placeholders to Djangos default authentication form's input fields (username and password)?
So I use Django's built-in authentication form for the user login. How can I adjust this form so I will have placeholder attributes for the html input objects? <form method="post" action="."> {% csrf_token %} <div class="email-wrapper field-wrapper"> <div class="input">{{ form.username }}</div> </div> <div class="password-wrapper field-wrapper"> <div class="input">{{ form.password }}</div> </div> <button class="login-button" type="submit">Log in</button> </form> path('login/', views.LoginView.as_view(template_name='userprofile/login.html'), name="login"), Couldn't find any example in the official docu. However, it states authentication_form: A callable (typically a form class) to use for authentication. Defaults to AuthenticationForm. So do I have to define an entire new form? -
add group into AbstractUser
I use AbstractUser to verify email and it success but I have problem with adding groups inside class customuser class CustomUser(AbstractUser): is_email_verified=models.BooleanField(default=False) so how i can add group inside that class -
How do i implement real time consultation on my app?
Within the past few days, i have learnt how to connect django and react to create a full stack application, the problem is that all the coding tutorials ive seen dont handle real time applications. seeing as my app is an online doctor consultation platform, i need to know how to allow the patient and the doctor communicate in real time. Any suggestion to go about it? -
django cannot create model with sufficient data
models.py class QuestionReply(models.Model): reply_user = models.ForeignKey(cUser, on_delete=models.CASCADE) reply_question = models.ForeignKey(Question, on_delete=models.CASCADE) reply = models.TextField() votes = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) views.py class AddQuestionReply(APIView): def post(self, request, id): try: reply = request.data.get('reply') reply_user = request.data.get('reply_user') reply_to_question = models.QuestionReply(reply_user=reply_user, reply_question=id, reply=reply) reply_to_question.save() return Response({'OK': 'Reply added'}, status=status.HTTP_200_OK) except: return Response({'400': f'QuestionReply has invalid data'}, status=status.HTTP_400_BAD_REQUEST) urls.py path('questions/question-reply/add/<int:id>', views.AddQuestionReply.as_view(), name='add-question-reply') data sent { "reply_user": "1", "reply": "Hello, world" } I have a model with 2 foreign keys, a TextField and 2 default fields, I sent the needed data to the url(reply_question comes from the url) but for some reason the model doesnt get created and an error occurs. -
Django how to filter a foreign key object only with specific value
I have two tables. Table Product id | name | Table Discount id | product_id | is_deleted product_id is the foreign key of product table's id, and is_deleted is a boolean field. How can I filter all products only with is_deleted discount? Notice those two tables may be large, so .exclude() is not fit for this case. -
Django change my migration write in migrations
I want to change my previous migration - in models I have this field: number = models.CharField('Number', max_length=8, unique=True, blank=True, editable=False, validators=[ MinLengthValidator(8), RegexValidator( regex=r'^[А-ЯҐЄІЇ]{2}-\d{5}$', message='Example TP-00001', ), ]) I want that my field looks like this: number = models.CharField('Number', max_length=11, unique=True, blank=True, editable=False, validators=[ MinLengthValidator(11), RegexValidator( regex=r'^[А-ЯҐЄІЇ]{2}-\d{8}$', message='Example TP-00000001', ), ]) That in regex I changed count of digits from 5 to 8. In my migration file I have this: migrations.AlterField( model_name='book', name='number', field=models.CharField(blank=True, editable=False, max_length=8, unique=True, validators=[django.core.validators.MinLengthValidator(8), django.core.validators.RegexValidator( message='Example: TP-00001', regex='^[А-ЯҐЄІЇ]{2}-\\d{5}$')], verbose_name='Number'), ), ] I tried to write func before this which change my migration: def update_number(apps, schema): Book = apps.get_model('library', 'Book') for bb in Book.objects.all(): bb.number = bb.number(regex='^[А-ЯҐЄІЇ]{2}-\\d{8}$') bb.save(update_fields=['number']) Here I tried to change number from 5 to 8 .What I am doing wrong?Please help? -
Getting "The current path, X didn’t match any of these." even though utls.py are configued
I have a weird problem with django not finding my file. Should be basic, but I cannot figure that out. If my app name is convers and the the file convers/urls.py (same folder as where settings.py is) reads: form django.contrib import admin from django.urls import path,include from django.views.generic import RedirectView from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('c/',include('convers_app.urls')), path('conversapp/',include('convers_app.urls')), path('',RedirectView.as_view(url='conversapp/')), ] + static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) the urls.py in my convers_app folder reads from django.urls import path from .import views urlpatterns = [ path('',views.index, name='index'), path('timer', views.timer, name='timer') ] and in my views.py folder I have def timer(request): return render(request, 'timer.html') I also have the timer.html in my templates folder. What am I missing? Why won't django locate my timerview? -
gTTS.say(text) takes string
I am trying to create a website using Django which will take some text as input and convert it into audio. I created an empty array that should store the value of the input and convert it into audio. But when I run the server, it gives me an error saying - gTTS.say(text) takes string. My views.py #An empty array called textForTts textForTts = [] class UploadFileForm(forms.Form): tts = forms.CharField(label = "Convert text to audio here") def index(request): if request.method == "POST": form = UploadFileForm(request.POST) if form.is_valid(): tts = form.cleaned_data["tts"] textForTts.append(tts) obj = say(language='en-us', text= textForTts) return render(request,'demo/website.html',{ "form" : UploadFileForm(), 'obj':obj }) my index.html: {% block body %} {% load gTTS %} <form method="post"> {% csrf_token %} <audio src = "{{obj}}" controls ></audio> {{form}} <input type = "submit"> </form> {% endblock %} This is my first time trying out Django. What should I do to fix my errors? Thanks in advance. -
Django global variables with threading
I'm building a web-app to control some hardware connected to a Raspberry Pi. The goal: On server startup do some tasks once and store information globally (open COM Ports and store as objects) On POST/GET call from a view start a thread with the serialports from 1) plus some data (names as Strings) from the POST/GET call. This thread is some game logic for the hardware and runs for around one hour each Have possibility to terminate this thread anytime from a view and from within the thread Have possibility to get variables from thread and display on web-app At the moment I'm struggeling with the general design of this task. I'm new to threading and Django and can't quite tie these together. My Implementation right now only has a simple endless loop which should print out some debugging info if a global variable has changed. On startup of the server, I'm starting a runner script in a new thread. The global var is stored in cfg.py and imported in apps.py and views.py. All three files are in the root directory of the app. cfg.py RUNNING = False views.py from django.shortcuts import render from .models import Player from . import … -
How, when selecting a category, display both the elements of this category and the elements of all its subcategories?
I am new to django, and in python too, now I am practicing on creating an online store and faced the problem that it would be logical, when choosing a category, to also display products from all its subcategories. Google, unfortunately, did not help ... I think that you need to somehow correctly filter the product in the views, but how? skills are not enough to understand. Using Django-mptt for the category tree (fewer database queries) models.py class Category(MPTTModel): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['name'] class Meta: ordering = ('name',) verbose_name = 'Категория' verbose_name_plural = 'Категории' def get_absolute_url(self): return reverse('shop:product_list_by_category', args=[self.slug]) def __str__(self): return self.name views.py def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True).order_by('-created') if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) return render(request, 'shop/shop.html', {'category': category, 'categories': categories, 'products': products}) html <div class="category_conteiner"> {% recursetree categories %} <div class="sub_menu_category"> <a href="{{ node.get_absolute_url }}" class="subcatbtn">{{ node.name }}</a> {% if not node.is_leaf_node %} <div class="subcat_content"> <div class="subcat_column"> {{ children }} </div> </div> {% endif %} </div> {% endrecursetree %} For example, there are such categories: -Clothing --- Jackets --- Hats If … -
I need to check an aws server for the existence of a file, if it does I need to save it to a django object
So, I am currently attempting to port data into a new system. We have a simple file system that uses an Image model with a file field connected to S3Boto3Storage. What I need to do is check the existence of a file with a known path, and if it is there, save an Image object in Django connected to that file. Im not even sure where to start, I thought about using Django Fixtures to load a bunch of image files based on a certain path, but I worry about the safety of doing that on a production branch. Has anyone encountered this kind of issue? -
Django master-slave data sync
I've just started to learn about Master-slave architecture and I have some questions: The data added to master db not sync to the slave db, is it correct? When I try to add a foo object to masterdb, and try to read it from slavedb, there is nothing. If it not so when we will use this architecture? Thank you all. -
REST API for a Facemask detection neural network model
a model has already been trained for the purpose of facemask detection using yolov5 while using react as a frontend. rest api is to be used for connecting the frontend and the ML MODEL for accessing the webcam is there any help one can get to implement the api,the frontend has a button to request live stream which should access the function of the ML model to project the webcam and state facemask detection but having problem with using django rest api. -
Cannot resolve keyword 'approve_moderator' into field. Choices are: id, user, user_id
Problem Synopsis: I am implementing a login logic that checks if the user is registered and in the MODERATOR group (a user is automatically added to the MODERATOR group on registration) with the status of "approve_moderator" set to True. The field "approve_moderator" is False by default. Now during login, I check if the user is a registered user and is approved before redirecting them to the moderator dashboard views.py def is_moderator(user): '''check if registered and in moderator group''' return user.groups.filter(name='MODERATOR').exists() def afterlogin_view(request): if is_student(request.user): messages.success(request, 'successfully logged in as ' + request.user.username) return redirect('student-dashboard') elif is_moderator(request.user): approval_status = Moderator.objects.all().filter(user_id=request.user.id, approve_moderator=True) if approval_status: return redirect('moderator-dashboard') else: return redirect('moderator-wait-approval') elif is_admin(request.user): return redirect('admin-dashboard') else: return redirect('login') def register_moderator_view(request): if request.user.is_authenticated and request.user.is_moderator: return redirect('moderator-dashboard') else: form = RegistrationForm() if request.method == 'POST': form = RegistrationForm(request.POST, request.FILES) if form.is_valid(): user = form.save(commit=False) user.is_moderator = False user.save() moderator = Moderator.objects.create(user=user) moderator_group, created = Group.objects.get_or_create(name='MODERATOR') moderator.user.groups.add(moderator_group) messages.info(request, 'Registration successful!') return redirect('login') # else: # messages.warning(request, 'Form invalid!') form = RegistrationForm() return render(request, 'accounts/register.html', {'form': form }) models.py class CustomUser(AbstractUser): email = models.EmailField(_('email address'), unique=True) phone = models.CharField(max_length=150, null=True, blank=True) address = models.CharField(max_length=200, null=True, blank=True) profile_picture = models.ImageField(default='images/student.png', upload_to='profile_picture/', null=True, blank=True) is_student = models.BooleanField(default=False) is_moderator = … -
How to make Django load profile image files form "media" directory
I have a directory '/media/profile_image' where profile images uploaded by users are saved. In the template I built the url by using the user object <img id="profile_image" src="{{ request.user.profile_image.url }}"></div> which creates the correct url to the desired directory. But it doesn't show the image, why's that? -
Integrating Django Admin with Firebase
I'm working on a mobile application where the backend is done by Dango but all the authentication and real-time database are in firebase is there any way to integrate a Django admin with firebase instead of using firebase admin? if not, can firebase admin be used with python to create an admin role and has the same permissions which Django gives to admin? and how to introduce the created role if possible to Django? -
Django Vue.js PasswordResetView posted with Axios gets Error 403 Forbidden CSRF Token
I am trying to create a custom Email Restore page in the frontend with Vue.js. There, I am trying to send input with an email with Axios through /api/v1/accounts/password_reset/, so basically I am trying to use the original ResetPasswordView and instead of using its template, I am using it as an endpoint. When I submit the value, the console returns Error 403 Forbidden CSRF Token, like below. What can be done to avoid it? Forbidden (CSRF cookie not set.): /api/v1/accounts/password_reset/ [07/Sep/2021 16:32:55] "POST /api/v1/accounts/password_reset/ HTTP/1.1" 403 2864 /Users/IvanStepanchuk/Desktop/web-project/web-backend/core/settings.py changed, reloading. Watching for file changes with StatReloader Performing system checks... This is my ResetPassword.vue: <template> <div id="login"> <div class="w-100 d-flex justify-content-center" id="home__screen"> <div class="col-sm col-lg-4 text-center align-self-center decorator__spacing"> <div class="card bg-white p-4"> <h1 class="fs-3 pb-3">Recover your account</h1> <form @submit.prevent="passwordReset"> <div class="mb-3"> <input type="email" class="form-control" id="username" v-model="email" aria-describedby="emailHelp" placeholder="Email con el cual se ha registrado"> </div> <div class="alert alert-primary d-flex flex-column" role="alert" v-if="errors.length"> <span v-for="error in errors" v-bind:key="error">{{error}}</span> </div> <button type="submit" class="btn btn-primary mb-3">Enviar</button> </form> </div> </div> </div> </div> </template> <script> import axios from 'axios' export default { name: 'ResetPassword', data() { return { email: '', errors: [] } }, components: { }, mounted() { document.title = 'Company | Recover Account' }, … -
how to access external postgresql database and other services network server in side docker container
'''docker version: '3.9' services: web: build: . command: gunicorn --chdir DjangoRestApi build.wsgi:application --bind 0.0.0.0:8000 volumes: - .:/app - static_volume:/app/static ports: - 8000:8000 env_file: - ./.env networks: - services nginx: build: ./nginx volumes: - static_volume:/app/static ports: - 1234:80 depends_on: - web networks: - services client: build: client/ command: python client.py volumes: - ./client:/client depends_on: - web - nginx networks: - services volumes: networks: new: external: true ''' -
Get number of registers by prefetch_related, created before 45 minutes, in Django
It is dificult to explain, I am going to try. I have a table whateverA and table whateverB. They are joined by a ForeingKey. whateverB have the foreingkey. I need to get the registers in whateverA where whateverB_created (is the field with date create) is less than 45 minutes. less45 = datetime.datetime.today() - timedelta(minutes=45) b=whateverA.objects.prefetch_related('whateverB_set').filter(whateverB__created__lt = less45).count() Obviously, this query is not correct, because I have to get the register in whateverB with the last date in whateverB_created, and then, compare it with less45. I know that it is with annotate(max(whaterverB__created)) but when I do not know how compare with less45, because I can not apply _lt and I can not use <>. -
convert this format Tue Sep 07 2021 08:34:00 GMT+0530 (India Standard Time) to YYYY-MM-DD HH:MM:SS in python or django
I am trying to convert this format or any timezone format to YYYY-MM-DD HH:MM:SS. format needed to be converted is - Tue Sep 07 2021 08:34:00 GMT+0530 (India Standard Time). can anyone help ?