Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to create account
I have two models in two different apps, the first model is a custom user model, from abstractbaseuser class, called users and the second model is called wallet the wallet model has a field account which is a foreign key to the users model.This is my problem I want to automatically create a wallet for every newly registered user but after I use this code from django.db.models.signals import post_save from django.dispatch.dispatcher import receiver from .models import Users from userwallets.models import Wallet @receiver(post_save, sender=Users) def create_wallet(sender, created, instance, *args, **kwargs): if created: Wallet.objects.create(owner=instance) I can only create one user then when I try to register another user it says unable to create account please what I'm doing wrong. fyi: I'm using djoser for user registration but a customized one I've tried anything possible no results -
Image Caption with python
I would like to ask for help on the procedure that I must follow to create a program that generates image subtitles, I have been reading about tensorflow and VGG16, but I am not sure what to do, first create a model or automatically generate the image subtitle and save it in a txt? I would appreciate the help I have seen repositories where they only load VGG16 and tensorflow, as well as an .h5 model but I can't understand what this document would have, they also load txt files with image descriptions -
I'm have a variable Topic to a foreign key that produces this error: NameError: name 'Topic' is not defined
I'm working on a django project where I have created a project and an app. In models.py I have two classes: Topic and Entry. When I try to runserver I get an error NameError Topic is not defined. from django.db import models # Create your models here. class Lesson(models.Model): """A topic the user is learning about""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the mocel""" return self.text class Entry(models.Model): """Something specific learned about a topic.""" topic = models.ForeignKey(Topic, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) I have tried to migrate and makemigration courses the name of the app. I have rewritten the code and checked for indentation. I'm following the code in a text called Python Crash Course to the letter. At one point my code was working but now I'm getting NameError: name 'Topic' is not defined. But when I do python manage.py runserver 8000 I keep getting the error. -
Django script.js file
I am working on a django project and import javscript code from a script.js file. I am attempting to run a class and am getting a reference error. In the script.js file class RWT { constructor(r, w, t) { this.r = r; this.w = w; this.t = t; } console_r() { console.log(this.r) } }; function test_func() { console.log("this works") } function my_func() { test_func() let new_rwt = new RWT("r", "w", "t") new_rwt.console_r() } In my html file, I have an input that calls my_func(). page.html <body> <input value="a" onclick="my_func()"> <script src="{% static 'js/script.js' %}"></script> </body> I get the error: Uncaught ReferenceError: Cannot access 'RWT' before initialization What am I doing wrong here? -
Django giving error when trying to get path to static file
I'm trying to implement xhtml2pdf, and in my html file, it references a static file. I have the file in my project at jobs/static/jobs/style.css. When using the code xhtml2pdf provides in their docs, I am getting an error when it gets to result = finders.find(uri) saying django.core.exceptions.SuspiciousFileOperation: The joined path (/static/jobs/css/style.css) is located outside of the base path component (/opt/project/myproject/static). If I navigate to the url that the file should be at, http://127.0.0.1:8000/static/jobs/css/style.css, I see the code of the css file, so it is in the generally correct location. This project is being served in a docker container, and there is nothing stored in /opt, so I don't know why it coming up with this "base path component" at (/opt/project/myproject/static). I don't know where it is getting this path. I have searched my entire project, and there is no path, in any file, that includes opt or project. The project is stored in /app in the container. Here is the code I got from their site: from xhtml2pdf import pisa from django.template.loader import get_template from django.http import HttpResponse from django.conf import settings import os import io from django.contrib.staticfiles import finders def link_callback(uri, rel): """ Convert HTML URIs to absolute system … -
Modifying request contents in DRF
As far as I know request objects are immutable and it's bad practice to modify request through closed attributes like request._body or request._data. And since it described everywhere as bad practice, I'm lack of details to understand why it's should be avoided. What is the best approach to dynamically change request (for example if we need to decode value in request.body). As I alternative I can imagine custom Serializer with custom decode serializer.Field but maybe there's more clever solution? Thank you in advance! -
Django Ajax The likes I push disappear when I refresh the page
I implemented the Like function in Django Ajax, but when I refresh the page, the Likes I have pushed disappear. Why? I thought there was a problem with body: post_pk={{ post.pk }}` and looked into it, but could not figure it out. models.py from django.db import models from accounts.models import CustomUser class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Meta: ordering = ["-created_at"] class Like(models.Model): user_id = models.ForeignKey(CustomUser, on_delete=models.CASCADE) target = models.ForeignKey(Post, on_delete=models.CASCADE) views.py class DeletePost(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Post template_name = 'delete.html' success_url = reverse_lazy('home') def test_func(self, **kwargs): pk = self.kwargs['pk'] post = Post.objects.get(pk=pk) return (post.user == self.request.user) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) like_count = self.object.like_set.count() context['like_count'] = like_count if self.object.like_set.filter(user_id=self.request.user).exists(): context['is_user_liked'] = True else: context['is_user_liked'] = False return context def like(request): post_pk = request.POST.get('post_pk') context = {'user_id': f'{ request.user }'} article = get_object_or_404(Post, pk=post_pk) like = Like.objects.filter(target=article, user_id=request.user) if like.exists(): like.delete() context['method'] = 'delete' else: like.create(target=article, user_id=request.user) context['method'] = 'create' context['like_count'] = article.like_set.count() return JsonResponse(context) detail.html {% extends "base.html" %} {% load static %} {% block title %}{% endblock %} {% block content %} <div class="container"> <div class="alert alert-success" role="alert"> <p>タイトル:{{object.title}}</p> <p>投稿者:{{object.user}}</p> <p>コメント:{{object.content|safe}}</p> … -
django re_path() function pattern wouldnt match a url that contains the pattern
I am trying to map any url that ends with patternA to my index function in django. To do this, I have the following in my main urls.py: urlpatterns = [ re_path(r'patternA/$', views.index), ] When I put http://localhost:8000/patternA/, everything works fine, but things get weird when I put anything before patternA, like: http://localhost:8000/something/patternA/. Although my second path matches the regex patternA/$, when putting it inside browser search bar, I get 404 error. And when I change the pattern to .*patternA/$, everything works fine. Why do I get 404 with patternA/$ pattern? I put http://localhost:8000/something/patternA/ in browser search bar, expected to get index function executed but got 404 instead -
Django ModuleNotFoundError: No module named 'store.products'?
I recently started learning Django. Faced an error. I have created a new application and I am trying to import it into the main project, but I am getting an error.enter image description here I tried doing it like thisenter image description here -
Django model instance not being created upon Formset submission
I have a Formset, where one of the fields is a multi-select checkbox, with the options available being determined by a foreign key relationship (to the business model; the form takes business as an arguement). This works, however upon submission of the Formset, nothing is saved to the database despite a POST request and redirect taking place (I would expect it to create an instance or instances of the Instructors model). My models.py (including only relevant models): class Instructors(models.Model): uid = models.CharField(verbose_name="Unique ID", max_length=255, primary_key=True) business = models.ForeignKey(Business, blank=False, on_delete=models.CASCADE) first_name = models.CharField(verbose_name="First Name", max_length=255, blank=False) surname = models.CharField(verbose_name="Surname", max_length=255, blank=False) activities = models.ManyToManyField(Activity, blank=False) def __str__(self): return str(self.uid) class Business(models.Model): # if is_business on profile model = true, then get access to create Business Profile business_name = models.CharField(verbose_name='Business Name', max_length=255) business_description = models.TextField(verbose_name='Business Description', max_length=500) slug = models.SlugField(verbose_name='Slug', max_length=250, null=True, blank=True, unique=True) business_contact_number = models.CharField(verbose_name='Business Contact Number', max_length=32) business_email = models.EmailField(verbose_name='Business Email') business_profile_image = models.ImageField(verbose_name="Profile Picture", null=True, blank=True, upload_to='business_images/') creation_date = models.DateTimeField(auto_now_add=True) address = models.CharField(verbose_name="Street Address", max_length=100, null=True, blank=True) town = models.CharField(verbose_name="Town/City", max_length=100, null=True, blank=True) county = models.CharField(verbose_name="County", max_length=100, null=True, blank=True) post_code = models.CharField(verbose_name="Post Code", max_length=8, null=True, blank=True) country = models.CharField(verbose_name="Country", max_length=100, null=True, blank=True) longitude = models.CharField(verbose_name="Longitude", max_length=50, null=True, … -
How to add select foreign keys from django html template
iam trying to create an add movie function on my movie project, fields such as actor,director are added as foreign keys. when i do this via iam only able to add non foreign key fiels to the object. this is the Movie model class Movie(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE,default=True) name=models.CharField(max_length=100,unique=True) slug=models.SlugField(max_length=100,unique=True,blank=True) year=models.CharField(max_length=5,blank=True) language=models.CharField(max_length=50,blank=True) release=models.CharField(max_length=100,blank=True) rating=models.CharField(max_length=20,blank=True) poster=models.ImageField(upload_to='movies/poster',blank=True) cover=models.ImageField(upload_to='movies/cover',null=True,blank=True) duration=models.CharField(max_length=50,default=None,blank=True) streaming=models.ForeignKey(Streaming,on_delete=models.CASCADE,blank=True,null=True) ott=models.TextField(max_length=200,blank=True,null=True) actors=models.ManyToManyField(Actor,related_name='actor',blank=True) Characters=models.ManyToManyField(Character,related_name='character',blank=True) director=models.ForeignKey(Director,on_delete=models.CASCADE,blank=True,null=True) writers=models.ManyToManyField(Writer,related_name='writer',blank=True) cinematographer=models.ForeignKey(Cinematographer,on_delete=models.CASCADE,null=True,blank=True) based =models.CharField(max_length=100,blank=True,null=True) genres=models.ManyToManyField(Genre,blank=True) certification=models.ForeignKey(Certification,on_delete=models.CASCADE,null=True,blank=True) synopsis=models.TextField(max_length=1000,blank=True) trailer=models.CharField(max_length=500,blank=True) def __str__(self): return self.name this is the path from django.contrib import admin from django.urls import path from Movies import views app_name='Movie' urlpatterns = [ # function based path path('add_movie',views.add_movie,name='add_movie'), ] this is the template to add movie <form method="POST" enctype="multipart/form-data" class="user"> {% csrf_token %} <div class="row"> <div class="col-md-12 form-it"> <label>Movie Name</label> <input type="text" name="name" placeholder="Add movie title"> </div> <div class="col-md-12 form-it"> <label>Released Year</label> <input type="text" name="year" placeholder="Add movie title"> </div> <div class="col-md-12 form-it"> <label>Released Date</label> <input type="text" name="release" placeholder="Add Released date"> </div> <div class="col-md-12 form-it"> <label>Language</label> <input type="text" name="language" placeholder="Add Language"> </div> <div class="col-md-12 form-it"> <label>Rating</label> <input type="text" name="rating" placeholder="Add IMDB rating"> </div> <div> <div class="col-md-6 form-it"> <label>Poster</label> <input type="file" name="poster" placeholder="Add Movie Poster"> </div> <div class="col-md-6 form-it"> <label>Cover image</label> <input type="file" name="cover" placeholder="Add a cover image"> </div> </div> <div class="col-md-12 form-it"> … -
cannot access local variable 'conversation' where it is not associated with a value
@login_required def detail(request, pk): conversation = Conversation.objects.filter(members__in=[request.user.id]).get(pk=pk) if request.method == 'POST': form = ConversationMessageForm(request.POST) if form.is_valid(): conversation_message = form.save(commit=False) conversation_message.conversation = conversation conversation_message.created_by = request.user conversation_message.save() conversation.save() return redirect('conversation:detail',pk=pk) else: form = ConversationMessageForm() return render(request,'conversation/detail.html',{ 'conversation': conversation, 'form': form, }) cannot access local variable 'conversation' where it is not associated with a value -
TypeError: Field.__init__() got an unexpected keyword argument 'max_lenght' django
do you know why get this error for below code? "TypeError: Field.init() got an unexpected keyword argument 'max_lenght'" thanks, M from django.db import models from django.contrib.auth.models import User STATUS = ((0, 'Draft'), (1, 'Published')) # Create your models here. class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_post') created_on= models.DataTimeField(auto_now_add=True) updated_on = models.DataTimeField(auto_now=True) conent = models.TextField() status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['created_on'] def __str__(self): return self.title -
Django: User activation not working properly
I have registration page in my Django project. I can finish the registration just fine, and the console outputs the email with the generated link, but for some reason the user value captured by the views is None? How do I fix this? I generate user tokens like this: from django.contrib.auth.tokens import PasswordResetTokenGenerator from six import text_type class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( text_type(user.pk) + text_type(timestamp) + text_type(user.is_active) ) account_activation_token = AccountActivationTokenGenerator() When a user completes their registration, they're supposed to get an email like this: {% autoescape off %} Hello, {{ user.user_name }}! Your account has been successfully created. Please click the link below to activate your account. http://{{ domain }}{% url 'users:activate' uidb64=uid token=token %} {% endautoescape %} And I have my views setup so that if a user clicks on the link, their account gets activated and they're redirected to the dashboard like this: from django.contrib.auth import login from django.contrib.auth.decorators import login_required from django.contrib.sites.shortcuts import get_current_site from django.http import HttpResponse from django.shortcuts import redirect, render from django.template.loader import render_to_string from django.utils.encoding import force_bytes, force_str from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode #from orders.views import user_orders from .forms import RegistrationForm from .models import UserBase from .tokens import account_activation_token … -
react axios POST request to django failure
I try to make POST request from react app with axios. This is my code: import axios from 'axios'; const csrftoken = document.cookie.split('=')[1] // please don`t pay attention to this implementation const axiosInstance = axios.create({ baseURL: 'http://127.0.0.1:8000/api/', headers: { "Content-Type": "application/json", "X-CSRFTOKEN": csrftoken }, }); // onClick const handleApply = () =>{ const apiUrl = 'im/category_characteristics/'; axiosInstance.post(apiUrl, {withCredentials: true}) .then((response)=>{console.log(response.data)}) .catch(error => console.log(error)) }; These are my request headers: headers: AxiosHeaders Accept: "application/json, text/plain, */*" Content-Type: "application/json" X-CSRFToken: "8MGBp41YrnOSM23RLsAPIWNTNFLVTU7c" Django raises: Forbidden (CSRF cookie not set.): /api/im/category_characteristics/ Whereas, I receive successful response, when using Insomnia with the same headers: Insomnia terminal output: > POST /api/im/category_characteristics/ HTTP/1.1 > Host: 127.0.0.1:8000 > User-Agent: insomnia/2023.4.0 > Cookie: csrftoken=8MGBp41YrnOSM23RLsAPIWNTNFLVTU7c > Content-Type: application/json > X-CSRFToken: 8MGBp41YrnOSM23RLsAPIWNTNFLVTU7c > Accept: */* > Content-Length: 59 * Mark bundle as not supporting multiuse < HTTP/1.1 200 OK < Date: Sun, 13 Aug 2023 15:07:03 GMT < Server: WSGIServer/0.2 CPython/3.10.1 < Content-Type: application/json < X-Frame-Options: DENY < Content-Length: 56 < Vary: Origin < X-Content-Type-Options: nosniff < Referrer-Policy: same-origin < Cross-Origin-Opener-Policy: same-origin * Received 56 B chunk * Connection #13 to host 127.0.0.1 left intact I see Cookie header among others, but when I try to set it, I get error … -
Django checkbox input only working in one direction
I have a form with a checkbox on "pregnant". If the profile is not pregnant and goes to the update profile form, checking the box and submitting the form updates the profile. I can see in the dashboard it appears as pregnant now. However, if the profile is pregnant, and goes to update profile, unchecking the checkbox (prepopulated) and submitting, it does nothing! The profile information does not update (it still appears as pregnant in the dashboard). I am puzzled because the form connects to the database (it can update from non-pregnant to pregnant) but not the other way around! What am I missing? :-/ See my code. view: def edit_profile(request): if request.user.is_authenticated: current_user = Account.objects.get(id=request.user.id) form = EditProfileForm(request.POST or None, instance=current_user) if form.is_valid(): form.save() messages.success(request,("Your profile has been updated!")) return redirect('dashboard') return render(request, 'accounts/edit_profile.html',context={'form':form}) # else: messages.success(request,('You must be logged in!')) return redirect('login') html: <div class="flex col col-auto form-group form-check"> <label><input type="checkbox" id="pregnancy" value="Yes" name="pregnancy" {% if form.instance.pregnancy == 'Yes' %} checked {% endif %}> {% trans " Pregnant" %}</label> </div> model: class Account(AbstractBaseUser): .... pregnancy = models.CharField(max_length=10,blank=True, null=True, default='No') -
Unable to save the form in my database in Django
I wanted to practice Django, so I started off by creating a quiz website. However the the form isn't being saved into my database. I created the following models. difficulty_choices=(('easy','easy'),('hard','hard'),('medium','medium')) class Quiz(models.Model): name=models.CharField(max_length=200) topic=models.CharField(max_length=100) number_of_questions=models.IntegerField() difficulty=models.CharField(max_length=100,choices=difficulty_choices) def get_questions(self): return self.questions_set.all()[:self.number_of_questions] class Questions(models.Model): text=models.CharField(max_length=200) quiz=models.ForeignKey(Quiz,on_delete=models.CASCADE) correct=models.CharField(max_length=25) def __str__(self): return str(self.text) def get_answers(self): return self.answers_set.all() class Answers(models.Model): text = models.CharField(max_length=200) question = models.ForeignKey(Questions, on_delete=models.CASCADE) def __str__(self): return f"Question: {self.question.text}, Answer: {self.text}" class UserAnswer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) question = models.ForeignKey(Questions, on_delete=models.CASCADE) answer = models.ForeignKey(Answers, on_delete=models.CASCADE) selected=models.CharField(max_length=25,blank=True) The text field in 'Answer' model contains the options and text field in 'Question' model contains the question The option for each question is displayed in the form of radio select button. The UserAnswer model saves the answer answered by the authenticated user, for each question. To be able to select the option i created the below forms.py class QuizForm(forms.ModelForm): class Meta: model = Questions fields = ['text'] # Add other fields as needed def __init__(self, *args, **kwargs): super(QuizForm, self).__init__(*args, **kwargs) question_instance = kwargs.get('instance') answers = question_instance.get_answers() answer_choices = [(answer.text, answer.text) for answer in answers] self.fields['selected_answer'] = forms.ChoiceField( label="Select the correct answer", choices=answer_choices, widget=forms.RadioSelect ) and the views.py for this is @login_required def questions(request, pk): try: … -
Can Django forms be used in a custom view?
I'm using a CreateView to create an object then a custom written view to assign and update the values. The problem is I can't get to assign multiple values to a many to many relation. A configuration page looks like this right now: I'm not using forms, everything is inside the template. And I have the problem with the last input, the 'Cut material' checkboxes. Since I don't use a form, it's very tricky to handle that some inputs has only one value and some of them might have multiple values (like 'Cut material'). Right now my view will request the POST data and will try to match each option with it's value, but when it get's to 'Cut material' it will get an error if I select more options. I tried some workaround to insert some hidden inputs to pass into the context more info but I had no success. I guess if I can use forms then I might solve this issue and it will also help with validation. How do you think I can manage to pass correctly the value from 'Cut material' to the view to save it correctly? Also if you would do it with … -
Django DBBackup issue
I want to backup media fileand database of a django project,based on document I install Django-dbbackup, I want to store backup files in dropbox . I ran this command : pip install dropbox django-storages and add following in setting.py DBBACKUP_STORAGE = 'storages.backends.dropbox.DropBoxStorage' DBBACKUP_STORAGE_OPTIONS = { 'oauth2_access_token': 'DROPBOX_TOKEN', } now I cant backup ; account of dropbox is base mode and free(2GIG); token from 'generate access token' button on web site ERROR: 'D:/default-DESKTOP-RISNQKN-2023-08-13-164717.dump' did not match pattern '(/(.|[\r\n])*|id:.*)|(rev:[0-9a-f]{9,})|(ns:[0-9]+(/.*)?)' Internal Server Error: /account/admin_ability/ Traceback (most recent call last): File "D:\CODES\python\virtualenvs\karapp2\karkpp2\app_account\views.py", line 37, in f_admin_ability call_command('dbbackup') File "D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\django\core\management\__init__.py", line 194, in call_command return command.execute(*args, **defaults) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\dbbackup\utils.py", line 120, in wrapper func(*args, **kwargs) File "D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\dbbackup\management\commands\dbbackup.py", line 93, in handle self._save_new_backup(database) File "D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\dbbackup\management\commands\dbbackup.py", line 120, in _save_new_backup self.write_to_storage(outputfile, filename) File "D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\dbbackup\management\commands\_base.py", line 97, in write_to_storage self.storage.write_file(file, path) File "D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\dbbackup\storage.py", line 86, in write_file self.storage.save(name=filename, content=filehandle) File "D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\django\core\files\storage\base.py", line 37, in save name = self.get_available_name(name, max_length=max_length) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\storages\backends\dropbox.py", line 205, in get_available_name return super().get_available_name(name, max_length) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\django\core\files\storage\base.py", line 77, in get_available_name while self.exists(name) or (max_length and len(name) > max_length): ^^^^^^^^^^^^^^^^^ File "D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\storages\backends\dropbox.py", line 126, in exists return bool(self.client.files_get_metadata(self._full_path(name))) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\dropbox\base.py", … -
Why validation in the serializer does not perform DRF
Why validation does not perform. I have tried many things but still there is the standard "This field may not be blank." or "This field may not be null.". I also changed the clean method in the model but it only helped in the admin panel, thanks for your help. serializer: class MemeSerializer(serializers.ModelSerializer): class Meta: model = Meme fields = ['id', 'title', 'meme_image', 'author'] def validate_title(self, value): if not value: raise serializers.ValidationError("BAD") return value View class MemeView(viewsets.ModelViewSet): queryset = Meme.objects.all() serializer_class = MemeSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] def create(self, request): user = request.user data = { "title": request.data.get("title"), "meme_image": request.FILES.get("meme_image"), "author": user.pk, } serializer = self.get_serializer(data=data) if serializer.is_valid(): serializer.save() return Response({"message": "Added."}, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
How to fetch row Django serialize query set on jQuery?
Hello I'm trying to load Django Serialize Query set into jQuery Here my view.py def Load_Temp_Data(request): serialize_data = "" data_list = "" if request.method == "GET": count = TempCalculate.objects.filter(create_by = request.user).count() if count: data = TempCalculate.objects.filter(create_by = request.user) serialize_data = serializers.serialize("json",data) #calculation = TempCalculate.objects.filter(create_by = request.user).aggregate(Sum('price')) #conver to list #List = list(calculation.items()) data_list = list(data) return HttpResponse(serialize_data, content_type='application/json') Here my template and jQuery code function Load_data() { var row = "" // table load karo tyre aa pela karo. $.ajax({ url: "{% url 'load_temp_data' %}", success: function (data, status) { console.log(data) if (status) { no = 1 row_data = data for (var i = 0; i < row_data.length; i++) { console.log(i['quantity']) row += "<tr id =" + i + "><td>" + no + "</td><td>" + "<button type='button' id='delet_button' onclick='Delet_Item(" + row_data[i]['id'] + "," + i + ")' class='btn btn-danger'><i class='fa fa-trash'></i></button>" + "</td><td>" + row_data[i]['items__name'] + "</td><td>" + row_data[i]['quantity'] + "</td><td>" + row_data[i]['price'] + "</td><td>" + row_data[i]['total_gst'] + "</td><td>" + row_data[i]['net_amount'] + "</td></tr>" $('#Table_Data').html(row) no = no + 1 } $('#id_sub_total').val(data.total) $('#id_gst_total').val(data.gst_total) $('#id_total').val(data.net_amount) } else { alert("Error !") } } }) } when I'm console.log data set is print but I can't slice data like items_name,quantity etc -
Euro Currency Format (Django)
I have a variable and am trying to format it to following format "100.000,00". I have an amount (integer) and a price (decimal) and try to multiply these things to one total price with: totalprice = price * decimal(amount) I'm using Django and in the end I have to cast it to a string so I can use it in a text field. -
How to set up a django form field to receive data from a request?
For multilang, I store the fields in the database as json fields in this format: {"ru": "some text", "en": "some text"}, add form by itself looks like this input names example: title[ru], title[en] So i don't know how to write my form to get this data as: title: {"ru": "some", "en":"some"} What should i do? How to overwrite form field to get data like this? don’t find answers before that, I decided to completely abandon the forms and collect data with a custom function, but this decision seems to me wrong -
Google authentication MismatchingStateError in django (CSRF Warning - State not equal in request and response)
I have a problem that I have been trying to resolve for the past couple of days. When attempting to handle Google authentication in my Django web app, a MismatchingStateError is encountered at /signup/google/callback/. The issue arises when the Google authentication works correctly upon initial attempts but fails with the mentioned error after multiple tries. Even after logging in and out multiple times, the error persists. This is my first time implementing Google authentication within Django, and I've struggled to find comprehensive guidelines or resources. I'm currently learning about flow handling and recently became aware of potential associated risks. It's important to note that this problem resembles CSRF attacks. It emerges when there's a series of rapid login requests. After this error arises, subsequent logins are blocked. Notably, this issue isn't related to the session ID, as I've attempted to clear it without success. It seems tied to generation, possibly due to how states are managed. See the error here def google_auth(request): # Generate the Google OAuth authorization URL and redirect the user to it authorization_url, state = flow.authorization_url(access_type='offline', include_granted_scopes='true') request.session['oauth_state'] = state return redirect(authorization_url) def google_callback(request): # Exchange the authorization code for a Google OAuth access token. stored_state = … -
Python logging in Django : Filter won't work in logger
I have a logging custom filter class which suppose to ignore Django logs in my logger 'bucket' (I don't want to disable Django logs, just to keep them in separate log): class ExcludeDjangoLogsFilter(logging.Filter): """ Excludes django system logs from logger """ modules_to_exclude = ( "daphne.server", "django", "django.db", "django.server" ) def filter(self, record: logging.LogRecord) -> bool: """ Filters records to exclude from a logging modules with a certain names. """ return not record.name.startswith(self.modules_to_exclude) It works just fine if I pass this filter to handler but It doesn't if I pass this filter to logger. If I use this filter within logger interpreter enters the filter's class but doesn't enter in filter method. My logging config: LOGGING = { "version": 1, "disable_existing_loggers": False, # Filters: "filters": { "info_only": { "()": "logger.logger_filters.InfoOnlyFilter" }, "exclude_django_log": { "()": "logger.logger_filters.ExcludeDjangoLogsFilter" } }, # Formatters' profiles: "formatters": { "base": { "format": "[{asctime}][{levelname}][{name} / {funcName}][{lineno}] {message}", "datefmt": "%d/%m/%Y %H:%M:%S", "style": "{" }, "info": { "format": "[{asctime}][{name} / {funcName}] {message}", "datefmt": "%d/%m/%Y %H:%M:%S", "style": "{" }, "django_sys_format": { "format": "[{asctime}][{levelname} | {name}] {message}", "datefmt": "%d/%m/%Y %H:%M:%S", "style": "{" } }, # handlers: "handlers": { "important_file": { "level": "WARNING", "class": "logging.FileHandler", "formatter": "base", "filename": BASE_DIR / "logger/logs/important.log" }, "info_file": { …