Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Djongo Remove DB (python manage migrate)
I'm using djongo. I don't know what the cause is, but a message asking me to run python manage migrate appears from time to time. Does anyone know the cause? please. this is my code below code is app/models model from djongo import models class RealTime(models.Model): _id = models.CharField(max_length=255, primary_key=True) site = models.CharField(max_length=125) title = models.CharField(max_length=255) url = models.URLField() create_time = models.DateTimeField() GPTAnswer = models.TextField() class Meta: db_table = 'realtimebest' class Daily(models.Model): rank = models.IntegerField() title = models.CharField(max_length=255) url = models.URLField() create_time = models.DateTimeField() below code is Schema schema import graphene from graphene_django.types import DjangoObjectType from graphene import Mutation from .views import board_summary from .communityWebsite.models import RealTime, Daily class RealTimeType(DjangoObjectType): class Meta: model = RealTime class DailyType(DjangoObjectType): class Meta: model = Daily class Query(graphene.ObjectType): all_realtime = graphene.List(RealTimeType) all_daily = graphene.List(DailyType) def resolve_all_realtime(self, info, **kwargs): return RealTime.objects.all() def resolve_all_daily(self, info, **kwargs): return Daily.objects.all() class SummaryBoardMutation(Mutation): class Arguments: board_id = graphene.String(required=True) response = graphene.String() def mutate(self, info, board_id): response = board_summary(board_id) return SummaryBoardMutation(response=response) class Mutation(graphene.ObjectType): summary_board = SummaryBoardMutation.Field() schema = graphene.Schema(query=Query, mutation=Mutation) settings.py # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "corsheaders", # Graph QL 'graphene_django', 'graphene_mongo', 'webCrwaling', 'kingwangjjang', 'chatGPT' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'corsheaders.middleware.CorsMiddleware', … -
get user-details from rest-auth/user
I want to get the details of the logged in user... it's working on localhost, but not on remote other paths e.g rest-auth/login/ etc are all working on remote except rest-auth/user it keeps returning Server error(500) my url pattern urlpatterns = [ path('', include('dj_rest_auth.urls')), ] config in setting REST_AUTH = { 'USER_DETAILS_SERIALIZER': 'accounts.serializers.UserDetailsSerializer', } REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ] } i don't know what's wrong -
Problem with organizing models and forms in Django
I need a good tip, how can i create registration form fro this two models: class Adress(models.Model): """ Abstract model for users and organizations adresses """ country = models.CharField(max_length=50) city = models.CharField(max_length=50) street = models.CharField(max_length=50) house_number = models.IntegerField() postal_code = models.CharField(max_length=50) class Meta: verbose_name = "Adress" verbose_name_plural = "Adresses" And Patient model: class Patient(DiaScreenUser): """ Choices for diabet type options """ FIRST_TYPE = '1' SECOND_TYPE = '2' NULL_TYPE = 'null' DIABETES_TYPE_CHOICES = ( (FIRST_TYPE, '1 тип'), (SECOND_TYPE, '2 тип'), (NULL_TYPE, 'відсутній'), ) height = models.DecimalField(max_digits=6, decimal_places=2) weight = models.DecimalField(max_digits=6, decimal_places=2) body_mass_index = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) connect_to_doctor_date = models.DateTimeField(blank=True) diabet_type = models.CharField(max_length=10, choices=DIABETES_TYPE_CHOICES, default=NULL_TYPE) is_oninsuline = models.BooleanField(db_index=True) doctor_id = models.ForeignKey(Doctor, on_delete=models.SET_NULL, blank=True, null=True) adress_id = models.ForeignKey(Adress, on_delete=models.SET_NULL, blank=True, db_index=True, null=True) I need a registration form in which patient could input his personal info AND adress info ( BUT i cant understand how it works when i have a foreign key in my patient model ). Thanks for any advices! I tried create something like that, but in this case i cannot understand how to link adress to a patient class AdressForm(ModelForm): class Meta: model = Adress fields = ["country","city"] class PatientForm(ModelForm): adress_form = AdressForm() class Meta: model = Patient fields … -
No connection to the administartion panel. Django, JS
I'm having trouble connecting my snake game points to the model registered in admin. Then I want to use them to create a ranking.I dont use a JS on a daily basis so i use chatGtp to generate js code. I more or less understand the JS code. Its my code: @require_POST def submit_score(request): data = json.loads(request.body) score = data.get('score') user = request.user if request.user.is_authenticated else None if user: player_username = user.username new_score = Score(player=user, point=score, player_username=player_username) new_score.save() return HttpResponse("Dobry wynik!") class Score(models.Model): player = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True) point = models.IntegerField() player_username = models.CharField(max_length=30) # Stores the username def __str__(self): return f'{self.player_username} - {self.point}' function submitScore(score) { // fetch to send score fetch('submit-score/', { // The URL to change to the correct endpoint in Django method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': getCookie('csrftoken') // Required to Django to prevent CSRF attacks }, body: JSON.stringify({ score: score }) }) .then(response => { console.log(response); if (response.ok) { return response.json(); } throw new Error('Nie udało się zapisywać wyniku.'); }) .then(data => console.log('Wynik został zapisany:', data)) .catch((error) => console.error('Błąd:', error)); } I call the JS function in restart game. The game on the website works as it should -
Django: problem with adding apps to isntalled apps when they are moved from root directory
i am using django 4.2 . the project was working when apps were in base directory ( where manage.py locates) , then i created an apps directory and moved the apps to this directoryso the structure is like this ( partially) : /project/ /manage.py /config/ /settings/ / base.py # base settings file / local.py / testing.py / __init__.py /__init__.py /requirements/ /siteapps/ /products/ / (file of products app including __init__.py /accounts/ / (file of accounts app including __init__.py / (other apps) /__init__.py and this is related code i use in base.py settings : BASE_DIR = Path(__file__).resolve().parent.parent.parent print(f"base dir => {BASE_DIR}") # output : # base dir => /code # /code is base directory is docker container the project running in. print("path =>", sys.path) # output: # path => ['/code', '/usr/local/lib/python311.zip', '/usr/local/lib/python3.11', '/usr/local/lib/python3.11/lib-dynload', '/usr/local/lib/python3.11/site-packages'] INSTALLED APPS = [ ... # other apps including django's and third parties, # LOCAL APPS "siteapps.accounts.apps.AccountsConfig", "siteapps.products.apps.ProductsConfig", ] the error i get is : Traceback (most recent call last): File "/usr/local/lib/python3.11/threading.py", line 1045, in _bootstrap_inner self.run() File "/usr/local/lib/python3.11/threading.py", line 982, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.11/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python3.11/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] … -
Почему внутренний HTML на странице не обновляется?
I'm making a project in Django. ran into a problem. I have div containers with dynamic IDs. I load the ID from the database and automatically upload it to HTML. Here is an example of dynamic IDs for container divs: <div id="replyLikesDiv"> <img id="replyReviewsImg" src="{% static 'images/icons8-reply-arrow-50.png' %}"> <div id="replyReviewsDiv">Ответить</div> <img class='likesReviewsImg' id="likesReviewsImg{{ REVIEWS_IDS }}" onclick="likesReviewsImgClick(this)" src="{% static 'images/icons8-facebook-like-50.png' %}"> <div class='likesReviewsDiv' id="likesReviewsDiv{{ REVIEWS_IDS }}" onclick="likesReviewsDivClick(this)">{{ REVIEWS_LIKES }}</div></div> <div class="likeAuthorizationDiv" id='likeAuthorizationDiv{{ REVIEWS_IDS }}'> <div id="likeAuthorizationMessage">Пожалуйста, авторизуйтесь, чтобы продолжить.</div> <div id="sendReviewBtnDiv2"> <div id="sendReviewBtn2"">Закрыть</div> </div> </div> REVIEWS_IDS is automatically loaded from the database and inserted using the Jinja template engine. REVIEWS_IDS is an integer value 1,2,3,4... and does not repeat, so all ids are unique. By design, when you click id="likesReviewsDiv{{ REVIEWS_IDS }}", the likesReviewsDivClick() function is called. It looks like this: function likesReviewsDivClick(el){ var id = el.id; id = Number(id.replace(/[^0-9]/g, '')); id = 'likeAuthorizationDiv' + id; var element = document.getElementById(id); element.style.visibility = 'hidden'; alert(element.style.visibility); } In the function I read the ID and substitute it in likeAuthorizationDiv. Then I get the element I need in the function and try to change its style to hidden. The style changes in the alert, but not on the page. What can be wrong? I …