Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Autocomplete dropdown for related-field filtering in Django admin
I'd like to have a nice autocomplete dropdown in my Django admin backend for filtering out results in the project model according to the subject attached to a person. this is my models.py: class Person(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE, blank=True, null=True) class PersonRole(models.Model): project = models.ForeignKey('Project', on_delete=models.CASCADE) class Project(models.Model): person = models.ManyToManyField(Person, through=PersonRole) For now I managed to get a simple list using SimpleListFilter with the following code in admin.py: class PISubjectFilter(admin.SimpleListFilter): title = 'PI Subject' parameter_name = 'subject' def lookups(self, request, model_admin): return Subject.objects.values_list("id", "name").order_by("id") def queryset(self, request, queryset): count = range(1, 100) for x in count: if self.value() == str(x): return queryset.filter( person__personrole__person__subject=x ).distinct() break How can I turn this long list into a autocomplete dropdown? I've almost achieved what I want by specifying a custom template for my form in admin.py with template = "custom_form.html", with something like the below: {% load i18n %} {% load static %} <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" /> <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script> <details data-filter-title="{{ title }}" open> <summary> {% blocktranslate with filter_title=title %} By {{ filter_title }} {% endblocktranslate %} </summary> <select id='select_subject' onchange="location = this.value;"> {% for choice in choices %} <option value="{{ choice.query_string|iriencode }}">{{choice.display}}</option> {% endfor %} </select> </details> … -
Using FormSet to editing a array of same form in django
My requirement to enable user to add description and remark against multiple files uploaded earlier.I am using formset to display a set of partial field data from a model 'medical_doc'. I am new to django and am not able to implement it properly. form.py class Files_uploadedForm(forms.Form) doc_name=forms.CharField(max_length=100) doc_type=forms.CharField(max_length=5) description=forms.CharField(max_length=100) remarks=forms.CharField(max_length=100) Files_uploadedFormSet=formset_factory(Files_uploadedForm) view.py if request.method='POST' med_qrset=medical_doc.objects.values('doc_name','doc_type','description','remarks') .filter(doc_id=doc_id) formset=Files_uploadedFormSet(queryset=med_qrset) context = {'formset'=formset} return render(request,"upload_doc.html") upload_doc.html ... {% for form in formset %} form.as_p {% endfor %} Please excuse the syntax errors.My issue here is to know it this method of initialising formset is correct. Because I get a error saying that BaseFormSet.init() got an unexpected keyword argument 'queryset'. Please help. -
Django post request is good in postman but not from frontend with the same payload
Django api interface and postman is working fine in posting the payload, however with the exact same payload posted from my frontend it doesn't work even while disabling cors. -This is my mode: `class Activity(models.Model): cid = models.CharField(max_length=10) percent = models.IntegerField() name = models.CharField(max_length=255)` -this is my view: class ActivityViewSet(viewsets.ModelViewSet): queryset = Activity.objects.all() serializer_class = ActivitySerializer def get_queryset(self): queryset = self.queryset # Start with the base queryset # Get the cid from the query parameters cid = self.request.query_params.get('cid') # If cid is provided in the query parameters, filter the queryset if cid: queryset = queryset.filter(cid=cid) return queryset -this is my url: `router.register(r'activities', ActivityViewSet)` And this is my frontend code: \` const postOutcomesAsync = async () =\> { function getCSRFToken() { const csrfCookie = document.cookie.match(/csrftoken=(\[\\w-\]+)/); if (csrfCookie) { return csrfCookie\[1\]; } return null; } const csrfToken = getCSRFToken(); axios.post('http://127.0.0.1:8000/activities/', inputValues[2], { headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrfToken } }); console.log('All activities posted successfully'); } \` The backend log shows OPTIONS 200 ok and no posting at all. Network tab shows post request failed but OPTIONS 200 ok. Axios shows network error 500. -
Vue 3 mutation is not reflected on Django backend
In my blog app, I want to like, dislikes and share posts using Vue 3 composition API. I provided Mutation class in schema.py and UpdatePostCounts Vue component. But for some odd reason the mutation is not showing on the Django backend database in Django Admin interface. How can I resolve this? Also how can I embed the likes, dislikes, and shares as I use SocialMedia.vue buttons? Schema.py: import graphene from django.contrib.auth import get_user_model from graphene_django import DjangoObjectType from blog import models class UserType(DjangoObjectType): class Meta: model = get_user_model() class AuthorType(DjangoObjectType): class Meta: model = models.Profile class TagType(DjangoObjectType): class Meta: model = models.Tag class PostType(DjangoObjectType): class Meta: model = models.Post class Query(graphene.ObjectType): all_posts = graphene.List(PostType) author_by_username = graphene.Field(AuthorType, username=graphene.String()) post_by_slug = graphene.Field(PostType, slug=graphene.String()) posts_by_author = graphene.List(PostType, username=graphene.String()) posts_by_tag = graphene.List(PostType, tag=graphene.String()) def resolve_all_posts(root, info): return ( models.Post.objects.prefetch_related("tags") .select_related("author") .all() ) def resolve_author_by_username(root, info, username): return models.Profile.objects.select_related("user").get( user__username=username ) def resolve_post_by_slug(root, info, slug): return ( models.Post.objects.prefetch_related("tags") .select_related("author") .get(slug=slug) ) def resolve_posts_by_author(root, info, username): return ( models.Post.objects.prefetch_related("tags") .select_related("author") .filter(author__user__username=username) ) def resolve_posts_by_tag(root, info, tag): return ( models.Post.objects.prefetch_related("tags") .select_related("author") .filter(tags__name__iexact=tag) ) class Mutation(graphene.ObjectType): like_post = graphene.Field(PostType, id=graphene.ID()) dislike_post = graphene.Field(PostType, id=graphene.ID()) share_post = graphene.Field(PostType, id=graphene.ID()) def resolve_like_post(self, info, id): post = models.Post.objects.get(pk=id) post.likes += … -
Image Creation via nested serializer field
MODELS: class Product(models.Model): uuid = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) slug = AutoSlugField(populate_from = 'name', unique=True) shop = models.ForeignKey(Shop, on_delete=models.CASCADE) name = models.CharField(max_length=255) description = models.TextField(blank=True, null= True) product_profile_image = VersatileImageField(blank=True, null= True, upload_to= 'images/product_profile') price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) def __str__(self): return self.name class Image(models.Model): uuid = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) product = models.ForeignKey(Product, on_delete=models.CASCADE) image = VersatileImageField(blank=True, null= True, upload_to='images/') def __str__(self): return f"image of {self.product.name}" SERIALIZERS: class ImageSerializer(DynamicFieldsModelSerializer): class Meta: model = Image fields = ['uuid','image'] class ListCreateProductSerializer(DynamicFieldsModelSerializer): images = ImageSerializer(many= True, required=False, source='image_set') class Meta: model = Product fields = ['uuid', 'name', 'description', 'price', 'product_profile_image', 'quantity', 'images'] def create(self, validated_data): images = validated_data.pop('images', []) product = Product.objects.create(**validated_data) for image in images: Image.objects.create(product=product, image=image) return product VIEWS: class ListCreateProductView(ListCreateAPIView): serializer_class = ListCreateProductSerializer permission_classes = [ShopPermission] def get_queryset(self): shop_uuid = self.kwargs.get('shop_uuid') shop = get_object_or_404(Shop, uuid=shop_uuid) products = Product.objects.filter(shop=shop) if not products: raise NotFound(detail="This shop does not have any products") return products def perform_create(self, serializer): shop_uuid= self.kwargs.get('shop_uuid') shop = get_object_or_404(Shop, uuid=shop_uuid) product = serializer.save(shop=shop) return product When I upload images in POSTMAN, no new images are being created or associated with the new product instance. Please Help I tried this # images = serializers.ListField(child=serializers.ImageField(), required=False, write_only= True) that worked, but … -
Ways to intercept error responses in Django and DRF
The problem: Django errors are values to details keys. Django Rest Framework (DRF) errors are values to detail keys. Therefore, having an application that raises both Django and DRF exceptions is inconsistent by default. I want a way to change the response errors so that they look like this: { "message": ..., "code": ... } Are there ways to handle both Django and DRF exceptions at the same time and respond with a custom response body? I have tried: custom exception handler in DRF, but this only handles DRF exceptions custom error messages when defining models email = models.EmailField(error_messages={"required": {"message": "", "code": 123}}) but Django can't handle a dictionary as a message Adding a DRF validator to my serializer: email = serializers.EmailField( validators=[ UniqueValidator( queryset=models.User.objects.all(), message={ "message": "a user with this email already exists", "code": status.EMAIL_EXISTS, }, ) ], ) but this does not override the response body, but instead it embeds the message as an error message to the {"details": {"message": {<embedded dictionary>}}} The only thing I believe would work, is to try-except all exceptions inside my Views, but I would like to know if there is a prettier way than placing all my Views inside try blocks. -
How to add a duplicate column to a table?
I am retrieving data from the database using Django ORM: ws = Ws.objects.all() ws = ws.filter(*q_objects, **filter_kwargs) ws = ws.order_by(*sort_list) ws = ws.annotate(created_unix=UnixTimestamp(F('created')), date_unix=UnixTimestamp(F('date'))))) total_sum = ws.aggregate(total=Sum('ts_time', output_field=DecimalField()))['total'])['total'] LIST_FIELDS[1], LIST_FIELDS[2] = 'created_unix', 'date_unix' return JsonResponse({'table_data': list(ws.values_list(*LIST_FIELDS)), 'summ_time': total_sum}, safe=False) ``` I need to add a new column to LIST_FIELDS, one that is True for every pair of rows that have multiple fields matching or False For example: For LIST_FIELDS[0] and LIST_FIELDS[2] LIST_FIELDS[0] LIST_FIELDS[1] LIST_FIELDS[2] LIST_FIELDS[3] 1 1 3 True 1 1 2 True 2 1 1 False 1 1 2 True 1 1 3 True I try ask GPT4, but T9 is stubbornly giving me match=Case( When(field1=F('field2'), then=Value(True)), default=Value(False), output_field=BooleanField() ) ) But it's like comparing field1 == field2 IN ONE row And I need True, if row1[field1] == row2[field1] and row1[field2] == row2[field2] -
I want to create a Django Apllication for a french compnay but using 'iso-8859-1' encoding not UTF-8 how i can do that?
I have added these 2 lines in settings file of the Django App: FILE_CHARSET = 'iso-8859-1' DEFAULT_CHARSET = 'iso-8859-1' and in html page that i want to render it I specified the encoding but i always got error UnicodeEncodeError: 'latin-1' codec can't encode character '\u2019' in position 9348: ordinal not in range(256) because of the name 'système' in the line English: système load is very high of my html template how i can resolve it? -
while working on vs code using django framework faced error
used python manage.py instead got this error. C:\Users\AppData\Local\Programs\Python\Python312\python.exe: can't open file 'C:\ i was expecting to get a file db.sqlt.3 file and a link to a host site. What to do and how to fix this -
Unable to Save UserModel Data to Database Using Django Form
Problem: I'm encountering issues with my Django registration form where user data isn't being saved to the database. Details: I have implemented a Django registration form. My Django project includes a registration view and template. JavaScript modals are utilized for displaying the registration template. The UserModel is employed to handle user data. Despite inputting data into the registration form, user information isn't being saved to the database. Code: Base Page which contains modals: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="{% static 'styles.css' %}"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script> <!-- JavaScript for modals --> <script> // Function to show login modal // Function to show login modal function showLoginModal() { document.getElementById('login-modal').style.display = 'block'; document.getElementById('logout-modal').style.display = 'none'; // Hide logout modal document.getElementById('main-content').style.filter = 'blur(5px)'; } // Function to show logout modal function showLogoutModal() { document.getElementById('logout-modal').style.display = 'block'; document.getElementById('login-modal').style.display = 'none'; // Hide logout modal document.getElementById('main-content').style.filter = 'blur(5px)'; } // Function to show register modal function showRegisterModal() { document.getElementById('register-modal').style.display = 'block'; document.getElementById('main-content').style.filter = 'blur(5px)'; } // Function to hide modals function hideModals() { document.getElementById('login-modal').style.display = 'none'; document.getElementById('register-modal').style.display = 'none'; document.getElementById('logout-modal').style.display = 'none'; document.getElementById('main-content').style.filter = 'none'; // Remove … -
IntegrityError at /createad/ (1048, "Column 'user_id' cannot be null") in Django
I'm making a comic book resale site in django. There is an Ad model that allows you to create an ad for the sale. It has a user (Django User) foreign key. models.py class Ad(models.Model): ad_id = models.AutoField(primary_key=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=50, null=False, blank=False) description = models.TextField(null=True, blank=True) forms.py class AdForm(forms.ModelForm): class Meta: model = Ad fields = ('title', 'description', 'publisher', 'author', 'pub_year', 'pub_type', 'price') views.py def create_ad(request): if request.method == 'POST': form = AdForm(request.POST) if form.is_valid(): form.save(commit=False) current_user = request.user form.user = current_user form.save() else: form = AdForm() return render(request, 'create_ad.html', {'form': form}) When I try to save the ad I get the following error: **IntegrityError at /createad/ (1048, "Column 'user_id' cannot be null")** I tried inserting via request.user and request.user.id, but it doesn't help. Please help me to solve this problem. -
Trouble Integrating `django-simple-history` with `django-modeltranslation` in Abstract Model
I'm working on a Django project where I'm trying to create an abstract model that provides subclassed models with history tracking using the django-simple-history package. Additionally, I need to integrate django-modeltranslation for translating certain fields. However, I'm encountering issues with the integration. Here's my BaseModel code: from uuid import uuid4 from django.db import models from simple_history.models import HistoricalRecords class BaseModel(models.Model): class Meta: abstract = True history = HistoricalRecords(inherit=True) id = models.UUIDField(primary_key=True, default=uuid4, editable=False) created_at = models.DateTimeField(null=True, blank=True, auto_now_add=True) updated_at = models.DateTimeField(null=True, blank=True, auto_now=True) Now, I have a model TestModel that inherits from BaseModel: models.py class TestModel(BaseModel): text = models.CharField(max_length=100) un = models.IntegerField() new_text = models.CharField(max_length=100) And for translating fields in TestModel, I have the following translation setup: translation.py from modeltranslation.translator import register, TranslationOptions from test_app.models import TestDeleteModel @register(TestModel) class TestModelTranslationOptions(TranslationOptions): fields = ( 'text', 'new_text', ) However, the issue arises when django-simple-history doesn't recognize the translated fields like text_en, resulting in them not being added to the history model. It seems that this occurs because the translation fields are added after the simple history package registers the model and creates the history model. I attempted to register TestModel again with simple_history after the translation registration to address this: translation.py from … -
How to iterate a dict within a template that contains a key named items?
I have some fairly simple django template and part of it is iterating through some dict ( that originates from some parsed json files ) like: {% for k, v in d.items %} However my dict now contains an item called items, which because for the syntax of a.b django first tries to resolve it as a[b] before trying getattr(a,b) (and calling the result if its callable), will try to iterate through the value under that key instead of the dict. What would be a good way to resolve that? I know already I could write a filter that simply returns list(d.items()) but that seems wrong/wasteful to me. Are there some other possibilities to solve this problem? -
How to use websockets in drf project with react-frontend?
How to work with websockets in a split (backend/frontend) project? In a full Django project, I did it like this (1st answer): Dynamic updates in real time to a django template Now, the frontend is separate on React and the backend is on DRF. The frontend will be using socketio. How, in this case, should websockets be properly implemented in DRF? Should I still use channels? I thought that it could be done similar to the answer on Stack Overflow, where now the frontend is done in React instead of Django templates. But the frontend mentioned that endpoints are not needed, just events: For example, he will have something like socket.on("getTasks") and socket.on("addTask", task: {"new task"}). And I have no idea how to work with this All I've tried is the way from stackoverflow. -
Patch or update by search query axios
I have django restframework and control from javascript axios What I am doing is like this, axios.get(`http://localhost:8010/api/myusers/?my_id=${my_id}`).then((res)=>{ var id = res['data']['results'][0]['id']; axios.patch(`http://localhost:8010/api/myusers/${id}/`, { phone: 'nice phone', }).then((res)=>{ console.log("patch finish"); }) }) Fetch the id by my_id and patch the data. However I think it is a bit clumsy, it uses twice request. At first get the id by my_id and change data by id So, I would like to do this by one request. How can I make it ? I tried like this but 405 Method not allowd error axios.patch(`http://localhost:8010/api/myusers/?my_id=${my_id}`, { phone: 'nice phone2', }).then((res)=>{ console.log("patch finish"); }) -
Django RawSQL annotate field
How can i annotate field with RawSQL? sql_query = """ SELECT c.id, COALESCE(SUM((cm.temp_min + cm.temp_max) / 2 - %s), 0) AS gdd FROM agriculture_commune c LEFT JOIN agriculture_communemeteo cm ON c.id = cm.commune_id WHERE cm.date BETWEEN %s AND %s GROUP BY c.id """ communes = communes.raw(sql_query, [TBASE, start_date, end_date]) it working , if i try do like this communes.annotate(gdd=RawSQL(sql_query, [TBASE, start_date, end_date])) i got error "subquery must return only one column\nLINE 1: ...mmune" -
django-admin: The term 'django-admin' i
django-admin: The term 'django-admin' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Sanskar\Desktop\django> i want to initialize django -
How can I persist Django session after a POST request?
I want to be upfront with you the project I'm working with is kind of a mess, so I'm just looking for solutions. I have a Django app (no DRF) and a CI4 app. I want authentication to persist across the two apps. Basically, the CI4 app is the main, and that's where the user authenticates. I want to use request. Session in the Django app to handle the authentication state. I made the CI4 app sends a POST request to the Django app, and create a request. Session upon a successful authentication. @csrf_exempt def login_view_endpoint(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = Utilisateur.checkuser(username, password) if user: if 'utilisateur' not in request.session: request.session['utilisateur'] = user.id print(request.session['utilisateur']) return HttpResponse('true') else: return HttpResponse('false') else: # If the request method is not POST, redirect to the login page return HttpResponse('false') But the issue is when I test the flow of what I had in mind, I get redirected to the "login_page" of my Django app (which I'm trying to remove), which means the session doesn't exist, but the authentication was a success because I got a true response in my CI4 app. Maybe my understanding of session is … -
Python Execution Script manager with Web Interface?
So I have a Python Django project which uses Celery as well as Flower To launch all the three processes I need to start them on three different terminals with the commands: python manage.py runserver 0.0.0.0:8080 celery -A Lab worker -l info --concurrency 3 celery --broker=redis://172.20.1.2:6379/0 flower --port=5566 I was looking for a simpler solution, some sort of graphic interface where I have all these three commands already registered and I have just to click "launch". If I want to kill the process, maybe a "stop" button would be cool as well I'm looking something like Portainer is for Docker I've seen Spotify has created something for amnage Python scripts called Luigi, but I'm not sure if it fits my needs -
Implementing Internationalization (i18n) in Django
How can I effectively utilize internationalization (i18n) in Django Metronic to make my web application accessible in multiple languages? I'm struggling to implement i18n in my Django project with the Metronic theme. Despite configuring settings and marking strings for translation, I'm facing issues with translations not reflecting correctly and language switching not working as expected. -
when ever i try to login using phone number,password and otp its keep rendering the ph number page or it throws an error
``from django.shortcuts import render, redirect from django.contrib.auth import authenticate ,login from .models import Profile from django.contrib.auth.models import User from .mixins import MessageHandler import random def Signup_page(request): if request.method == "POST": username = request.POST.get('username') email = request.POST.get('email') phone_number = request.POST.get('phone_number') password = request.POST.get('password') if User.objects.filter(email=email).exists(): return render(request, "sign_up.html", {'error': 'Email already in use'}) if Profile.objects.filter(phone_number=phone_number).exists(): return render(request, "sign_up.html", {'error': 'Phone number already in use'}) user = User.objects.create_user(username=username, email=email) user.set_password( password) user.save() profile = Profile.objects.create(user=user, phone_number=phone_number) profile.save() return redirect('/login/') return render(request, "sign_up.html") def Login_page(request): if request.method == "POST": phone_number = request.POST.get('phone_number') try: profile = Profile.objects.get(phone_number=phone_number) return redirect('/password/') except Profile.DoesNotExist: return render(request, "login.html", {'error': 'Phone number not found'}) return render(request, "login.html") def password_page(request): if request.method == "POST": password = request.POST.get('password') phone_number = request.POST.get('phone_number') user = Profile. objects.get(phone_number = phone_number, password = password) profile = Profile.objeects(user=user) if user is not None: profile.otp = random.randint(100000, 999999) profile.save() messagehandler = MessageHandler(profile.phone_number, profile.otp).send_otp_on_phone() return redirect(f'/otp/<uid>/{profile.uid}') else: print('password check failed') print("Rendering password.html") return render(request, 'password.html') def Otp_page(request , uid): if request.method == "POST": otp = request.POST.get('otp') profile = Profile.objects.get(uid=uid) if otp == profile.otp: login(request,profile.user) return redirect('/dashboard/') def Dashboard_page(request): return render(request, "dashboard.html") ` i want it can go the otp page and send the otp` -
Efficient way to process data for number of views with dates
I am looking for a more efficient way to implement the provided code, which retrieves the number of views for object within a date range (start_date and end_date). The current code achieves the expected result, transforming data into a dictionary structure with names and corresponding daily view counts. However, I believe there might be a more optimized approach. Here's the code snippet for reference: models.py class Ad(models.Model): ad_type = models.ForeignKey(to=AdType, on_delete=models.CASCADE, related_name="ad") name = models.CharField(max_length=256) image = models.ImageField(upload_to="ads") is_active = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) class AdStat(models.Model): class StatType(models.TextChoices): VIEWS = "views", _("Views") CLICKS = "clicks", _("Clicks") ad = models.ForeignKey(to=Ad, on_delete=models.CASCADE, related_name="ad_stat") stat_type = models.CharField(max_length=10, choices=StatType.choices) created_at = models.DateTimeField(auto_now_add=True) views.py @staff_member_required def ads_number_of_views(request): start_date = request.GET.get("start_date") end_date = request.GET.get("end_date") ads = ( AdStat.objects.filter(ad__is_active=True, ad__ad_type__slug="desktop-hader") .select_related("ad") .values("ad__name", "created_at__date") .annotate(view_count=Count("id")) .order_by("created_at__date") ) if start_date and end_date: ads = ads.filter(created_at__gte=start_date, created_at__lte=end_date) elif start_date: ads = ads.filter(created_at__gte=start_date) elif end_date: ads = ads.filter(created_at__lte=end_date) ads_data = [] for item in ads: ad_name = item["ad__name"] date_str = str(item["created_at__date"]) count = item["view_count"] found = False for entry in ads_data: if entry["name"] == ad_name: entry["number_of_views"].append({"created_at": date_str, "count": count}) found = True break if not found: ads_data.append({"name": ad_name, "number_of_views": [{"created_at": date_str, "count": count}]}) return JsonResponse(ads, safe=False) Expected Output. The code successfully … -
cannot find django module
so im watching a tutorial in django, on my end i created a virtual environment but the python file cant seem to find the django modules, steps i did: open folder Django created virtual environment djangocrudenv activated the environment then pip installed the requirements.txt then followed the tutorial but as you can see in the attached picture it cant find the django module -
Hello folks. i am a fresher ..Currently learning Django basics . i got a error like this .Could you please resolve this 'template loader postmortem
i got a error like this .Could you please resolve this 'template loader postmortem', I also double checked the path for template in settings.py also . but still i could not able to resolve this ..?enter image description here Could you please anyone solve this issue.. -
Caching issue in Celery
I have a scheduled task that runs every 2 days to send reminders to people who haven't read and acknowledged documents on the system. The function works fine when I run it on the shell and all the results are correct. But when celery runs the task it gives (what I believe) cahced results. Meaning that a user has acknowledged the document but the system still sends him reminders about the document. below is my task: @shared_task(bind=True, autoretry_for=(Exception,), retry_backoff=5, retry_kwargs={'max_retries': 5}) def acknowledgment_reminder(self): customers = Customer.objects.filter(is_deleted=False) for customer in customers: log.info(customer.full_name) not_accepted = customer.not_accepted.filter(document__is_deleted=False, document__section__isnull=False) log.info(not_accepted.count()) if not not_accepted: continue customer.send_email(email_type='not_accepted', not_accepted=not_accepted)