Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to overwrite save method in django model form
i'm trying to overwrite save method in my forms.py ,i have to prevent from creating duplicated objects , and if the object exists only update some fields class Item(models.Model): item = models.ForeignKey(Product,on_delete=models.CASCADE) quantity = models.IntegerField() for example if i entered this data before : item = XYZ , quantity = 100 i want to prevent from creating another XYZ item , i want to just update the quantity , for example i'll enter this data item = XYZ , quantity = 200 i try to prevent from creating this duplicate data , i just try to update the quantity previous quantity + new quantity 100 + 200 = 300 i must update the quantity to 300 for that purpose i overwrite save() in my forms.py class ItemForm(forms.ModelForm): class Meta: model = Item fields = ['item','quantity'] def save(self,*args,**kwargs): if self.instance.item is None: #i also tried this if not self.instance.item return super().save(*args,**kwargs) else: Item.objects.filter(item__name=self.instance.item).update( quantity=F('quantity') + self.instance.quantity) my views.py def createNewProduct(request): form = ItemForm() if request.method == 'POST': form = ItemForm(request.POST) if form.is_valid(): form.save() return render(request,'temp/add_item.html',{'form':form}) but it only update if it exists if not exists it doesn't create any new object , iexpect to create new object if it didn't exists … -
Using Protocols in django models raises metaclass conflict error
Let's say I have PEP-544 protocol called Summable : class Summable(Protocol): total_amount: Decimal And I have model Item that implements the Protocol class Item(Summable, models.Model): discount = models.DecimalField( decimal_places=2, validators=[MaxValueValidator(1)], default=Decimal('0.00'), max_digits=10 ) price = models.DecimalField( decimal_places=4, validators=[MinValueValidator(0)], max_digits=10 ) @property def total_amount(self): return sel.price - self.price * self.discount class Meta: ordering = ['id'] I get: TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases The same happens even if I extend Item's Meta from Summable.Meta and models.Model.Meta as well. I am using python 3.9 Any ideas? -
I am trying to supply data to a serializer related filed but it throws validation error
I am trying to supply data to serializer related field but it keeps throwing a validation error which says the field is required even when I supply a value for it through postman. I honestly don't know what I am doing wrong. Here's are my serializer; class ProjectFileSerializer(serializers.ModelSerializers): class Meta: model = ProjectFile fields = ['project', 'file'] class ProjectSerializer(serializers.ModelSerializer): project_file = ProjectFileSerializer(write_only=True, many=True) class Meta: model = Project fields = ['title', 'category', 'budget', 'project_file'] -
filter changelist records based on model's field
I have a model that contains the following fields: I added two button in changelist page and want to filter the list based on "active" field by clicking each of buttons , but i don't know how do that. please help me, thankes -
Django too slow only for post request
MY Django app runs perfectly in local machine. But when I uploaded it to Heroku, Digital Ocean and AWS differently. First worked in digital ocean but now doesn't work in any of these platform. Get requests are too fast but post request are timed out. Is there any known problem like this. -
Migrate two different models from two different Django applications
Hi guys so i have a Django project with two application named, shopper, parcel, each of this app have one model also named Parcel and Shopper. there is a one-to-many relationship between the 2 models. the problem is i want to migrate the two models, if I was just one i could have gone with the normal way of migrating a model. This is what i have tried python manage.py makemigrations parcel python manage.py migrate the problem with the first one is it does not take the other models in the shopper app into consideration and that is not what i want. python manage.py makemigrations parcel python manage.py migrate python manage.py makemigrations shopper python manage.py migrate this was my second solution, the commands end up creating migration of each model but still i don't think that is the right thing to do. Any help in the right direction please -
Django Form Javascript read Boolean field
In my models.py I have urgency = models.BooleanField(blank=True, default=False, verbose_name="Hitno otklanjanje") And I wish to run a javascript function to change a text field depending on 'True' or 'False' on that Boolean field. Problem is, I can't get the value. When I use 'document.getElementById('id_urgency').value;' I always get 'on', no matter of clickbox check. Why is that? I guess I'm reading the value wrong? Or? <script type="text/javascript"> function makeReadOnly() { var a = document.getElementById('id_urgency').value; console.log(a); if (document.getElementById('id_urgency').value == 'True'){ document.getElementById('id_date_days').readOnly = true; }else if (document.getElementById('id_urgency').value == 'False'){ document.getElementById('id_date_days').readOnly = false; } } document.getElementById('id_urgency').addEventListener('change', makeReadOnly); This is a part of django form. If I go to 'inspect' on that page, that Checkbox doesn't even have value, why is that? 'input type="checkbox" name="urgency" class="checkboxinput form-check-input" id="id_urgency"' -
Count the number of customers in view in Django rest Framework
I have a multi-vendor eCommerce website, wherein seller dashboard I have to count the number of customers that has purchased that merchant product. I have tried somehow , but it is not correct. I have written my logic in my view which is as follows: class DashboardView(ListAPIView): permission_classes = [AllowAny] def get(self, request, *args, **kwargs): count_1 = Order.objects.filter(order_items__item__merchant=self.kwargs['pk']).count() count_2 = Token.objects.filter(user__is_customer=True).count() # Having problem in this count_9 count_9 = Order.objects.annotate(abc=Count('user')).filter(order_items__item__merchant=self.kwargs['pk']).count() return Response( {'active_users_now': count_2, 'total_customers': count_9, 'total_orders': count_1, }, status=status.HTTP_200_OK) My models: class Order(models.Model): ............... user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) class OrderItem(models.Model): ...................#other fields order = models.ForeignKey(Order,on_delete=models.CASCADE, blank=True,null=True,related_name='order_items') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) Class Product(models.Model): ............ merchant = models.ForeignKey(Seller,on_delete=models.CASCADE,blank=True,null=True) I have two users model which are customers and sellers. I actually need to find out the number of customers which have purchased the products of a particular seller. Seller and Customer are one to one related with my CustomUser model: class Seller(models.Model): ................ seller = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) class Customer(models.Model): ............... customer = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) I just need to write the correct SQL join to determine the counts. Also 2nd question is: I need to write an api to see all the customers with details who … -
Using DjangoRestAPIKey while testing
I'm struggling with test my views with HasAPIKey and IsAuthenticated permission classes/ I've tried to create it in setUp function and in test function but with no effect.After passing it in header I'm still getting 403 error. The only change in settings.py is that line API_KEY_CUSTOM_HEADER = "HTTP_X_API_KEY" In test Class I'm inheriting from APITestCase views.py @api_view(['POST']) @permission_classes([HasAPIKey&IsAuthenticated]) def message_create(request): serializer = MessagesSerializer(data=request.data) if serializer.is_valid(): message_text = serializer.data.get('text') new_message = Message.objects.create(user=request.user, text=message_text) return Response(MessagesSerializer(new_message).data, status=status.HTTP_200_OK) tests.py def setUp(self): self.user1 = User.objects.create_user(username='Bob133', password='Pas$w0rd') self.user2 = User.objects.create_user(username='Katy_eleven', password='HardPassword23') self.message1 = Message.objects.create(user=self.user1, text="Example text message number 1") self.message2 = Message.objects.create(user=self.user1, text="Example text message number 2") self.message3 = Message.objects.create(user=self.user1, text="Example text message number 3") self.message4 = Message.objects.create(user=self.user2, text="Example text message number 4") def test_create_message_authorized(self): url = reverse('message_create') self.client.login(username='Bob133', password='Pas$w0rd') self.api_key = APIKey.objects.create_key(name='test_key') data = {"text": "completly new message"} response = self.client.post(url, data, content_type='application/json', **{'X-Api-Key':self.api_key[1]}) self.assertEqual(response.status_code, status.HTTP_200_OK) -
How to get request Object value in Django
I want get member object value 1.models.py enter image description here 2.views.py enter image description here 3.Log enter image description here -
User login not working on different view django
I use Django's authentication system to login a user. When I login a user like this: views.py: class Login(APIView): def post(self, request): data = request.data username = data.get("username") password = data.get("password") user = authenticate(username=username, password=password) if user is None: return Response(status=400, data={"error": "wrong input", "statusCode": 400}) else: login(request, user) #outputs True print(request.user.is_authenticated) #outputs True print("is_active: ", request.user.is_active) return Response() I can't verify the user in a different view, e.g: views.py class Files(APIView): def get(self, request): #outputs False print("is_authenticated", request.user.is_authenticated) return Response() In my settings.py I've included: INSTALLED_APPS = [ ... 'django.contrib.auth', 'django.contrib.contenttypes', ... ] MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ... ] Any ideas? -
Why autoescape cannot substitute safe in Django template?
I am a beginner in Django and working on the template and get confused on autoescape and |safe. I thought autoescape could substitute |safe, but it is not. I don't know why. Following is my code. Could anyone help me out? Thanks a lot. |safe works well: {% block title %} {{ name|safe }} {% endblock %} {% block body %} {{ description|safe }} {% endblock %} autoescape does not work: {% autoescape on %} {% block title %} {{ name }} {% endblock %} {% block body %} {{ description }} {% endblock %} {% endautoescape %} -
Not able to get the requested URL in django new version
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/customer/ Using the URLconf defined in crm.urls, Django tried these URL patterns, in this order: admin/ The current path, customer/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Here is my code crm/urls.py---> from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')), ] now accounts/urls.py---> from django.urls import path from . import views urlpatterns = [ path('', views.home,name="ShopHome"), path('products/', views.products,name="ProductsHome"), path('customer/', views.customer,name="customerHome"), ] Now accounts/view.py---> from django.shortcuts import render from django.http import HttpResponse def home(request): return HttpResponse('home') def products(request): return HttpResponse('products') def customer(request): return HttpResponse('customer') Please help me out guys I'm struck here for 2 days -
How to make Django dictionary serializer
So i tried to make a serializer but my server keeps giving me this error Traceback (most recent call last): File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\rest_framework\views.py", line 505, in dispatch response = self.handle_exception(exc) File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\rest_framework\views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception raise exc File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\rest_framework\views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\rest_framework\decorators.py", line 50, in handler return func(*args, **kwargs) File "C:\Users\aldya\OneDrive\Рабочий стол\work\SmartTeens\proshop_django\base\views\marathon_views.py", line 56, in getMarathon marathon = Marathon.objects.get(_id=pk) File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\django\db\models\query.py", line 418, in get clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs) File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\django\db\models\query.py", line 942, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\django\db\models\query.py", line 962, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, *args, **kwargs) File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\django\db\models\query.py", line 969, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\django\db\models\sql\query.py", line 1358, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\django\db\models\sql\query.py", line 1377, in add_q child_clause, needed_inner = self.build_filter( File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\django\db\models\sql\query.py", line 1319, in build_filter condition = self.build_lookup(lookups, col, value) File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\django\db\models\sql\query.py", line 1165, … -
Django error with admin form TypeError at /admin/syst/pet_history/add/ __str__ returned non-string (type NoneType)
I am trying to make a django admin form and all my other componenet work however when I try to add to this class on the form it comes back with the following error: TypeError at /admin/syst/pet_history/add/ str returned non-string (type NoneType) Does anyone know why this is happening here is the code for the class: class Pet_History(models.Model): pet_history_ID = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) pet_ID = models.ForeignKey(Pet_Description, on_delete=CASCADE) visit_Num = models.IntegerField(null=True) Visited_vet_before = models.CharField(max_length=50, null=True) First_time_of_illness = models.DateField(null=True) Special_Medication = models.CharField(max_length=50, null=True) Medication_Description = models.CharField(max_length=50,null=True) def __str__(self): return {self.visit_Num} -
Is there a way to convert Text to Image base64 without having to store the image?
Currently I have a captcha that generates random text in the Django backend and then pass the value via Jinja template, Then on the client side the Captcha is freshly drawn into the Canvas, There is one problem with this approach, The text is displayed in the View Page Source, Therefore a script can fetch the value and bypass it easily without having to crack the actual image. So I am planning to send it as an Image Base64 and then have canvas draw it on the client side without having to store the Image(Text to Image to base64 but image is not stored), And if possible, Without having to create the image(Text to Image base64 directly) -
Heroku 403 Forbidden Error while using Python requests module
I am working on a Django application, currently deployed on a Free Heroku dyno, which consumes the CoWin public API. On Heroku server, the requests.get() method returns HttpResponse status code 403. This is what my API call looks like - headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36'} url = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin?pincode=110001&date=23-05-2021" api_response = requests.get(url, headers = headers) When I run it locally using heroku local command, everything works fine & the HttpResponse status code returned is 200. I am failing to understand why it returns 403 status code when running it on Heroku server. -
How do I run migrations when I'm re-deploying Django app on server?
I'm new to Django and programming in general. After we have deployed a Django app either on VPS or AWS, and need to replace the files, how do I go about it? Had it been in development, I would just need to run the makemigrations and migrate commands. What is the safe way to do without affecting the data already there? Note: I would be using MS SQL server on VPS, or one of the RDS on AWS. -
Django only saving one option from custom multi select field
So I am trying to save class to my model which is a many to many field and when I try to save it from my custom form using multi select it only save one valu This is my views.py @login_required() def create_class(request): tea_user = request.user.username validate = teacher_validation(tea_user) if validate: if request.method == 'POST': Link = request.POST.get('link') Subject = request.POST.get('Subject') Class = request.POST.get('Class') teacher_user = Teacher.objects.get(User=request.user) teacher = Teacher.objects.get(id=teacher_user.id) created_class = Online_Class.objects.create( Link=Link, Subject=Subject,Created_by =teacher ) created_class.Class.set([Class]) return redirect('home') return render(request, 'online_class/Teacher/class-create.html') else: messages.warning(request, 'Sorry You Dont have Permission to access this page') return redirect('logout') And My models.py looks like this class Online_Class(models.Model): Created_by = models.ForeignKey(Teacher, on_delete=models.DO_NOTHING) Class = models.ManyToManyField(Classes) Subject = models.CharField(max_length=100) Link = models.CharField(max_length=200) Joined_by = models.ManyToManyField(Student, blank=True) created_at = models.DateTimeField(auto_now_add=True) choice = (('Yes','Yes'),('No', 'No')) Class_Ended = models.CharField(choices=choice, default='No', max_length=10) And my template looks like this {% extends 'dashboard/teacher/base.html' %} {% block title %} Create Class {% endblock title %} {% block class %} active {% endblock class %} {% block body %} <div class="pc-container"> <div class="pcoded-content"> <div class="row"> <form method="POST"> {% csrf_token %} <div class="form-group"> <label >Zoom Link</label> <input type="url" class="form-control" name="link" placeholder="URL" required=""> </div> <div class="form-group"> <label>Subject</label> <select class="form-control" name="Subject" required=""> {% for subject in … -
export two querysets into one excel using django-import-export
I can't get two querysets export into a single excel. How should I do it??? This is what I tried. class ExportIssuedBooksResource(resources.ModelResource): def export(self, queryset = None, *args, **kwargs):#this method helps capture the current user school queryset = Issue.objects.all().filter(borrower_id__school = kwargs['school']) queryset2 = TeacherIssue.objects.all().filter(borrower_teacher__school = kwargs['school']) return super().export(queryset, queryset2,*args, **kwargs) class Meta: model = Issue fields = ('book_id__reg_no','book_id__book_name','borrower_id__name','borrower_id__student_id','issue_date') export_id_fields = ('book_id__reg_no',) And the view def ExportIssuesView(request): dataset = ExportIssuedBooksResource().export(school = request.user.school) response = HttpResponse(dataset.xls, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="All Issued Books.xls"' return response -
AssertionError: You cannot call `.save()` on a serializer with invalid data
def update(self, request, pk=None): queryset = Product.objects.all() product = get_object_or_404(queryset, pk=pk) serializer = ProductSerializer(product, data=request.data, context={"request": request}) serializer.is_valid() serializer.save() # print(request.data["product_details"]) for type_detail in request.data["product_details"]: if type_detail["id"] == 0: # For Insert New product_type Details del type_detail["id"] type_detail["product_id"] = serializer.data["id"] serializer2 = ProductDetailsSerializer(data=type_detail, context={"request": request}) serializer2.is_valid() serializer2.save() else: # For Update product_type Details queryset2 = ProductDetails.objects.all() type_product = get_object_or_404(queryset2, pk=type_detail["id"]) del type_detail["id"] serializer3 = ProductDetailsSerializer(type_product, data=type_detail, context={"request": request}) serializer3.is_valid() serializer3.save() print("UPDATE") return Response({"error": False, "message": "Data Has Been Updated"}) hi guys I have got this error in my view set Django can you guys help me with it ..whenever I want to update the date this is the error I get -
Django rendering error while using request.session in html page?
why i am getting error during rendering?? views.py: r.session["name"]="testing" return render(r,"home.html")``` home.html: -------- ``` <body> <h1>{{ r.session["name"] }}</h1> </body> -
APITestCase throws 403 when no credentials needed
I', strugglinh with strange APITestCase behaviour while testing. I'm keep getting 403 Error on views that doesn't require any authentication. Settings.py are completly free from any DEFAULT_PERMISSION_CLASS etc. Only additional lines there are installed apps and "API_KEY_CUSTOM_HEADER = "HTTP_X_API_KEY"" line. More over I explicit said in views "AllowAny" what You can see below. While testing with Postman everything works like a charm. views.py @api_view(['GET']) @permission_classes([AllowAny]) def message_detail(request, pk): try: message = Message.objects.get(pk=pk) except Message.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = MessagesSerializer(message) message.add_view() return Response(serializer.data, status=status.HTTP_200_OK) tests.py def test_detail_view_status(self): pk = 3 url = reverse('message_detail',kwargs={'pk': pk}) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_detail_view_content(self): pk = 3 url = reverse('message_detail', kwargs={'pk': pk}) response = self.client.get(url) message = Message.objects.get(pk=pk) serializer = MessagesSerializer(message) self.assertEqual(response.data, serializer.data) tracebacks test_detail_view_content self.assertEqual(response.data, serializer.data) AssertionError: {'detail': ErrorDetail(string='Authenticati[57 chars]ed')} != {'views': 0, 'text': 'Example text message number 3'} test_detail_view_status self.assertEqual(response.status_code, status.HTTP_200_OK) AssertionError: 403 != 200 -
How to create "Delete Event" botton on Django Calendar in Python
I want to be able to Delete Event on my Calendar in Django using Python? I am not able to figure out how I delete the Event after it creates it. HOW TO CREATE A CALENDAR USING DJANGO I used this person code to make my calendar in Django but now I need some type of delete button to delete a event on there. Please help.... -
Google API OAuth 2 and Django
I work on a project with Django, Google API Calendar and OAuth 2 and I have the follow error: (insecure_transport) OAuth 2 MUST utilize https. When I set the redirect_uri with google_auth_oauthlib.flow.Flow, the URI that I set is: http://localhost:8000/google/oauthcallback.