Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
is it possible to use django-push-notifications for both android/ios without apns? (if I have both apps in firebase)
I want to use django-push-notifications library for push notifications. My mobile app part configured firebase for both android and ios. In library's documentations they separated logic and configuration of gcm and apns devices. Can I use just GCMDevice for both android and ios devices (to save them, send message) as it is already configured in firebase? Or should I configure apns in django also as it is mentioned in documentation from firebase_admin import auth # Initialize the default app (either use `GOOGLE_APPLICATION_CREDENTIALS` environment variable, or pass a firebase_admin.credentials.Certificate instance) default_app = firebase_admin.initialize_app() PUSH_NOTIFICATIONS_SETTINGS = { "APNS_CERTIFICATE": "/path/to/your/certificate.pem", "APNS_TOPIC": "com.example.push_test", "WNS_PACKAGE_SECURITY_ID": "[your package security id, e.g: 'ms-app://e-3-4-6234...']", "WNS_SECRET_KEY": "[your app secret key, e.g.: 'KDiejnLKDUWodsjmewuSZkk']", "WP_PRIVATE_KEY": "/path/to/your/private.pem", "WP_CLAIMS": {'sub': "mailto:development@example.com"} } -
Static not loaded when django project deployed
I'm trying to deply my django site, and I did to my ip address, but when I load page online it doesn't load static files. I tried changing different settings on a server and on django files, but I'm out of ideas. I would appreciate a pair of fresh eyes. for sites-available I did this: sudo nano /etc/nginx/sites-available/django-site Output: server { listen 80; server_name xx.xx.xxx.xx; #my ip address location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/muser/django-site/staticfiles/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } this is settings.py STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] #media MEDIA_URL = 'media/' MEDIA_ROOT = BASE_DIR / 'media' It might be that this is all correct, but it might be that urls aren't set up properly. So please see urls.py urlpatterns = i18n_patterns( path(_('admin/'), admin.site.urls), path('rosetta/', include('rosetta.urls')), path('', include('my_app.urls', namespace='my_app')), ) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) Any ideas what I did wrong? Thanks in advance! -
ReportLab Encoding Issue When Drawing Translated Text in Django
I encountered an issue when using drawString in ReportLab to draw text in the Czech language after translating the text with Django. I've set the font to Arial, which supports the necessary characters, and noticed the following behavior: When I draw a string directly like this: t = "vůči" self.canvas.drawString(10, 10, t) The text is rendered correctly. However, when I try to draw a translated string like this: from django.utils.translation import gettext as _ t = _("towards") self.canvas.drawString(10, 10, t) The text is rendered incorrectly, showing black rectangles instead of the expected characters, indicating that the characters are not being recognized. Does anyone know why this is happening and how to fix it? -
Django - All users added to all groups
i am working to my first django project and i have some problems while creating users. views.py class registerCrispyForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(registerCrispyForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_method = 'POST' self.helper.add_input(Submit('submit', 'Submit')) class Meta: model = models.UserExt fields = ('username', 'password') def register(request): template_name = 'gestionePrenotazioni/login.html' formR = registerCrispyForm(request.POST) context = {'formRegister':formR} if request.method == 'POST': if formR.is_valid(): user = formR.save() user.set_password(request.POST['password']) user.save() return redirect("home") return render(request, template_name, context) models.py class UserExt(AbstractUser): Image = models.ImageField(upload_to='media/users') abbonamento = models.DateField(null=True, blank=True) class Meta: verbose_name_plural = 'Utenti' When i create a new user he is added to all groups and i can't remove him even in administration panel I have tried to use user.groups.clear() or even to add him only one group but i didn't get any results. -
I am making a celery-django connection, but receiving error "consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//:"
I am trying to make a django-celery connection and running a command "celery -A busynaut worker -l info" but i am receiving a following error this is my celery.py # busynaut/celery.py import os from celery import Celery os.environ.setdefault( 'DJANGO_SETTINGS_MODULE', 'busynaut.settings' ) app = Celery('busynaut') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() this is my init.py # busynaut/__init__.py from .celery import app as celery_app __all__ = ('celery_app',) -
Trying to create a generic HTML template that renders a set of questions under topic headings based on context from views.py
I have several areas, i.e. Leadership, operations, etc., each of which has a set of topics and questions associated with it. Leadership, for example, has 3 topics, each with a different set and number of questions. I am trying to create a general questions.html template where the views.py can then fit with the specific area, topics, questions, etc. for that area. I provide the topics, separate question sets for each topic via context when rendering the page for that area. I am trying to avoid hardcoding each page by looping through each topic and using the question set for that topic. I tested the code by hardcoding 1 question set and seeing if the table render properly, and it does except of course the questions are repeated under each topic. However, when I set the outer loop to loop through the topics with each unique questions set using variables, none of the questions appear. The page just renders the topics with no errors. Here is the code snippet that works but reuses the questions: <tbody> {% for m in categories %} <td colspan="7">{{ m }}</td> {% for key, value in questions1.items %} <tr> <td class="question">{{ value }} </td> {% for … -
Django Project Redirecting to /accounts/login/ URL Despite Custom URLs Configuration
I’m working on a Django project and encountering an issue where the login functionality is redirecting to URLs like /accounts/login/ or /accounts/profile/ which I did not configure. I have customized the login and registration views and removed the default Django authentication URLs. However, the server seems to be redirecting to these default paths. Here are the details of the problem: Project Setup: Django version: 5.1 Custom views for login, registration, and logout are implemented. The urls.py in my app does not include the default Django authentication URLs. urls.py in the app (firstapp/urls.py): python from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path("", views.index, name="index"), path("index/", views.index, name="index"), path("error/", views.custom_404, name="error"), path("login/", views.login, name="login"), path("register/", views.register, name="register"), path("profile/", views.profile, name="profile"), path("logout/", views.logout, name="logout"), # Remove or comment out the line below # path("accounts/", include("django.contrib.auth.urls")), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Remove or comment out handler404 if not using custom 404 view # handler404 = views.custom_404 Views File (views.py): python from django.shortcuts import render, redirect from django.contrib.auth import login as auth_login, logout as auth_logout from django.contrib.auth import update_session_auth_hash from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User, auth from .models … -
fcm-django gives error fcm_django.FCMDevice.user: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out
I'm using fcm-django to send push notifications. I have configured it as it is in documentation. While python manage.py migrate I got an error: SystemCheckError: System check identified some issues: ERRORS: fcm_django.FCMDevice.user: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out. HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'. I have custom user model. I checked fcm_django models and migrations there is no relation with auth.User. In github issues I have found exact the same issue, but it doesn't have a lot information. Only information from owner was https://github.com/xtrinch/fcm-django/issues/207#issuecomment-1091457284 . But I didn't get it How can I fix this? -
how can i have image of user who sign up before
i have three table #post that user create class Post(models.Model): title = models.CharField(max_length=255) content = models.TextField(help_text='type something') author = models.ForeignKey(User,on_delete=models.SET_NULL,null=True) #.... #comment has related to uniqe post class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE) name = models.CharField(max_length=255) #.... #userprofile get image for each user has sign up befor class UserProfile(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) avatr = models.ImageField() comment = models.ForeignKey(Comment,on_delete=models.CASCADE) i try to have user profile image when show comments for any user can we call image when users comment has picture post=get_object_or_404(Post,pk=pid,status=1) #...... comment = Comment.objects.filter(post=post.id,) #like this i want to have my comment details {% for comment in comment %} {{comment.name}} {{comment.userprofile.image.url}} -
Django: cannot display variations of items on the template
I'm working on adding product variations to my website. However, I'm encountering a problem where the drop-down menu is showing product names instead of sizes. My application already filters products by categories, but I need to ensure that the product sizes are displayed correctly on the product detail page. models.py from django.db import models from category.models import Category from django.urls import reverse class Product (models.Model): product_name = models.CharField(max_length=100,unique=True) slug = models.SlugField(max_length=100,unique=True) description = models.CharField(max_length=1000,unique=True) price = models.IntegerField() images = models.ImageField(upload_to='photos/products') stock = models.IntegerField() is_avilable = models.BooleanField(default=True) category = models.ForeignKey(Category,on_delete=models.CASCADE) created_date = models.DateTimeField(auto_now=True) modified_date = models.DateTimeField(auto_now=True) def __str__(self): return self.product_name def get_url(self): return reverse('product_detail',args=[self.category.slug, self.slug]) class VariationManager(models.Manager): def colors(self): return super(VariationManager, self).filter(variation_category='color', is_active=True) def sizes(self): return super(VariationManager, self).filter(variation_category='size', is_active=True) variation_category_choice = ( ('color', 'color'), ('size', 'size'), ) class Variation(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) variation_category = models.CharField(max_length=20, choices= variation_category_choice) variation_value = models.CharField(max_length=100) is_active = models.BooleanField(default=True) created_date =models.DateTimeField(auto_now=True) objects = VariationManager() def __str__(self): return self.variation_value product-details.html {% extends "base.html" %} {% load static %} {%block content%} <section class="section-content padding-y bg"> <div class="container"> <!-- ============================ COMPONENT 1 ================================= --> <div class="card"> <div class="row no-gutters"> <aside class="col-md-6"> <article class="gallery-wrap"> <div class="img-big-wrap"> <a href="#"><img src="{{ single_product.images.url }}"></a> </div> <!-- img-big-wrap.// --> </article> <!-- gallery-wrap .end// --> … -
Django rest framework Google OAuth best packages
I am currently building a webapp with backend in django and frontend in react (Later, I want to add mobile app for it too. I want to add login via Google as only option, so it would be easier for users to register/login. What packages do you think will work the best? What will be the easiest to implement? -
django migration failed : the field value was declared with a lazy reference
I am trying to enforce my User's email should be unique. In my app called accounts I have the below models.py where I created a CustomUser. Then the Employeee model below there is a 1:1 relationship to CustomUser. from django.db import models from django.conf import settings from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): email = models.EmailField(unique=True) groups = models.ManyToManyField( 'auth.Group', related_name='customuser_set', # Unique related_name to avoid conflict blank=True, help_text='The groups this user belongs to.', verbose_name='groups', ) user_permissions = models.ManyToManyField( 'auth.Permission', related_name='customuser_set', # Unique related_name to avoid conflict blank=True, help_text='Specific permissions for this user.', verbose_name='user permissions', ) def __str__(self): return self.username # Create your models here. class Employee(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) number_work_hour_per_week = models.FloatField( help_text="Number of working hour per week" ) work_hour_limit = models.BooleanField( default=False, help_text="If true number_work_hour_per_week applies in the time registration", ) flexible_time_registration = models.BooleanField( default=True, help_text="Allow the user to register working hour flexible without preregistered time", ) def __str__(self): return self.user.username In my settings.py I have overwrite the default User to be accounts.CustomUser AUTH_USER_MODEL = 'accounts.CustomUser' When I do python manage.py migrate I get the below error stack dimsum-dk-py3.10jianwu@localhost:~/webapp/HD_website/website$ poetry run python manage.py migrate accounts zero Operations to perform: Unapply all migrations: accounts Traceback (most recent call last): … -
Send variable to Django crispy forms
I have a Django Crispy form defined in views.py: @login_required def PostCreate(request): if request.method == 'POST': form = PostFileForm(request.POST or None, request.FILES or None) files = request.FILES.getlist('file') if form.is_valid(): post = form.save(commit=False) post.author = request.user form.instance.author = request.user etc. and post_form.html: {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <button class="btn btn-outline-info" id="audit" onclick="audit()">Basic</button> <form method="POST" id="PostForm" data-sektor-url="{% url 'ajax_load_sektors' %}" data-department-url="{% url 'ajax_load_departments' %}" data-person-url="{% url 'ajax_load_persons' %}" novalidate enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4" style="color:red;">Order</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" id="submit" type="submit">Submit</button> </div> </form> in my models.py I have defined all models I need for the full form. Depending on the 4 buttons which user can click to call the form, that form should have some fields hidden/shown or autofilled. I hide them using Javascript, for example: <script type="text/javascript"> function on_load(){ document.getElementById('hidden_on_open').style.display = 'none'; My problem is, I don't know which button is pressed. Is there a way to 'pass a static variable' or something to the HTML, since if I pass it to views.py it's already rendered? So that I can use Javascript to hide/show and autofill certain fields depending on that variable. Just … -
Django ORM efficient way for annotating True on first occurrences of field
I have a situation where we have some logic that sorts a patient_journey queryset (table) by some heuristics. A patient_journey has a FK to a patient. I now need an efficient way of setting True for the first occurrence of a patient_journey for a given patient, false otherwise. The first heuristinc is patient_id so the queryset will already by grouped by patient. The algorithm is v straight forward & should be fast, yet I'm stuck at trying to get something <1s. I've tried using distinct and checking for existence, however that's adding 1-2s. I've tried using a subquery with [:1] & test on id, but that's even worse around 3-5s extra. def annotate_primary( *, qs: 'PatientJourneyQuerySet' # noqa ) -> 'PatientJourneyQuerySet': # noqa """ Constraints: -------------- Exactly One non-global primary journey per patient Annotations: ------------ is_primary_:Bool, is the primary_journey for a patient """ from patient_journey.models import PatientJourney qs = get_sorted_for_primary_journey_qs(qs=qs) # cost until now is around 0.17s # using distinct on patient_id & checking if id is in there adds around 1.5-2s # looking for something faster, i.e. this shoiuld be a straight forward scan. qs = qs.annotate( # True for first occurrence of a `patient_id` false otherwise primary= ) … -
"detail": "Authentication credentials were not provided." postman django
Trying to do authorization on tokens When I make a POST request through postman it gives an error "detail": "Authentication credentials were not provided." REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_PARSER_CLASSES':[ 'rest_framework.parsers.JSONParser', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', #'rest_framework.authentication.SessionAuthentication', #'rest_framework_simplejwt.authentication.JWTAuthentication', ] manager.py from django.contrib.auth.models import BaseUserManager from django.core.exceptions import ValidationError from django.core.validators import validate_email from django.utils.translation import gettext_lazy as _ class UserManager(BaseUserManager): def email_validator(self, email): try: validate_email(email) except ValidationError: raise ValueError(_("please ener a valid email")) def create_user(self, email, username, password, **extra_fields): if email: email=self.normalize_email(email) self.email_validator(email) else: raise ValueError(_("an email adress is required")) if not username: raise ValueError(_("an username is required")) user=self.model(email=email, username=username, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password, **extra_fields): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) extra_fields.setdefault("is_verified", True) if extra_fields.get("is_staff") is not True: raise ValueError(_("is staff must be true for admin user")) if extra_fields.get("is_superuser") is not True: raise ValueError(_("is superuser must be true for admin user")) user = self.create_user( email, username, password, **extra_fields ) user.save(using=self._db) return user views.py from django.shortcuts import render from rest_framework.generics import GenericAPIView from .serializers import UserSerializer from rest_framework.response import Response from rest_framework import status from .utils import send_code_to_user class RegisterUserView(GenericAPIView): serializer_class=UserSerializer def post(self, request): user_data=request.data serializer=self.serializer_class(data=user_data) if serializer.is_valid(raise_exception=True): serializer.save() user=serializer.data send_code_to_user(user['email']) return Response({ 'data':user, 'message':f'hi{user.username}' }, … -
Azure Appservice for Django fails with Azure Devops Pipeline
I have an appservice running on Azure in a Linux environment. I try to associate it with a Azure Devops Pipeline so I can have CI/CD for the repositories & branches on Github. I want the builds to occur on Azure Pipeline & Azure infrastructure, not Github Actions. I have tried all other suggestions including following environment variables on App Service : SCM_DO_BUILD_DURING_DEPLOYMENT=true WEBSITE_NODE_DEFAULT_VERSION=~18 WEBSITE_RUN_FROM_PACKAGE=true Here is the logs that I receive from the Kudu / Azure Devops Pipeline / AppService logs : /home/LogFiles/2024_08_14_ln1xsdlwk0000K3_docker.log (https://project-app-development.scm.azurewebsites.net/api/vfs/LogFiles/2024_08_14_ln1xsdlwk0000K3_docker.log) 2024-08-14T23:51:45.168Z INFO - Status: Image is up to date for 10.1.0.6:13209/appsvc/python:3.10_20240619.2.tuxprod 2024-08-14T23:51:45.179Z INFO - Pull Image successful, Time taken: 0 Seconds 2024-08-14T23:51:45.223Z INFO - Starting container for site 2024-08-14T23:51:45.223Z INFO - docker run -d --expose=8000 --name project-app-development_0_f2e0544d -e WEBSITE_USE_DIAGNOSTIC_SERVER=false -e WEBSITE_SITE_NAME=project-app-development -e WEBSITE_AUTH_ENABLED=False -e WEBSITE_ROLE_INSTANCE_ID=0 -e WEBSITE_HOSTNAME=project-app-development.azurewebsites.net -e WEBSITE_INSTANCE_ID=3f627dbbecdaed255d87aa9c3e8f1448758df1cdff41f5e14b114384ea9b244a appsvc/python:3.10_20240619.2.tuxprod gunicorn -b :$PORT project.wsgi 2024-08-14T23:51:45.223Z INFO - Logging is not enabled for this container. Please use https://aka.ms/linux-diagnostics to enable logging to see container logs here. 2024-08-14T23:51:45.893Z INFO - Initiating warmup request to container project-app-development_0_f2e0544d for site project-app-development 2024-08-14T23:51:49.043Z ERROR - Container project-app-development_0_f2e0544d for site project-app-development has exited, failing site start 2024-08-14T23:51:49.057Z ERROR - Container project-app-development_0_f2e0544d didn't respond to HTTP pings on port: 8000, failing site … -
How do I use prefetch_related for Generic Relationship in Django?
I've multiple models. Model1, Model2, Model3, ... Each model requires multiple let's say feature/images. Can be implemented by making different Image models ( i.e. Morel1Image ) then link with foreign key. Or, Make a Generic Image Model and use it wherever it needs. The problem is, I'm having similar queries ( debug ). And prefect_related isn't working ( Django might not have the feature ). Now how do I solve the problem ( efficiently ) ? I'm expecting no similar or duplicate quary. -
Using formset in django formtool
am creating a 8 steps form wizard. 2 of the models are Qualification and SSCE and i used formset to create multiple forms inputs Formset factory QualificationsFormSet = modelformset_factory(Qualifications, form=QualificationsForm, extra=5) SscesFormSet = modelformset_factory(Ssces, form=SSCESubjectForm, extra=5) the View class StudentWizard(LoginRequiredMixin, SessionWizardView): form_list = FORMS # template_name = 'admission/form_wizard.html' file_storage = FileSystemStorage(location='/tmp/') def get_form(self, step=None, data=None, files=None): if step is None: step = self.steps.current form = super().get_form(step, data, files) form.request = self.request if step == '3': form = QualificationsFormSet(data, queryset=Qualifications.objects.none()) elif step == '4': form = SscesFormSet(data, queryset=Ssces.objects.none()) return form def get_form_instance(self, step): print(f"Current step: {step}") if step == '4': # SSCE step qualifications = self.get_cleaned_data_for_step('3') print(f"Qualifications data: {qualifications}") if qualifications: certificates = [qual['certificate_obtained'] for qual in qualifications] print(f"Certificates: {certificates}") if not any(cert in ['WASC', 'SSCE', 'NECO', 'GCE'] for cert in certificates): print("Skipping SSCE step") return None # Skip the Ssces formset return super().get_form_instance(step) def get_context_data(self, form, **kwargs): context = super().get_context_data(form=form, **kwargs) if self.steps.current in ["3", "4"]: context['formset'] = form context['formset_with_widgets'] = [ [(field, field.field.widget.__class__.__name__) for field in form] for form in context['formset'].forms ] else: context['fields_with_widgets'] = [ (field, field.field.widget.__class__.__name__) for field in form ] return context the problem is that the other forms works well upto the Qualification where after … -
Django admin popup window not closed after the form submitted successfully
I have a computed field(add_workplace_link) in display_list to open a popup window in order to add new instance of Workplace model. The popup window opens as expected. After form submitted successfully, the window remains open an empty page. models.py from django.db import models class Company(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Workplace(models.Model): title = models.CharField(max_length=255) company = models.ForeignKey(Company, on_delete=models.CASCADE) def __str__(self): return self.title admin.py @admin.register(Company) class CompanyAdmin(admin.ModelAdmin): list_display = ['name', 'add_workplace_link'] def add_workplace_link(self, obj): # Generate the URL to the Workplace add form with the company preselected url = reverse('admin:appname_workplace_add') + f'?company={obj.pk}' return format_html('<a href="{}">Add Workplace</a>', url) add_workplace_link.short_description = 'Add Workplace' class WorkplaceAdmin(admin.ModelAdmin): list_display = ['title', 'company'] def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) # Check if we have the company parameter in the URL and set the initial value if 'company' in request.GET: company_id = request.GET.get('company') form.base_fields['company'].initial = company_id return form Admin changelist for Company model popup window opened as expected popup window remains open after form submitted successfully I already checked to make sure RelatedObjectLookups.js is loaded in popup window. I expect the popup window close automatically after form submitted successfully. What is missing? -
How i run a program in background in django without loading page
i am working on a project which has a function which generate response automatically on loop using google gemini api and show it to the html page by saving it to the database, i want this function to run in background all the time without loading the page Currently what is happening is, if the function is generating 10 response in a loop then it is keep loading the page until all response get generated and then it is showing me home.html page. Someone told me to use command management and i made the command, but i dont know how this command is going to run a function automatically in background on starting a server. i am providing a example command code, suppose i want to run it in background withouth loading a page, what should i do. from django.core.management.base import BaseCommand from main.models import Data1 data1 = Data1.objects.all() class Command(BaseCommand): help = 'Displays stats related to Article and Comment models' def handle(self, *args, **kwargs): for data_test in data1: print(data_test) -
How to get an attribute of a serializer class in DRF?
I have a serializer class CourseSerializer. A course can have a number of groups, lessons and etc.. A code for a serializer: class CourseSerializer(serializers.ModelSerializer): lessons = MiniLessonSerializer(many=True, read_only=True) lessons_count = serializers.SerializerMethodField(read_only=True) students_count = serializers.SerializerMethodField(read_only=True) groups_filled_percent = serializers.SerializerMethodField(read_only=True) demand_course_percent = serializers.SerializerMethodField(read_only=True) def get_lessons_count(self, obj) -> int: return obj.lessons.count() def get_students_count(self, obj) -> int: amount = Subscription.objects.filter().count() return amount def get_groups_filled_percent(self, obj) -> int: counts = [group.users.count() for group in obj.groups.all()] return ((sum(counts) / len(counts)) / 30) * 100 def get_demand_course_percent(self, obj) -> int: users = CustomUser.objects.all().count() students = Subscription.objects.filter().count() return (students / users) * 100 As you see, a serializer has calculated attributes like lessons_count, students_count ad etc.. The question is: how can I get one of these attributes in a serializer method, for example: def get_demand_course_percent(self, obj) -> int: users = CustomUser.objects.all().count() return (self.students_count / users) * 100_ If I do like this explicitly, it gives an Attribute error that there's no such attribute in a serializer class -
Incorrect inharitance of objects in django python app
I have a model MenuIngredientConsumption, which is inherited from MenuOfferOptionModificationThrough. class MenuOfferOptionModificationThrough(models.Model) : 'content of offer' menu_offer_option_modification = models.ForeignKey(MenuOfferOptionModification, on_delete=models.CASCADE) storage_position = models.ForeignKey(StoragePosition, on_delete=models.CASCADE) quantity = models.DecimalField(max_digits=20, decimal_places=2, null=True) ingredient_name = models.CharField( max_length=200, validators=[MinLengthValidator(2, "Title must be greater than 2 characters")] ) class MenuIngredientConsumption(MenuOfferOptionModificationThrough) : created_at = models.DateTimeField(auto_now_add=True) I have 2 created objects of MenuOfferOptionModificationThrough. MenuOfferOptionModificationThrough(..., ingredient_name="potato") MenuOfferOptionModificationThrough(..., ingredient_name="tomato") So i want to copy these 2 objects of MenuOfferOptionModificationThrough to MenuIngredientConsumption. And i wrote a code in view.py: def post(self, request, **kwargs): gastronomy = get_object_or_404(Gastronomy, id=self.kwargs['gastronomy_pk']) order_modification_through = get_object_or_404(OrderModificationThrough, id=self.kwargs['order_modification_pk']) menu_offer_option_modification = order_modification_through.menu_offer_option_modification quantity = order_modification_through.quantity menu_offer_option_modification_through_list = MenuOfferOptionModificationThrough.objects.filter(menu_offer_option_modification=menu_offer_option_modification) if menu_offer_option_modification_through_list: for i in range(quantity): for ingredient in menu_offer_option_modification_through_list: menu_ingredient_consumption = MenuIngredientConsumption( menu_offer_option_modification = ingredient.menu_offer_option_modification, storage_position = ingredient.storage_position, quantity = ingredient.quantity, ingredient_name = ingredient.ingredient_name, ) menu_ingredient_consumption.save() Yes, I copy 2 objects to MenuIngredientConsumption, but also i have 6 objects of MenuOfferOptionModificationThrough. But there should be 2 still (I didn;t work with it). I don't understand why it happens. Please, help. -
Django module not found error on running docker-compose up command
I'm trying to setup local development server for my website www.priyaji.thakurani.in using dockers. The website is built on using python 3.6.8 and django 3.1.5. On running docker-compose build django command, I can see the packages from priyaji_requirements.txt getting loaded. And the command finishes successfully. However on running docker-compose up django command I'm constantly getting django module not found error. **Here's the output of docker-compose build django **. kunjabeharidasa@Kunjabeharis-MacBook-Air Priyaji % docker-compose build django WARN[0000] /Users/kunjabeharidasa/Priyalaljiu/Priyaji/docker-compose.yml: version is obsolete [+] Building 840.8s (32/32) FINISHED docker:desktop-linux => [django internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 4.10kB 0.0s => [django internal] load metadata for docker.io/library/python:3.6.8 2.2s => [django internal] load .dockerignore 0.0s => => transferring context: 412B 0.0s => [django internal] load build context 4.2s => => transferring context: 13.00MB 3.5s => [django builder 1/18] FROM docker.io/library/python:3.6.8@sha256:f20a9bfddd87c238c3d2316b4179222f219090cbb25 0.0s => CACHED [django builder 2/18] RUN sed -i 's/deb.debian.org/archive.debian.org/g' /etc/apt/sources.list && 0.0s => CACHED [django builder 3/18] RUN apt-get update && apt-get install -y build-essential libssl-dev 0.0s => CACHED [django builder 4/18] RUN pip install six && pip install --upgrade pip && pip install setupto 0.0s => CACHED [django builder 5/18] RUN groupadd -r django && useradd -r -g django django … -
Unable to update latest database configuration in settings.py in django
I write code on my local machine and then use github to transfer the code to my Amazon AWS EC2 server, I am using AWS Route53 to connect to a domain name and AWS RDS for database (started using recently, few days ago). In my previous code I was using Hostinger's remote mysql capability for a hosted database which was working fine, I deployed the code on AWS EC2 server and tested, however, when I created MySql database using RDS and updated its details in the settings.py the application is still being run using the old Hostinger's database settings only. I have tried the following things: deleting all the cache files, removing all migrations files and creating migrations once again, checked settings.py (database configuration settings) multiple times Restarted the EC2 instance, restarted supervisor, gunicorn, nginx Deleted the RDS database and created one more and updated its respective settings in settings.py To my surprise, for some reason it is still working on the old database, I am not able to figure out where exactly is it picking up the details of the old database and why is the latest settings.py file not being loaded in real time? -
Why is Django App Not Rendering HTML Page
Hello I am using Django version 4.2.3 to build my website for building my website. I have an Object called UE (upcoming_events) that I have added several fields to however, these fields don't seem to be rendering when I call the object instead the words No Events render which only happen when the upcoming_events object is empty. In order to see why this is happening I used the Django Shell to visualize the code post processing. But in the visualization the code seems to populate the objects just fine just not when rendering the object on the website. {% extends "webapp/header.html" %} {% block content %} <div class = "centerbody"> <div class="liner"> <!--Carousel Starts--> <div class = 'dive'></div> <div class = float_col> <div id="carouselExampleFade" class="carousel slide carousel-fade span" data-ride="carousel"> <div class="carousel-inner carouselMargin1"> <div class="carousel-item active"> <img src="/static/images/CarouselPictures1/canyonphoto1.jpg/" class="d-block w-100 carouselImgs" alt="..."> </div> <div class="carousel-item"> <img src="/static/images/CarouselPictures1/canyonphoto2.jpg" class="d-block w-100 carouselImgs" alt="..."> </div> <div class="carousel-item"> <img src="/static/images/CarouselPictures1/canyonphoto3.jpg/" class="d-block w-100 carouselImgs" alt="..."> </div> </div> <a class="carousel-control-prev" href="#carouselExampleFade" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleFade" role="button" data-slide="next"> <span class="carousel-control-next-icon next_button" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div> <div class="announcements"> <h2>Announcements</h2> <div class="announcement-container"> {% for announcement in announcements %} <div class="announcement-item"> <img …