Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use autocomplete filter in Django admin back-end for integer / dates / string fields
Is it possible to use an autocompelte filter class to be used in the list_filter for normal fields (i.e. not foreign keys or other relations)? For example, for this model: class Project(models.Model): project_number = models.DecimalField(max_digits=15, decimal_places=0, blank=True, null=True) I'd like to have an autocomplete filter in my admin back-end for the project_number field. Would [admin_auto_filters][1] be able to do that? -
Integrating a fine-tuned model into my Django-React application issue
I have a feature where the user can log what they’ve eaten for meal and the food data would get passed into to a fine-tuned model on OpenAI I created and the model would feedback to the user the impact it would have on their sugar levels and well-being. After having trained the model using the jsonl file which successfully completed and tested it in the playground. When I include the code in my views.py and test it, i get a 200 response in the terminal, but on the UI its saying “Sorry, I couldn’t provide a response. Please try again.”. Any help here would be much appreciated to help me fix this issue. On the frontend, the user enters what they had for breakfast for example, fish and chips, and the model would produce an output like shown on the second image. Dietary habits UI user enters their food `const DietaryHabits = () => { const [selectedDate, setSelectedDate] = useState(new Date()); const [open, setOpen] = useState(false); const [currentMeal, setCurrentMeal] = useState(''); const [foodEntry, setFoodEntry] = useState(''); const [entries, setEntries] = useState({ Breakfast: '', Lunch: '', Dinner: '', Snacks: '' }); const [dietaryAdvice, setDietaryAdvice] = useState(''); const handleClickOpen = (meal) … -
Django group by after annotate does not work
I have the following Django models: class Order(models.Model): ... org_slug = models.CharField() class ProductToOrder(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) qty = models.IntegerField() cost = models.FloatField() I need to sum Orders that grouped by on org_slug and it must have sum of orders that have only one ProductToOrder and ProductToOrder.qty=1 I'm trying to do it in this way orders = Order.objects.filter( some_filter_here ).values('org_slug').annotate( order_sum=Subquery(Order.objects.filter( org_slug=OuterRef('org_slug')).annotate( product_count=Coalesce(Sum('producttoorder__qty'), 1) ).filter(product_count=1).values('org_slug').annotate( sum=Sum('producttoorder__cost') ).values('sum')[:1] But it returns queryset of all orders. For example, if I have 1000 orders and 2 org_slugs, I need to get 2 objects in the query list but it returns 1000. This line where I'm trying to group by queryset in the following Subquery does not work: .filter(product_count=1).values('org_slug') I'm tried a lot of different querysets to fix it but it didn't give me any positive result. I see only one way to fix it, I need to create qty field in Order model but I hope, there are other ways to fix it. Can anybody help me with it? -
Docker / Celery / Django : Run a task with `celery` in a container while my `django` server is running in another container. It's possible?
I'm working on a project that uses Django, I'm a beginner with Django and Docker. For a feature, I decided to create a task with Celery (the feature consist to create a matchmaking queue) But, I use Docker for run my app, and I have 3 containers : one is for the frontend (node), the second for Django and the last is for my database PostgreSQL. And I don't really know if it's necessary to create another container for Celery. I found nothing with my research about a thing like that, but (if I say nothing wrong) in theory, it's possible and even very good to create a container for Celery, it's logic. So, I tried to launch my celery task in background, then launch my Django server like this in the same container : $ celery -A backend worker -l INFO --detach $ daphne -p 8000 backend.asgi:application TWO PROBLEMS : We lose the whole point of using Docker doing this AND we can't see the logs of celery. Problem : it is "ok" to do that, or it's really better to create another container for Celery or only for my task ? If yes, how I can do this … -
How to replicate tinymce V6 html minification on Django templates?
So I'm using both tinymce and React-hook-forms to create a form which is linked to a Django backend. I've recently updated tinymce to version 6 but I have noticed that now it automatically minifies the default values upon mounting I.e. if the default value is: <p>Random text<p> <p>Random text 2<p> Then the final tinymce result will be: <p>Random text<p> <p>Random text 2<p> I need to replicate this logic on the Django template backend otherwise the default template value and the actual tinymce value will be different and set dirty fields equal to true on react-hook-forms. This is easy to do for small templates, I've created my own personal python minification function but this does not work for large templates. Is there any way for me to replicate the tinymce minification process on the backend or somehow turn it off in the tinymce config frontend? Note: I have already tried a couple of backend minification libraries like django-htmlmin but this hasn't worked. -
Why does the nested sterilizer in django rest framework not work?
Good afternoon, I'm making an API and I ran into a problem, the embedded sterilizer does not work. Models from django.db import models def upload_to(instance, filename): return 'posts/{filename}'.format(filename=filename) class Brands (models.Model): BrandsDescription=models.TextField(null=True) def __str__(self): return self.BrandsDescription[0:50] class Cosmetic (models.Model): CosmeticName = models.TextField(default="") CosmeticDescription = models.TextField(null=True) Price = models.IntegerField(null=True) UrlsImage = models.ImageField(upload_to=upload_to, default = "") IsItNew = models.BooleanField(default="") Brands = models.ForeignKey(Brands,related_name="brands", on_delete=models.CASCADE) def __str__(self): return self.CosmeticName[0:50] class Order (models.Model): UserToken = models.TextField(default="") Date= models.DateTimeField(auto_now_add=True) Product = models.ManyToManyField(Cosmetic) Price = models.IntegerField(null=True) class Meta: ordering = ['UserToken'] def __str__(self): return self.UserToken[0:50] Serializers from dataclasses import field from rest_framework.serializers import ModelSerializer from rest_framework import serializers from .models import * class BrandsSerializer(ModelSerializer): class Meta: model= Brands fields='__all__' class CosmeticSerializer(ModelSerializer): brands=BrandsSerializer(read_only=True, many=True) class Meta: model= Cosmetic fields=('CosmeticName','CosmeticDescription','Price','UrlsImage','IsItNew','brands') class OrderSerializer(ModelSerializer): product = CosmeticSerializer(read_only=True, many=True) class Meta: model= Order fields=('UserToken','Date','product','Price') class postOrderSerializer(ModelSerializer): class Meta: model= Order fields='__all__' Views from rest_framework.decorators import api_view from rest_framework import viewsets from rest_framework.response import Response from rest_framework.permissions import * from rest_framework.authentication import TokenAuthentication from api.permissions import IsAdminOrReadOnly from .serializers import * from django_filters.rest_framework import DjangoFilterBackend from rest_framework.filters import SearchFilter class BrandsAPI(viewsets.ModelViewSet): queryset= Brands.objects.all() serializer_class = BrandsSerializer def get_paginated_response(self, data): return Response(data) class CosmeticAPI(viewsets.ModelViewSet): queryset= Cosmetic.objects.all() serializer_class = CosmeticSerializer def get_paginated_response(self, data): return Response(data) … -
Django doesn't send csrftoken and sessionid cookies
I accidentally deleted the csrftoken and sessionid cookies and now django is not sending me new cookies when pages load. What to do? (I'm using the Edge browser) -
django Could not parse the remainder: '[0]' from 'carray[0]'
hi i receved the mistake above with this sutiuation type here def check_url_exists(url_to_check): try: countArray= [] # محاولة استرداد سجل بناءً على الرابط المعطى display_obj = Display.objects.get(url=url_to_check) for i in range(1, 6): # حساب عدد السجلات where choosenum = i count = Display_Data.objects.filter(url=url_to_check, choosenum=i).count() print(count)# إضافة عدد السجلات إلى القائمة countArray.append(count) return countArray # الرابط موجود في قاعدة البيانات except Display.DoesNotExist: countArray= [0,0,0,0,0] return countArray def display_video(request, url): # تشكيل الـ URL الكامل لإطار الفيديو على YouTube embed_url = f"https://www.youtube.com/embed/{url}" full_url = f"https://www.youtube.com/watch?v={url}" soup = BeautifulSoup(requests.get(full_url).content, "html.parser") title = soup.title.text # استخدم نموذج "display_data" countArry=check_url_exists(url) # استخدم "Count" لحساب عدد السجلات # طباعة النتيجة # مرر الـ embed_url وعنوان الفيديو إلى القالب return render(request, 'display/videoA.html', {'embed_url': embed_url , 'title': title,'carry':countArry}) and templet have include sentence <div class="container mt-5"> <div class="d-flex justify-content-start">> <!-- زر "نجحت" --> <button type="submit" name="CHOOSE" value="1" class="btn btn-success mr-2">{{carray[0]}} نجحت</button> <!-- زر "فشلت" --> <button type="submit" name="CHOOSE" value="2" btn btn-danger mr-2">{{carray[1]}}فشلت</button> <!-- زر "تحتاج إلى مال" --> <button type="submit" name="CHOOSE" value="3" class="btn btn-warning mr-2">تحتاج إلى مال{{carray[2]}}</button> <!-- زر "تحتاج إلى أدوات" --> <button type="submit" name="CHOOSE" value="4" btn btn-info mr-2">{{carray[3]}}تحتاج إلى أدوات</button> <!-- زر "مؤجل" --> <button type="submit" name="CHOOSE" value="5" class="btn btn-secondary">{{carray[4]}}مؤجل</button> <!-- زر "اخر نجاح" --> <button … -
My custom permission isn't blocking put requests for editing objects
I have this permission class class AuthorOrReadOnly(BasePermission): def has_object_permission(self, request, view, obj): if request.method in SAFE_METHODS: return True return obj.author == request.user And this viewset class PostViewSet(viewsets.ViewSet): permission_classes = (AuthorOrReadOnly, ) queryset = Post.objects.all() serializer_class = PostSerializer def list(self, request): serializer = self.serializer_class(self.queryset, many=True) return Response(serializer.data) def create(self, request): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): serializer.validated_data['author'] = request.user serializer.save() return Response(serializer.data, status=201) return Response(serializer.errors, status=400) def retrieve(self, request, pk=None): post = get_object_or_404(self.queryset, pk=pk) serializer = self.serializer_class(post) return Response(serializer.data) def update(self, request, pk=None): post = get_object_or_404(self.queryset, pk=pk) serializer = self.serializer_class(post, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=400) def partial_update(self, request, pk=None): post = get_object_or_404(self.queryset, pk=pk) serializer = self.serializer_class(post, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=400) def destroy(self, request, pk=None): post = get_object_or_404(self.queryset, pk=pk) post.delete() return Response(status=204) And when I open my view url route It hidden the input fields for put patch... etc methods. But when I make a request from shell it just edit any objects. So I think my permission isnt working. I already tried put permission in list and a tuple and tried combining with other permissions, changing has_permission func, but It looks like it didnt work at all. -
For some reason the code doesn’t work until you set it unsafe in the settings? [closed]
from asgiref.sync import sync_to_async @sync_to_async @login_required def export_excel1(request): pricesecret = Price.objects.get(id=1) path = "/var/www/django/mysite/static/media/pricenew/" + str(request.user.usrid.listusers_id) + "" try: os.makedirs(path) except: path = "/var/www/django/mysite/static/media/pricenew/" + str(request.user.usrid.listusers_id) + "" filepath = '/var/www/django/mysite/static/media/pricenew/' + str(request.user.usrid.listusers_id) + '/' + pricesecret.url + '.xlsx' if os.path.exists(filepath) and os.stat(filepath).st_size != 0: url = "https://x.x.x.x/static/media/pricenew/" + str( request.user.usrid.listusers_id) + "/" + pricesecret.url + ".xlsx" print(filepath) return JsonResponse({'priceurl': 0, 'filepath': filepath, 'pricesecret': pricesecret.url + '.xlsx', 'url': url}) else: files = os.listdir("/var/www/django/mysite/static/media/pricenew/" + str(request.user.usrid.listusers_id) + "") if files: files = ''.join(map(str, files)) eawa = "/var/www/django/mysite/static/media/pricenew/" + str(request.user.usrid.listusers_id) + "/" os.remove(eawa + files) price_title = "Прайс_" + datetime.today().strftime('%Y-%m-%d %H:%M') headers = ( 'Код', 'Артикул', 'Наименование', 'Производитель', 'Ед', 'Цена,руб', 'Остаток', 'Заявка', 'Норма отпуска', 'Новинка!', 'Изображение') data = [] data = tablib.Dataset(*data, headers=headers, title=price_title) products = Product.objects.filter(stock__gt=0, published=True).select_related('brand', 'product_sklad').prefetch_related( 'brand__clt1__client_id__discount_list_k1', 'category__parent', ).exclude( product_sklad__gte=1) saleban = Salenban.objects.filter(client_id=request.user.usrid.listusers_id, published=1).select_related('client_id', 'mf_un').prefetch_related( 'client_id__discount_list_k1').values_list('mf_un', flat=True) post = [] for person in saleban: post.append(person) if saleban.exists(): for pos in post: products = products.filter.exclude(brand=pos) else: products = products for book in products: zayvka = "" if book.artikul == None: book.artikul = "" if book.brand == None: book.brand = "" if book.new_product == 0: book.new_product = "" if book.stock > 50: book.stock = ">50" data.append((book.id_p, book.artikul, book.name, book.brand, book.shtuk_e, book.price, … -
Django - Custom Translation for Django automatically generated messages
In a django project, how do I access the messages generated automatically by django? After implementing internationalization it seems some messages have been left our of the translation. IN particular those generated as part of the authentication process. Amongst the different messages I am trying to access is this one: The two password fields didn’t match.. I thought I could: override the existing UserCreationForm in the views write the sentence in english I want to override use from django.utils.translation import gettext as _ to capture it in the .po file. It feels overly complicated for what I am trying to achieve. Is there a more elegant way to achieve this? forms.py: class RegisterForm(UserCreationForm): email = forms.EmailField(required=True) def clean_email(self): if User.objects.filter(email=self.cleaned_data['email']).exists(): raise forms.ValidationError(_("the given email is already registered")) return self.cleaned_data['email'] class Meta: model = User fields = ["username", "email", "password1", "password2"] def __init__(self,*args,**kwargs): super(RegisterForm, self).__init__(*args, **kwargs) #iterate over form fields and set label to false for field_name, field in self.fields.items(): field.label = False views.py def register_user_form(request): url = request.META.get('HTTP_REFERER') if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = True user.save() age_group = form.cleaned_data.get('age_group') # check if userprofile with same username already exists user_profile, created = UserProfile.objects.get_or_create( … -
How to get an object by max value in Django ORM
I'm searching for a better way to do this: i need to get an object with the highest value in a model. The value isn't stored in a field, instead it is a number of objects from related(secondary) model (ManyToOne relations, ForeignKey) I've tried this: from django.db.models import * annotatedPM = PrimaryModel.objects.annotate(Count('secondarymodel')) max_value = annotatedPM.aggregate(Max('secondarymodel__count'))['secondarymodel__count__max'] annotatedPM.get(secondarymodel__count=max_value) >>> <PrimaryModel: object> This variant works well, but i'm wondering, is there any better way to do this? -
Django Class Based View Failed to Pass a Variable to the Template
I am new to Django and trying to build up a simple catalog site. I inserted some data into the table. So there should be values at primary key = 1 However, class is empty after passing to the template allclass_detail.html. There should be name and description text above the red line as in the screenshot Missing text, but now they are missing Same thing happened to both AllClassDetailView() and CombatEngravingDetailView() views.py from django.shortcuts import render from .models import CombatEngraving, ClassEngraving, AllClass, Archetype from django.views import generic from django.shortcuts import HttpResponse, Http404 def index(request): return render(request, 'index.html') class AllClassListView(generic.ListView): model = AllClass paginate_by = 5 context_object_name = 'class_list' template_name = 'catalog/class_list.html' class AllClassDetailView(generic.DetailView): model = AllClass def all_class_detail_view(request, primary_key): try: the_class = AllClass.objects.get(pk=primary_key) except AllClass.DoesNotExist: raise Http404('Class does not exist') return render(request, 'catalog/allclass_detail.html', context={'class': the_class}) class CombatEngravingListView(generic.ListView): model = CombatEngraving paginate_by = 10 context_object_name = 'combat_engraving_list' template_name = 'catalog/combat-engraving.html' class CombatEngravingDetailView(generic.DetailView): model = CombatEngraving def combat_engraving_detail_view(request, primary_key): try: combat_engraving = CombatEngraving.objects.get(pk=primary_key) except CombatEngraving.DoesNotExist: raise Http404('Combat Engraving does not exist') return render(request, 'catalog/combatengraving_detail.html', context={'combat_engraving': combat_engraving}) class_list.html {% extends "base_generic.html" %} {% block content %} <h1>Class List</h1> {% if class_list %} <ul> {% for class in class_list %} <li> <a href="{{ class.get_absolute_url … -
How to make CKEditor Django Mobile Responsive?
Well, I have a website that contains a ckeditor field (RichTextUploadingField) Default, no extra config but I want it to be mobile responsive. Here's the look of ckeditor in mobile view: I am not able to wrap it in a width coz that also doesn't work. I wasn't able to find any of solutions. Thank You! -
DisallowedHost message despite correctly configuring ALLOWED_HOSTS in my settings.py
Right, so I have an Amazon AWS Ubuntu server set up to deploy my website. I have correctly set up my virtual environment .venv and installed Python 3.10.12 and Django version 5.0.3 I have successfully cloned my GitHub Repo via the SSH methodology and have full access to said repo through my EC2 server I cd into my repo with no issues. I set up the NSG correctly - as confirmed my Amazon support I run the command python3 manage.py runserver 0.0.0.0:8000 I enter the Public IPv4 address http://xx.xx.xx.xx:8000/ into my address browser. Django Local Vars Settings.py Django Error Page Why are the local vars declaring the local host as given by Visual Studio Code 127.0.0.0.1 when this is clearly not the case. Its like it's refusing to take another look at the ALLOWED_HOSTS variable. I did read on here that this could be a cashe issue - if so how would I clear the cache. If this is not a cache issue then why is Django not seeing the correct host in the ALLOWED_HOSTS settings.py variable. Why has this not updated itself? Even when I clear the cache from my browser and even tried this in another browser, the … -
Hello, im new to programing can anyone help me with my problem, for some reason this massage keeps poping up
`Reverse for 'vjestiPlus' with arguments '('',)' not found. 1 pattern(s) tried: ['vjesti\-Dodavanje/(?P<slug>[-a-zA-Z0-9_]+)\Z'] `This is my views.py class VjestiDodavanje(View): def get(self, request, slug): vjest = Post.objects.get(slug=slug) context = { "vjest" : vjest, "vjestiForm" : VjestiForm() } return render (request, "members/vjestiDodavanje.html", context) def post(self, request, slug): vjestiForm = VjestiForm(request.POST) vjest = Post.objects.get(slug=slug) if vjestiForm.is_valid(): vjest = vjestiForm.save(commit=False) vjest.post = vjest vjest.save() return HttpResponseRedirect(reverse("vjestiPlus", args=[slug])) context = { "vjest" : vjest, "vjestiForm" : VjestiForm() } return render (request, "members/vjestiDodavanje.html", context) html {% extends "base.html" %} {% load static %} {% block title %} Vjesti {% endblock title %} {% block css_filles %} {% endblock css_filles %} {% block content %} <a href="{% url "><img src="{% static ' alt="Logo"></a> </div> <div> </div> <div class="desno"> <p class="naslovTekst"> <a href="{% url "prijava" %}">PRIJAVI SE</a></p> </div> <div class="desno"> <p class="naslovTekst"><a href="{%url "kontakti"%}">KONTAKTIRAJ NAS</a></p> </div> <div> <p class="naslovTekst"> <a href="{%url "vjesti"%}">VIJESTI</a></p> </div> </div> </header> <section id="all-posts"> <h2>My Collected Posts</h2> <ul> {% for post in Vjesti %} {% include "members/includes/vjestiPost.html" %} {% endfor %} </ul> </section> <p><a href="{% url "vjestiPlus" vjest.slug %}"> Dodavnje Vjesti </a></p> {% endblock content %} model.py class Post(models.Model): title = models.CharField(max_length=150) description = models.CharField(max_length=200) image = models.ImageField(upload_to="posts", null=True) date = models.DateField(auto_now=True) slug = models.SlugField(unique=True, db_index=True) … -
Rendering attachment url in iframe giving error of refused to connect
I have build a django backend to store a file in static , and through api i am fetching file details along with uri in reactjs i want to show the file in , but here i am facing issue of "refused to connect" models.py class Attachment(models.Model): file = models.FileField(upload_to='v1/file/attachment/') size = models.BigIntegerField(blank=True, null=True) def save(self, *args, **kwargs): if not self.size and self.file: self.size = self.file.size super().save(*args, **kwargs) Views.py def get_folder_data(folder, serializer_class): data = serializer_class(folder).data children = Folder.objects.filter(parent=folder) if children.exists(): data['children'] = [] for child in children: data['children'].append(get_folder_data(child, serializer_class)) files = File.objects.filter(folder=folder) if files.exists(): data['files'] = FileSerializer(files, many=True).data return data on frontend const uri = BaseUrl.FileServices.substring(0, BaseUrl.FileServices.indexOf("/v1"))+file.attachment_file_url <iframe src={uri} width="800" height="600" title="Embedded File"></iframe> but i am able to open the link of pdf file on new tab , but it is not working in iframe how can i solve this ? PS: I want to render pdf . You can suggest ,if there any other way enter image description here -
How to get Formset data in clean method and validate it - Django
I am using Formset as a field in a form. I am unable to get the Formset data in clean method. sharing code here. Forms.py class MyForm(forms.Form): my_field = forms.CharField() MyFormSet = formset_factory(MyForm, extra=2) class MainForm(forms.Form): main_field = forms.CharField() my_formset = MyFormSet() def clean(self): cleaned_data = super().clean() my_formset = cleaned_data.get('my_formset') print(my_formset,"my_formset") my_formset is getting printed as "None", even if i give data to the fields. Html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Main Form</title> </head> <body> <h1>Main Form</h1> <form method="post"> {% csrf_token %} <label for="id_main_field">Main Field:</label> {{ main_form.main_field }} <h2>Formset Fields</h2> {{ main_form.my_formset.management_form }} {% for form in main_form.my_formset %} <div> {{ form.my_field.label_tag }} {{ form.my_field }} </div> {% endfor %} <button type="submit">Submit</button> </form> </body> </html> How can i get the Formset data in clean method. -
Graphene field return null in answer even if exception was raised
I'm using Django + GraphQL to build a backend for my project. I have a User model defined in my models.py which have many fields including for instance email and telephone defined in the following piece of code: email = models.EmailField(_("email address"), max_length=320, unique=True) telephone = models.CharField(max_length=20, null=True, default=None, blank=True) The definition for UserType is: import graphene from graphene_django import DjangoObjectType from main.graphql import validators from main.models import User class UserType(DjangoObjectType): class Meta: model = User fields = ( "id", "first_name", "last_name", "email", "birthdate", "birthplace", ) def resolve_telephone(self, info): validators.verify_request_from_staff_user_or_from_superuser_if_target_staff( info, self, info.context.user, "telephone" ) return self.telephone def resolve_verified_email(self, info): validators.verify_request_from_staff_user_or_from_superuser_if_target_staff( info, self, info.context.user, "verified_email" ) return self.verified_email verify_request_from_staff_user_or_from_superuser_if_target_staff is a simple function that raises an exception of type graphql.GraphQLError if request user is trying to access information that he cannot (i.e. Staff-user accessing other staff users of base-user accessing other users). I have defined a query testUser which takes id as argument and return the user with such id. If i request the email field in the query the result data does not contain the email field (and this is my desidered behaviour), but if I request the telephone field the result data contains the field telephone with null … -
IntegrityError at /Hod/Staff/Save_Notification NOT NULL constraint failed: app_staff_notification.message in DJANGO
Can anyone please solve this error for me. I'm unsure if the problem is in the models.py or the values I put in the html code. Initially there was some kind of problem with the models migrating but I quitted it. enter image description here aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa **models.py** class Staff_Notification(models.Model): staff_id = models.ForeignKey(Staff, on_delete=models.CASCADE) message = models.TextField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.staff_id.admin.first_name **urls.py** path('Hod/Staff/Send_Notification', Hod_Views.STAFF_SEND_NOTIFICATION, name='staff_send_notification'), path('Hod/Staff/Save_Notification', Hod_Views.SAVE_STAFF_NOTIFICATION, name='save_staff_notification'), **Hod_Views.py** def SAVE_STAFF_NOTIFICATION(request): if request.method=='POST': staff_id = request.POST.get('staff_id') message = request.POST.get('message') staff = Staff.objects.get(admin = staff_id) notification = Staff_Notification( staff_id = staff, message = message, ) notification.save() return redirect('staff_send_notification') **staff_notification.html** {% extends 'base.html' %} {% block content %} <div class="content container-fluid"> <div class="page-header"> <div class="row align-items-center"> <div class="col"> <h3 class="page-title">Staff</h3> <ul class="breadcrumb"> <li class="breadcrumb-item"><a href="index.html">Dashboard</a></li> <li class="breadcrumb-item active">Staffs</li> </ul> </div> <div class="col-auto text-right float-right ml-auto"> <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter">View All Notifications </button> <!--a href="#" class="btn btn-primary mr-2"--> </div> </div> </div> {% include 'includes/messages.html' %} <div class="row"> <div class="col-sm-12"> <div class="card card-table"> <div class="card-body"> <div class="table-responsive"> <table id="table_id" class="table table-hover table-bordered table-center mb-0"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Email</th> <th class="text-right">Action</th> </tr> </thead> <tbody class="table-group-divider"> {% for i in staff %} <tr> <td>{{i.id}}</td> <td> <h2 … -
Django path doesn't match URL
This Django path: path('/search/<str:q>', views.search, name="search") doesn't match this url: http://127.0.0.1:8000/akdbapp/search/?q=foo Why not? Result: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/akdbapp/search/?q=foo Using the URLconf defined in aksite.urls, Django tried these URL patterns, in this order: akdbapp/ [name='index'] akdbapp/ /search/<str:q> [name='search'] akdbapp/ [name='detail'] akdbapp/ <int:artwork_id>/ [name='detail'] admin/ __debug__/ The current path, akdbapp/search/, didn’t match any of these. -
Having trouble retrieving the cookie in a django endpoint
So in one of my django view, I am setting a cookie, after a successful login, so that I can retrieve the user details from it and use it to display the appropriate information Here is my view class LoginView(APIView): def post(self, request): username = request.data.get('username') password = request.data.get('password') # Validate that both username and password are provided if not username or not password: return Response({'error': 'Username and password are required.'}, status=status.HTTP_400_BAD_REQUEST) # Authenticate user user = authenticate(username=username, password=password) if user is None: return Response({'error': 'Invalid username or password.'}, status=status.HTTP_401_UNAUTHORIZED) # Generate JWT token token = jwt.encode({'user_id': user.id}, 'your_secret_key', algorithm='HS256') response_data = {'token': token, 'Role': user.user_data.role} response = Response(response_data, status=status.HTTP_200_OK) response.set_cookie('jwt', token) return response Then I tried to retrieve the cookie in the following view class GetUserDetails(APIView): def get(self, request): token = request.COOKIES.get('jwt') print(token) if token: try: # Decode the JWT token to extract user ID payload = jwt.decode(token, 'secret', algorithms=['HS256']) user_id = payload.get('id') user = LoginDetails.objects.get(pk=user_id) user_data = user.user_data # Fetch and format user details education_data = list(Education.objects.filter(user=user_data).values()) work_experience_data = list(WorkExperience.objects.filter(user=user_data).values()) data = { 'user': { 'fullName': user_data.fullName, 'gender': user_data.gender, 'aadhaarNumber': user_data.aadhaarNumber, 'dateOfBirth': user_data.dateOfBirth, 'maritalStatus': user_data.maritalStatus, 'emergencyContactName': user_data.emergencyContactName, 'address': user_data.address, 'phoneNumber': user_data.phoneNumber, 'emailID': user_data.emailID, 'emergencyContactNumber': user_data.emergencyContactNumber, 'jobTitle': user_data.jobTitle, 'departmentName': … -
How to restrict access to my API written in DRF?
I have an email form on my website to contact me. It's implemented using Django Rest Framework. It only accepts POST requests. @api_view(['POST']) def send_email(request): if request.method == 'POST': name = request.data.get("name") email = request.data.get("email") subject = request.data.get("subject") message = request.data.get('message') message_con = 'Message: ' + message + '\nEmail: ' + email + '\nName of the sender: ' + name print("sent via POST") try: send_mail(subject, message_con, settings.EMAIL_HOST_USER, ['someemail@gmail.com']) return Response({"message": _("Email Successfully sent!")}) except Exception as e: print(e) return Response({"error": e}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) return Response({"error": _("Method Not Allowed.")}, status=status.HTTP_405_METHOD_NOT_ALLOWED) How do I restrict access to its API on my web site for other users? Is it possible to accept requests only from my form? -
Inserting uuid data in a uuid field gives out an error
When i try to create an object inserting uuid data in a uuid field it gives out an error what is the error that i could not find out in my code and what could be the solution to solve the error when uuid field is not accepting uuid data def create(self, validated_data): products_data = validated_data.pop('products') kitchen_order = KitchenOrder.objects.create(**validated_data) for product_data in products_data: modifiers_data = product_data.pop('modifiers', []) print(f"product id: {product_data}") kitchen_order_item = KitchenOrderItem.objects.create( kitchen_order=kitchen_order, product_id=product_data.get('product_id'), quantity=product_data['quantity'], note=product_data['note'] ) for modifier_data in modifiers_data: KitchenOrderItem.objects.create( kitchen_order=kitchen_order, modifier=kitchen_order_item, product_id=modifier_data.get('product_id'), quantity=modifier_data['quantity'], note=modifier_data['note'] ) return kitchen_order "products": [ { "product_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "quantity": 2, "note": "safs", "modifiers": [ { "product_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "quantity": 2, "note": "safs" } ] } ] Inserting above error gives out an error like updated = self._save_table( File "/home/suraj/Desktop/backend-third-party-integration/venv/lib/python3.10/site-packages/django/db/models/base.py", line 1067, in _save_table results = self._do_insert( File "/home/suraj/Desktop/backend-third-party-integration/venv/lib/python3.10/site-packages/django/db/models/base.py", line 1108, in _do_insert return manager._insert( File "/home/suraj/Desktop/backend-third-party-integration/venv/lib/python3.10/site-packages/django/db/models/manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/suraj/Desktop/backend-third-party-integration/venv/lib/python3.10/site-packages/django/db/models/query.py", line 1845, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "/home/suraj/Desktop/backend-third-party-integration/venv/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1823, in execute_sql cursor.execute(sql, params) File "/home/suraj/Desktop/backend-third-party-integration/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 122, in execute return super().execute(sql, params) File "/home/suraj/Desktop/backend-third-party-integration/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 79, in execute return self._execute_with_wrappers( File "/home/suraj/Desktop/backend-third-party-integration/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 92, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/suraj/Desktop/backend-third-party-integration/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 100, in … -
Is Django Templates Auto Full Translation Possible? if yes then how?
I want to translate my whole web app to Arabic I used the free google translate API thingy but its not accurate at all and I want accuracy now I looked for it and found DeepL and some others but it requires me to use translate text variables but it'll be too much because I have good amount of pages in my app so is there anyway I can just select Arabic from a dropdown and it translate my app to it with accuracy? I am willing to pay for some subscription if needed.