Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to build a form in django based on 3 models with Many-To-Many relationship
This is my first experience with django and I'm stuck on creating the form. The models that must be involved in the form are the following: models.py class Ingredient(models.Model): name = models.CharField(max_length=100) id_category = models.ForeignKey(Category, on_delete=models.CASCADE) property = YAMLField() def __str__(self): return self.name class Meta: verbose_name_plural = "Ingredients" class Category(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Meta: verbose_name_plural = "Categories" class Inventory(models.Model): id_user = models.ManyToManyField(User) name = models.CharField(max_length=200) last_update = models.DateTimeField(auto_now=True) creation_date = models.DateTimeField(auto_now_add=True) ingredients = models.ManyToManyField(Ingredient, through='InventoryIngredient') class Meta: verbose_name_plural = 'Inventories' ordering = ['-creation_date'] class InventoryIngredient(models.Model): id_ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) id_inventory = models.ForeignKey(Inventory, on_delete=models.CASCADE) quantity = models.DecimalField(decimal_places=2, max_digits=10) measurement_unit = models.CharField(max_length=100) expiry_date = models.DateField() I don't know where to start implementing the form. I tried to look for something similar but I didn't find anything about form management in case of many-to-many relationship with a through table. In practice, in my form there will have to be the attributes of the Ingredient(name, property) model and the attributes of the InventoryIngredient(quantity, measurement_unit, expiry_date) model and also the name for the Category. I ask you if you can please help me with this, at least I would need a basis from which to implement my form. -
Django Template not loading the view inside another template
I am trying to include another template inside my home page as follows: {% if user.userorganisation.organisation %} {% include 'organisation_members.html' %} {% else %} {% include 'create_organisation.html' %} {% endif %} The create_organisation template is correctly loading its view so the step of checking the organisation of the user is correct. When I am trying to directly access the organisation_members.html url everything is working fine but when I am inside the home page where the include 'organisation_members.html' exists, only the static contents are being loaded. I have tried adding some prints for debugging and the view is not being called at all. Here is the view: def organisation_members(request): print("aaaaaa") try: print("aaaaaaaa") user_organisation = UserOrganisation.objects.get(user=request.user) print(user_organisation.organisation) organisation_users = UserOrganisation.objects.filter( organisation=user_organisation.organisation).select_related('user') print(organisation_users) context = { 'organisation_users': organisation_users, } return render(request, 'organisation_members.html', context) except UserOrganisation.DoesNotExist: return redirect('some_error_page') And here is the url: path('organisation_members/', views.organisation_members,name='organisation_members'), Why is the view not being called when including the html page? I know that the 'include' only includes the html but why is it that the create_organisation.html being called and the organisation_members not, when I am doing the same exact steps in both of them -
ByPass Django Basic Auth
I am trying to bypass django basic auth as I want to use firebase auth on Frontend and I am only getting the id_token on Backend. The Middleware is as follows: class FireBaseAuth(MiddlewareMixin): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): modified_request = self.process_request(request) response = self.get_response(modified_request) response = self.process_response(response) return response def process_request(self, request): middleware = "[FireBase Auth]" logger.info(f"{middleware} Request path: {request.path}") if request.path.rstrip('/').split('/')[-1] in EXCLUDE_AUTH_ENDPOINTS: logger.info( f"{middleware} Skipping auth check for: {request.path}") return request user = User.objects.filter(email='lahiwe@pelagius.net').first() request.user = user return request token = request.META.get("HTTP_FB_ACCESS_TOKEN") if not token: logger.info(f"{middleware} No token found") return HttpResponse("Unauthorized", status=status.HTTP_401_UNAUTHORIZED) # check if token is valid try: fb_user = auth.verify_id_token(token) if not fb_user: logger.info(f"{middleware} No info found against token") return HttpResponse("Unauthorized", status=status.HTTP_401_UNAUTHORIZED) if fb_user: # Fetch user Data fb_user = auth.get_user_by_email(fb_user['email']) if not fb_user.email_verified: logger.info(f"{middleware} User email not verified") return HttpResponse("User email not verified", status=status.HTTP_401_UNAUTHORIZED) logger.info( f"{middleware} Got user[{fb_user.email}] from firebase") # Check if user exists in current region user = User.objects.filter(email=fb_user.email).first() # Create user if not exists if not user: logger.info(f"{middleware} User not Found") return HttpResponse("User email not Found",status=status.HTTP_400_BAD_REQUEST) logger.info(f"{middleware} User Found. {user.id}") request.user = user setattr(request, 'user', user) logger.info(f"{middleware} Updated request user") return request except Exception as e: exec_type, exce_value, … -
How to fix MyPy [return-value] error when type is actually correct
I am using Django-Ninja + MyPy and I get this error that type it received tuple[int, dict[str, str]]" is not correct as it doesn't match one of the tuple[int, None] | tuple[int, DetailType] types but it is exactly as second type. Because in other parts of code it can figure out correctly it has "detail" as key. But as soon as I use Union[...] it somehow cannot look recursively? apps/users/views.py:106: error: Incompatible return value type (got "tuple[int, Message]", expected "tuple[int, None] | tuple[int, DetailType]") [return-value] This is how my types look like: DetailType = TypedDict("DetailType", {"detail": str}) MessageType = tuple[int, DetailType] NoContentType = tuple[int, None] And this is complete code where mypy is returning error: @post("me/password/change/", response={204: None, 401: Message}, url_name="users_me_password_change") def change_password(request: HttpRequest, data: ChangePasswordRequest) -> Union[NoContentType, MessageType]: <<< THIS IS RETURN TYPE user = request.user if not user.check_password(data.password): return 401, {"detail": "Password is incorrect."} <<< IN THIS LINE IS MYPY ERROR user.set_password(data.new_password) user.save() return 204, None -
i worked on the backend django framework. but i faced Django views.py import problem
I work on the django framework but when i open the urls.py file the views import did not work . kindly guide me . enter image description here kindly guide me about my problem so i continue next to it. kindly give a useful suggestion and solution about it. -
I think iam getting something wrong
recently i tried to setup my environment using miniconda so, i download python and django in my environment so, when is started my django project django-admin startproject myproject i got this error Unable to create process using 'C:\Users\Yoga 260.conda\envs\myenv\python.exe “C:\Users\Yoga 260.conda\envs\myenv\Scripts\django-admin-script.py” how i could solve the issue i tried to delete env and create new one but it didnt work also i started from scratch and deleted everything -
How to create alias for first active item in reverse relation in Django models?
I have a model called Item: class Item(models.Model): ... Also I have another model called Content. It has relation to Item and a ChoiceField to select is the content is active or not: class Content(models.Model): item = ForeignKey(Item related_name=) is_active = BooleanField(default=False) content = TextField() def save(self, *args, **kwargs): """There's a logic to make sure every item has only one content""" I have two questions. How to filter out the Items without any content or without any active content. Can I do something like alias to call item.content to return active content of the item without causing db performance issues. -
Translated Fields not Rendering Correctly in Django CMS Plugin
Am encountering an issue with rendering translated fields in a Django CMS plugin using django-modeltranslation. The plugin is supposed to display translated content based on the selected language, but it only renders with the default language. All other non-CMS plugin parts on the page that also make use of django-modeltranslation translate and are displayed correctly. Here's a brief overview of the setup: I'm using django==4.2.10; django-cms==4.1.0; along with django-modeltranslation==0.18.11 for model field translations. The plugin in question (HeaderPlugin) has a single field that is translated using django-modeltranslation. The template (cms_plugins/header/list_items.html) only includes {{ instance }}, but the translated fields are not appearing as expected when switching languages. {{ instance }} only displays the instance when the default language is selected. The plugin is used within {% static_alias 'header' %}. A noteworthy observation is that, when I want to set the plugin for a non-default language page via the menu dropdown Aliases..., it redirects to the default language (since the page does not exist). Hence I am only able to set the plugin from the default language. The plugin and associated model: #cms_plugins.py @plugin_pool.register_plugin class HeaderPlugin(CMSPluginBase): model = HeaderPlugin module = _("Header") name = _("Header Plugin") render_template = "cms_plugins/header/list_items.html" def render(self, … -
Using 'import_export' model in Django....If I export means it shows an badgateway in nginx
`I am using an import-export model in my Django admin panel it works very well...if the records goes more means on that time also i am export means it gives an error like Bad Gateway...if i click export it asks what format it wants like that then it takes too much of timing and gives an Bad Gateway.I don't Know why `class SongListAdmin(ImportExportModelAdmin): list_display = ('article_title','song_views','date_posted','date_updated','listview') search_fields=('article_title','Tags__tag_name') this is my code...In my SongList table having an record 16,000 if i click export from my admin panel means it goes an Bad Gateway....why If i export i need to 16,000 records but it does'nt comes the actual result it goes an an badgateway in nginx why`` -
Fastest way to redirect with refresh button?
I have an issue where after I've selected some products and filtered them I would like to refresh to the home page (in my case - series_list/) where it shows all products and their specifications but without the filters. Basically it should refresh to the home page immediately when I click on the refresh button from the browser. I tried using: if (performance.navigation.type === 1) { window.location.href = '/series_list/'; } However, it takes roughly 2-2.5 seconds for it redirect to the home page which is too slow. Here is the Django code for the products filters and specifications: {% for key, value in specification_list_fields %} <th> <a class="table-headers" href="?{% if order_by == key %}order_by={{ key }}_desc{% else %}order_by={{ key }}{% endif %}&{{ query_atrs_wo_order_by }}"> {{ value }} <i class="fa fa-fw fa-sort{% if order_by == key %}-up{% elif order_by == key|add:'_desc' %}-down{% else %}{% endif %}"></i> </a> </th> {% endfor %} Is it possible to redirect even quicker when pressing the refresh button? -
How to save products on my Django Ecommerce website
I am trying to implement a feature in my Django ecommerce website where a user can save a desired product after clicking on a button on the product detail page of said product - <div class="me-3 text-white" onclick="saveProduct({{ product.id }})"> <i class="bi bi-balloon-heart"></i> </div> This is my models.py - class UserActivity(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) timestamp = models.DateTimeField(default=timezone.now) saved = models.BooleanField(default=False) # a boolean field to track whether the product is saved by the user class Meta: ordering = ['-timestamp'] This is my ecommerce/views.py - @require_POST @login_required def save_product(request): if request.headers.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest': product_id = request.POST.get('product_id') product = get_object_or_404(Product, pk=product_id) # Check if the user has already saved the product user_activity, created = UserActivity.objects.get_or_create(user=request.user, product=product) if created: user_activity.saved = True user_activity.save() return JsonResponse({'status': 'success'}) else: return JsonResponse({'status': 'error', 'message': 'Product already saved'}, status=400) else: return JsonResponse({'status': 'error', 'message': 'Invalid request'}, status=400) this is my ecommerce/urls.py - app_name = 'ecommerce' path('save_product/', views.save_product, name='save_product'), This is my accounts/views.py for rendering the saved products - @login_required def saved_items(request): current_path = resolve(request.path_info).url_name saved_products = UserActivity.objects.filter(user=request.user, saved=True).select_related('product') return render(request, 'accounts/saved_items.html', {'current_path': current_path, 'saved_products': saved_products}) This is my saved_items.html for rendering saved products - {% for user_activity in saved_products %} <div class="border … -
What to do with ''attempted relative import with no known parent package'' in VS?
it is PS C:\storefront> & C:/Users/ANJALY/.virtualenvs/storefront-qOrq4PPp/Scripts/python.exe c:/storefront/playground/urls.py Traceback (most recent call last): File "c:\storefront\playground\urls.py", line 3, in from . import views ImportError: attempted relative import with no known parent package PS C:\storefront>. i tried to change it to subpackage. -
The button does not work with using the library library <django-formset>
I use the library "Django-formset". It seems that I did everything according to the instructions. The form filtering is triggered. But the button does not respond at all to pressing. There is speculation that this could be due to a label error in template (it comes from using the library). But most likely the reason is different. Models: class Brand(models.Model): name = models.CharField(max_length=100) class Car(models.Model): name = models.CharField(max_length=100) brand = models.ForeignKey('Brand', null=False, blank=False, on_delete=models.CASCADE) class Trip(models.Model): brand = models.ForeignKey('Brand', on_delete=models.CASCADE) car = models.ForeignKey('Car', on_delete=models.CASCADE) Form: from formset.utils import FormMixin class TripForm(FormMixin, forms.ModelForm): brand = forms.ModelChoiceField( label="Brand", queryset=Brand.objects.all(), widget=Selectize( search_lookup='name__icontains', placeholder="First, select Brand" ), required=True, ) car = forms.ModelChoiceField( label="Car", queryset=Car.objects.all(), widget=Selectize( search_lookup=['name__icontains'], filter_by={'brand': 'brand__id'}, placeholder="Then, select a Car" ), required=True, ) class Meta: model = Trip fields = ('brand', 'car') View: from django.views.generic import CreateView from formset.views import FormViewMixin, FormView class TripView(FormView, FormViewMixin, CreateView): model = Trip form_class = TripForm success_url = "" template_name = 'test.html' Template: {% load formsetify %} <head> <script type="module" src="{% static 'formset/js/django-formset.js' %}"></script> <script type="text/javascript" src="{% static 'js/jquery.js' %}"></script> </head> <body> <django-formset endpoint="{{ request.path }}" csrf-token="{{ csrf_token }}"> {% render_form form %} <button type="button" click="submit -> proceed">Submit</button> </django-formset> </body> -
Many to many field with extra fields in Django REST Framework
I have two models: Purchase and Product, in the Purchase model I have some fields and among them a many to many referencing the Product, but for each product inserted in the purchase I need to add a status field, price and quantity and I have no idea how I could do this. Later I need to change these fields and I also need to have the option of adding more products, changing a product or excluding it from the purchase. Purchase class Purchase(models.Model): id = models.UUIDField(primary_key=True, unique=True, default=uuid4, editable=False) created_at = models.DateTimeField(_("Created At"), default=timezone.now) request_date = models.DateField(_("Request Date"), default=date.today) obs = models.TextField(_("Observation")) status = models.CharField(_("Status"), choices=STATUS, default="Pending", max_length=8) products = models.ManyToManyField(Product, verbose_name=_("Products")) approval_date = models.DateField(_("Approval Date"), blank=True, null=True)` Product class Product(models.Model): id = models.UUIDField(primary_key=True, unique=True, default=uuid4, editable=False) code = models.CharField(_("Code"), max_length=30) un = models.CharField(_("Measurement Unit"), max_length=30) description = models.TextField(_("Description"))` I've tried to create a PurchaseProduct model but I couldn't make it work properly. PurchaseProduct class PurchaseProduct(models.Model): purchase = models.ForeignKey(Purchase, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.DecimalField(_("Quantity"), max_digits=10, decimal_places=2) price = models.DecimalField(_("Price"), max_digits=10, decimal_places=2) status = models.CharField(_("Status"), choices=STATUS, default="Pending", max_length=8)` -
Django: count how many related objects I have
I have the following unmanaged django models: class A(models.Model): # some fields here class Meta: app_label = "app" db_table = "table_A" managed = False and another one, which has a foreign key to the model A: class B(models.Model): # some fields here city = models.CharField() obj_a = models.ForeignKey(A, on_delete=models.RESTRICT, related_name="b_objects") class Meta: app_label = "app" db_table = "table B" managed = False I need to write an endpoint that would return information about A objects + some statistics on B objects related to a particular A object: total number of B objects for this A object number of B objects for this A object where city='city_1' number of B objects for this A object where city='city_2' (results of 2 and 3 will add up to 1) Here's what I got so far (haven't tried to work on 2 and 3 bullets, as the 1st one isn't working yet): class MyView(ListAPIView): serializer_class = MySerializer queryset = A.objects.prefetch_related("b_objects").annotate( total=Count("b_objects") ).all() I got an error saying 'Cannot resolve keyword 'b_objects' into field.' Here's MySerializer: class MySerializer(serializers.ModelSerializer): cryovials = BSerializer(many=True) class Meta: model = A fields = "__all__" I found this question Django count related objects but unfortunately it didn't help me. -
Django system check to warn for deprecated blocks in templates
I am maintaining a Django library that has some templates that users can extend. I want to remove some of the blocks in a couple major versions and I was wondering if it is possible to add a system check to warn users who use that block in their code that it is now deprecated. The official Django documentation for system checks does not mention templates or blocks at all and I am not sure if it is possible (and if so, how) -
Error while trying to create a school timetable, in Django, that is automatically filled with buttons on the correct time and week day
I am trying to create a Django school timetable that is automatically filled with buttons once its created. I spent a lot of time trying to come up with a way since im still not very experience in programming and very new to Django, but the way I tried to do it was with "for" loops, while using a nested dictionary on the views, but due to my lack of understanding and experience i cannot figure out where the error (VariableDoesNotExist at /timetable/ Failed lookup for key [end_time] in 'monday') is comming from. this is my models.py of the schedule table(some stuff is in portuguese): class Horario(models.Model): ID_Horario = models.BigAutoField(primary_key=True) ID_Sala = models.ForeignKey(Sala, on_delete=models.CASCADE) ID_Turma = models.ForeignKey(Turma, on_delete=models.CASCADE) ID_Professor = models.ForeignKey(Professor, on_delete=models.CASCADE) Hora_inicio = models.TimeField() Hora_fim = models.TimeField() Dia_semana = models.CharField(max_length=100) Disciplina = models.CharField(max_length=100) this is my views page(where i would guess I did something wrong): def timetable(request): horario_entries = Horario.objects.all() timetable_data = {} for entry in horario_entries: day_of_week = entry.Dia_semana subject = entry.Disciplina start_time = entry.Hora_inicio.strftime('%H:%M') end_time = entry.Hora_fim.strftime('%H:%M') timetable_data[day_of_week] = {} timetable_data[day_of_week][start_time] = {} timetable_data[day_of_week][start_time][end_time] = {} timetable_data[day_of_week][start_time][end_time][subject] = {'entries': []} # Append the entry to the 'entries' list timetable_data[day_of_week][start_time][end_time][subject]['entries'].append(entry) return render(request, 'testetimetable.html', {'timetable_data': timetable_data}) and finally this … -
Undefined Movie Name and City Name in Seats HTML Template Despite Passing Through JavaScript and URL in Django Application
this is my html code of shows.html {% for cinema_hall in cinema_halls %} <div> <h2>{{ cinema_hall.name }}</h2> <div class="show-container" id="show-container-{{ cinema_hall.id }}"> <!-- Loop through shows for each cinema hall --> {% for show in shows %} {% if show.cinemahall == cinema_hall %} <div class="show-box" data-cinema_hall_id="{{ cinema_hall.id }}" data-show_id="{{ show.id }}"> Show: {{ show.timings }} <br> ₹ {{ show.price }} </div> {% endif %} {% endfor %} </div> </div> {% endfor %} and this is its js code function filterShowsByDate(date) { const movieName = '{{ movie_name }}'; // Replace with actual movie name const city = '{{ request.GET.city }}'; // Replace with actual city name $.ajax({ url: `/shows/${movieName}/filter/${date}/?city=${city}`, type: 'GET', success: function(response) { // Clear existing show containers $('.show-container').empty(); // Loop through the filtered shows and display them response.shows.forEach(function(show) { const showBox = `<div class="show-box" data-show-id="${show.id}" data-cinema-hall-id="${show.cinemahall_id}">Show: ${show.timings} <br> ₹ ${ show.price } </div>`; $('#show-container-' + show.cinemahall_id).append(showBox); }); $('.show-box').click(function(event) { event.preventDefault(); // Prevent default behavior const showId = $(this).data('show-id'); const cinemaHallId = $(this).data('cinema-hall-id'); const movieName = $(this).data('movie-name'); const cityName = $(this).data('city-name'); // Redirect to seats page with appropriate parameters window.location.href = `/seats/?show_id=${showId}&cinema_hall_id=${cinemaHallId}&movie_name=${encodeURIComponent(movieName)}&city_name=${encodeURIComponent(cityName)}`; }); }, error: function(xhr, errmsg, err) { console.log(errmsg); } }); } and this is views.py def filter_shows_by_date(request, movie_name, … -
Sorting Objects By Biggest Attribute Value Django
I am creating an application which will record Athletics events and points. Eventually I want to show on the screen the HOUSES (teams), points, and their overall position. The team with the highest number of points will be number one etc... My model has a field points which will be updated as results are recorded. I want the model to auto-determine he position of the team based off of the other objects' points. How can I achieve this? Here is my code: models.py class House(models.Model): name = models.CharField(max_length=255) points = models.FloatField(default=0, null=False) house_color = models.CharField(max_length=10, null=False, blank=False, default='red') position = models.IntegerField(default=4) def determine_position(self): all_houses_queryset = self.objects.all() I've tried to get the index of an ordered queryset on the template but it threw a Value error. Views.py def dashboard(request): ordered_houses = House.objects.all().order_by('-points').values() context = { 'houses': ordered_houses, 'range': [1,2,3,4], } return render(request, 'core/index.html', context) index.html {% for index, house in houses %} -
How to send (or upload ) images from flutter app to Django server and vice versa?
I want just the big picture on how to upload an image from a flutter app (.jpg or .png formats) to a Django server in order to classify the image and return a response, also how to send an from the server when the user in flutter app make a get request (I want just guidelines). I didn't tried yet because I don't know from where to start. -
Django SessionAuthentication 'Authentication credentials were not provided'
I'm using DRF for backend and React for frontend. I'm trying to get user Information after logged in. However, I got 403 'Authentication credentials were not provided' when sending get method to get the Information. The authentication method is SessionAuthentication. Here is the UserView which I got 403. class UserView(APIView): permission_classes = (permissions.IsAuthenticated, ) authentication_classes = (SessionAuthentication, ) def get(self, request): return Response(request.session['user_id'], status=status.HTTP_200_OK) I thought the user is authenticated after logged in. Is there anything I need to do before sending this request? In the response of login request, there is a sessionid. I checked that I set REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', ), } Also, I added below to the settings.py CORS_ALLOW_CREDENTIALS = True SESSION_COOKIE_SAMESITE = 'None' CORS_ALLOW_ALL_ORIGINS = False Here is the login class. class UserLogin(APIView): permission_classes = (permissions.AllowAny, ) authentication_classes = (SessionAuthentication, ) def post(self, request): data = request.data assert validate_email(data) assert validate_password(data) serializer = UserLoginSerializer(data=data) if serializer.is_valid(raise_exception=True): user = serializer.check_user(data) login(request, user) request.session['user_id'] = user.user_id return Response(serializer.data, status=status.HTTP_200_OK) -
Dockerized Django-React-PostgreSQL App Not Serving Frontend Despite Successful Build and Container Rebuild
I have a Dockerized application setup that includes a React frontend and a Django backend service. Despite successfully building the Docker container and ensuring the backend is running as expected, when I attempt to access the frontend, I'm met with the following message: 'This URL is only accessible after you've built the React frontend.' I've attempted to rebuild the Docker container from scratch to ensure there are no caching issues, but the problem persists. Environment: Operating System: Win10 -- Using Ubuntu through WSL for building the container Docker Version: Docker version 25.0.3, build 4debf41 Node Version: 10.5.0 Steps Taken: Rebuilding the Docker Container: I used the command docker build --no-cache -t mycontainer:latest . to ensure a fresh build without using any cached layers. Running the Container: After rebuilding, I ran the container using docker run -d -p 8000:80 --name mycontainer mycontainer:latest. Verifying Backend Functionality: I can confirm the backend services are running as expected, responding to API calls. Dockerfile: # Stage 0: Build React Frontend FROM node:16 AS build-frontend WORKDIR /app/frontend COPY frontend/package\*.json ./ RUN npm install COPY frontend/ . RUN npm run build # Stage 1: Build Django Application FROM tiangolo/uwsgi-nginx:python3.9 # Set environment variables ENV PYTHONDONTWRITEBYTECODE=1 \ PYTHONUNBUFFERED=1 … -
Django Reuse Model Serializers Custom Validators
I have below serializer.py file. I have validate_semester() present in SubjectSerializer(), I want to reuse the same method in my StudentSerializer() class. Any help is appreciated. validate_semester() is verifying that semester id exists in semester table before assigning it to Student or Subject object. from rest_framework import serializers from .models import * from .helpers import SEMESTER_NOT_STORED class SemesterSerializer(serializers.Serializer): id = serializers.IntegerField(required=False) name = serializers.CharField(max_length=100, required=False) class SubjectSerializer(serializers.ModelSerializer): semester = SemesterSerializer() class Meta: model = Subject fields = ["id", "name", "code", "semester"] def create(self, validated_data): semester = validated_data.pop("semester") serializer = SemesterSerializer(semester) subject = Subject.objects.create( semester_id=serializer.data["id"], **validated_data ) return subject def validate_semester(self, value): id = value.get("id") semesters = list(Semester.objects.all().values_list("id", flat=True)) if id not in semesters: raise serializers.ValidationError({"id":[SEMESTER_NOT_STORED.format(id)]}) return value class SemesterSubjectSerializer(serializers.ModelSerializer): subjects = SubjectSerializer(many=True, read_only=True) class Meta: model = Semester fields = ["id", "name", "subjects"] class StudentSerializer(serializers.ModelSerializer): semester = SemesterSerializer() class Meta: model = Student fields = ["id", "name", "email", "semester"] def create(self, validated_data): semester = validated_data.pop("semester") serializer = SemesterSerializer(semester) student = Student.objects.create( id=None, semester_id=serializer.data["id"], **validated_data ) return student I have try adding validation at model level as well, it doesn't seem to be working out. I am getting IntegrityError anyways. from django.core.validators import MinLengthValidator, MaxLengthValidator from .helpers import SEMESTER_NOT_STORED def validate_semester(id): … -
Celery AppRegistryNotReady: Apps aren't loaded yet when using Django with Celery
I'm encountering an issue with Celery and Django where I receive an "AppRegistryNotReady" exception, stating that "Apps aren't loaded yet." This occurs when attempting to run Celery with the beat scheduler. Here are the key details: - I'm using Django with Celery for background task processing. - When trying to start the Celery beat scheduler using the command: celery -A myproject beat -l info I encounter the following traceback: Traceback (most recent call last): ... raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. - The issue seems related to Django settings or app loading during Celery initialization. This is my code celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE','myproject.settings') app = Celery('myproject') app.conf.enable_utc = False app.conf.update(timezone = 'Asia/Kolkata') app.config_from_object(settings, namespace = 'CELERY') # celery beat settings app.conf.beat_schedule ={ } app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') settings.py CELERY_BROKER_URL = 'redis://127.0.0.1:6379/0' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE ='Asia/Kolkata' CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' CELERY_RESULT_BACKEND = 'django-db' from myapp.models import Client,ImportSettings task_intervals = ImportSettings.objects.all() CELERY_BEAT_SCHEDULE = {} for task_interval in task_intervals: interval_seconds = task_interval.check_frequency_minutes client_id = task_interval.client CELERY_BEAT_SCHEDULE[f'import-{client_id}'] = { 'task': 'myapp.tasks.process_csv_files', 'schedule': interval_seconds, 'args': ( 'directory_path', 'table1', 'table2' ) … -
Gunicorn Worker Fails to Boot on Azure Web App Linux - ModuleNotFoundError
I am facing an issue with deploying a Django application on Azure Web App Linux using Gunicorn. The deployment process appears to be successful, but the Gunicorn worker fails to boot with the following error: [2024-03-07 04:42:30 +0000] [71] [ERROR] Exception in worker process ... ModuleNotFoundError: No module named 'csvvalidator.validator.wsgi' ... This is my YAML file: trigger: - main pool: vmImage: 'ubuntu-latest' steps: - task: UsePythonVersion@0 inputs: versionSpec: '3.10' addToPath: true - script: | python -m venv /home/site/wwwroot/antenv source /home/site/wwwroot/antenv/bin/activate pip install -r requirements.txt displayName: 'Install dependencies' - task: ArchiveFiles@2 inputs: rootFolderOrFile: '$(Build.Repository.LocalPath)' includeRootFolder: false archiveType: 'zip' archiveFile: '$(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip' replaceExistingArchive: true - task: PublishBuildArtifacts@1 inputs: pathtoPublish: '$(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip' artifactName: 'drop' publishLocation: 'Container' - task: DownloadBuildArtifacts@0 inputs: buildType: 'current' downloadType: 'single' artifactName: 'drop' downloadPath: '$(System.ArtifactStagingDirectory)' - task: AzureRmWebAppDeployment@4 inputs: ConnectionType: 'AzureRM' azureSubscription: 'Subscription' appType: 'webAppLinux' WebAppName: 'safe-lives-copilot-dev' packageForLinux: '$(System.ArtifactStagingDirectory)/**/*.zip' RuntimeStack: 'PYTHON|3.10' StartupCommand: 'gunicorn -b :8000 csvvalidator.validator.wsgi:application' The virtual environment is created during deployment, but there is a warning indicating that it couldn't find the virtual environment directory. 2024-03-07T04:42:30 WARNING: Could not find virtual environment directory /home/site/wwwroot/antenv. 2024-03-07T04:42:30 WARNING: Could not find package directory /home/site/wwwroot/__oryx_packages__. Any guidance or insights on resolving this Gunicorn worker boot failure would be highly appreciated.