Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am unable to serialize my product images in Django Rest Framework
I am trying to create product model for my e-commerce app in Django rest framework, and I am able to upload images to my products on the admin panel but I am unable to get their links while calling the API. Here's my: models.py from django.db import models from api.category.models import Category from api.color.models import Color from api.size.models import Size class Product(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=250) regular_price = models.CharField(max_length=50) sell_price = models.CharField(max_length=50, blank=True, null=True) stock = models.CharField(max_length=50) is_active = models.BooleanField(default=True, blank=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, blank=True, null=True) colors = models.ManyToManyField(Color) sizes = models.ManyToManyField(Size) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self) -> str: return self.name class ProductImage(models.Model): product = models.ForeignKey(Product, default=None, on_delete=models.CASCADE) image = models.FileField(upload_to = 'images/') def __str__(self): return self.image.url serializer.py from django.db.models import fields from rest_framework import serializers from .models import Product, ProductImage class ImageSerializer(serializers.ModelSerializer): class Meta: model = ProductImage fields = ('image', ) #print(model) class ProductSerializer(serializers.HyperlinkedModelSerializer): colors = serializers.StringRelatedField(many=True) sizes = serializers.StringRelatedField(many=True) image = ImageSerializer(many=True, read_only=True) class Meta: model = Product fields = ('id', 'name', 'description', 'regular_price', 'sell_price', 'category','colors', 'sizes', 'image') admin.py from django.contrib import admin from .models import Product, ProductImage class ProductImageAdmin(admin.StackedInline): model = ProductImage @admin.register(Product) class ProductAdmin(admin.ModelAdmin): inlines = [ProductImageAdmin] class Meta: model … -
How to add redis sentinel in django apps?
I have a django application and I want to use redis sentinel for high availabilty. Since Django has added support for redis in its latest version (i.e django 4.0) so I am thinking to use it, but if a better solution is available in django-redis or django-redis-cache I might use them too. The sample Caching settings is given below from django-documentation. CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.redis.RedisCache', 'LOCATION': [ 'redis://127.0.0.1:6379', # leader 'redis://127.0.0.1:6378', # read-replica 1 'redis://127.0.0.1:6377', # read-replica 2 ], } } Here first node is master and other two nodes are its replica(or slaves). I wanted to ask how could I configure these settings so I could use them in my application. -
How to assign Foreign key inside loop Django
enter image description hereI want assign foreign key to each colors in loop colorArray=[{color:'red', product_id:5}, {color:'yellow', product_id:5}] Product Model class Product(models.Model): name = models.CharField(max_length=500) brand = models.CharField(max_length=500) description = models.CharField(max_length=500) Color Model class Color(models.Model): colorName = models.CharField(max_length=500) product_id = models.ForeignKey(Product, on_delete=models.CASCADE) views class AddColors(APIView): def post(self,request): for i in colorArray: s=AddColors() s.colorName=i['color'] s.product_id=i[Product.objects.get(id=i['product_id'])] s.save() return Response({'colors Saved'}) -
Mock API call in model signal Django
I am new to Django and unit tests, so any feedback is very helpful. I built a small integration with a third party to create a matching account in their system whenever an account is created in our system. I do this on a signal in the model class. The signal is simple and looks like this: @receiver(post_save, sender=Company) def create_integration_company(sender, instance, created, **kwargs): if created: company_integration_id = third_party.create_crm_company(instance) instance.integration_id = company_integration_id instance.save() When I ran our tests, it created thousands of accounts in this third party's system, so I discovered mock. We have a bunch of tests that create companies and I was wondering if I have to add this to every one of them? @mock.patch("apps.accounts.utils.build_request", return_value="123") My question is: at which level should I mock the response and just return 123 for the new integration id? Can I do it at the model level? Or do I have to do this for every test case we have? -
How to specify custom auth backend for single login view only?
I have a two login api endpoints. One for normal user where user login with only username and for staff users user should login with valid username and password. class PasswordLessBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): try: user = User.objects.get(username=username) except User.DoesNotExist: return None else: if self.user_can_authenticate(user): return user AUTHENTICATION_BACKENDS = [ "django.contrib.auth.backends.ModelBackend", "users.backends.PasswordLessBackend", ] I want to remove my custom backend from settings and apply this in this login view only since other login for staffs should require correct password as well. class NormalUserLoginView(APIView): permission_classes = [permissions.AllowAny] def post(self, request): serializer = NormalUserLoginSerializer(data=request.data) serializer.is_valid(raise_exception=True) username = serializer.validated_data.get("username") user = authenticate(username=username) if user is not None: refresh_token = RefreshToken.for_user(user) access_token = refresh_token.access_token data["access_token"] = str(access_token) data["refresh_token"] = str(refresh_token) -
uWSGI uid to get database connection
I am trying to work out the correct config to automate and not sure how to reconcile user id for uwsgi. I have a (Ubuntu system) user called 'prod' who owns the source code for a Django site, and a postgres database 'dbprod' with owner 'prod'. I can define a .pgpass in /home/prod so that the prod user can access the database without typing in a password. This is the postgres way. I am worried that running my uwsgi worker processes as this user ('prod') is wrong / insecure, in that if someone subverts the web-server process, they can change the code and the data and I'm toast, whereas if the process was owned by www-data who only had 'read' access to the source code, they'd need another exploit. If I make that change, to a different user (e.g. www-data), the database connection can't be established because www-data can't access 'prod''s home/.pgpass. I don't think I want 'www-data' to access the database. What is the correct approach now? (I know using docker is normal and would make this look somewhat different, but the fundamental issue of minimising privileges is the same) -
How do i paginate objects grouping by their date in each page?
Trying to paginate a list of objects by their date. For example: page 1 -> objects date is smaller than today page 2 -> objects date is equals to today page 3 -> objects date is equals to tomorrow and so on. Each page can have different number of elements. -
Change django picture img src in template based on min-width
I wasn't sure how to ask this question. Want to send correctly sized images to different screens from my django application. I have it so that when an image is uploaded, that it is saved to media but with multiple sizes. So, the image above shows in my media/uploads/pieces/{ID}/Sargent.jpg and all of it's other sized images. The models imageField is pointing to the "original" file without an underscore and width. templates/art/piece_detail.html <picture> <source media="(min-width:300px)" srcset="{{ piece.image.url ??? }}"> <source media="(min-width:375px)" srcset="{{ piece.image.url ??? }}"> <source media="(min-width:786px)" srcset="{{ piece.image.url ??? }}"> <source media="(min-width:1440px)" srcset="{{ piece.image.url ??? }}"> <img src="{{ piece.image.url }}" alt="{{ piece.name }} - {{ piece.height }} x {{ piece.width }}"> </picture> Then here I am using an HTML <picture> tag with some source medias to be how I serve the appropriate image. However I am at a loss on maybe the best way to do what I am trying to accomplish. I realize these break points are probably not exactly what I need, but just trying to get my idea across. I thought about adding more "path" fields to the Piece model and set them to these other URL paths too, but that seems like a sloppy solution to … -
Importing FDB file in Django Python in Visual Studio Code?
I am working in Django framework in Python using Visual studio code, I want to import an FDB file but I'm new to Django, therefore can't figure out how to do it. It would be really appreciated if I Could get what steps to follow to do it. Thanks -
Bizarre login/session error scenario with Django
if anyone could help I would be very thankful, I'm so confused and dumbfounded. The Scenario When we create a user on our sign up page, it redirects to the profile page where we can view all the attributes of the user, like it should. Creating a new user Getting Redirected after creating new Since we have not implemented logout yet, on a new incognito browser (to start a clean session with no pre-existing variables) we log in using an existing admin, we can see the user entry as well in the database. However, now when we use another new incognito tab to log into this new user, django refuses to log us in, and we get a 403 forbidden error and we are redirected to a error httpresponse page. Here is the bizzare part, when we change the password through the user table on the admin page, then decide to login again using a new incognito browser, it logs us in. We thought it was a problem with the password, so we got rid of the hash to see the raw password. So we tried again with a new user, confirming the password was the same. Also, when we … -
The view fitness_app.views.BookingView didn't return an HttpResponse object. It returned None instead
I dont understand as this code was working fine earlier and now i am receiving the above error when the form is submited. views.py file class BookingView(FormView): form_class = AvailabilityForm template_name = "availability.html" def form_valid(self, form): data = form.cleaned_data bookingList = Appointment.objects.filter() for booking in bookingList: if booking.start == data["start_time"]: print("Cant be booked") return HttpResponse("Cant be booked") else: booking=Appointment.objects.create( name=data["name"], start=data["start_time"], end=data["end_time"] ) booking.save() return HttpResponse("can be booked") -
getting null in object of many to many relation object django
I'm saving an object with many to many relations in the database but when I'm fetching it so so it returns me IDs of that relational object but I want to the whole object instead, so I have added a property in the serializer and after that, it returns me the object.name only and the value of it is null, I don't know why it is behaving like this? anyone can help? views.py queryset = Tag.objects.filter(project_id=project_id).all() serializer = TagSerializer(queryset, many=True) return Response(serializer.data) serializers.py class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag # fields = '__all__' fields = ['id', 'name', 'description', 'singleline'] singleline = SinglelineSerializer(read_only=True) models.py class Tag(models.Model): name = models.CharField(max_length=255, default='') description = models.CharField(max_length=255, default='') singleline = models.ManyToManyField(Singleline) class Meta: db_table = 'tags' -
django-bootstrap5 and button alignment
I want to display a button next to a form instead of below: This is how it looks: should look like this: corresponding code: form: class TheForm(forms.Form): var = forms.ChoiceField(choices = choices, label = "") temp late: {% if TheForm %} <form method = "post"> {% csrf_token %} {% bootstrap_form TheForm %} {% bootstrap_button button_type="submit" content="OK" %} </form> {% endif %} -
how to send input date value (GET) to backend - django
I'm trying to send two dates from template to backend through ajax response , in order to check if the two date exists or not! if not exists then return the entire data, but if exists just return the data between that two range def dateTimePrice(request): start = request.GET.get('from') end = request.GET.get('to') print(start,end)# if start and end: datetimes = ImeiInvoice.objects.filter(invoice__created_at__range=(start,end)).annotate( total_price=Sum( (F('price')) - F('discount'),output_field=DecimalField(max_digits=20,decimal_places=3)) ).annotate( total_quantity=( Count('pk') ) ).aggregate( all_price=Sum(F('total_price')), all_qnt=Sum(F('total_quantity')) ) else: datetimes = ImeiInvoice.objects.all().annotate( total_price=Sum( (F('price')) - F('discount'),output_field=DecimalField(max_digits=20,decimal_places=3)) ).annotate( total_quantity=( Count('pk') ) ).aggregate( all_price=Sum(F('total_price')), all_qnt=Sum(F('total_quantity')) ) return JsonResponse(datetimes,safe=False) @login_required def dateTimePriceTemp(request): return render(request,'myapp/datetimes.html') and here is my GET form, to get the two date from $(document).ready(function(){ const spinner = document.getElementById('spinnerDateTimePrice') const start_date = new Date($('#from').val()); const end_date = new Date($('#to').val()); console.log(start_date) console.log(end_date) if(start_date && end_date){ data={ 'from':start_date, 'to':end_date } } function dateTimePrices(){ $.ajax({ type:'GET', url:'/prices/dateTime/data', data:data, success:function(data){ const datetimes = data; var k = '<tbody>'; if(datetimes){ k+= '<tr>'; k+= '<td>' + datetimes["all_qnt"] + '</td>'; k+= '<td>' + datetimes['all_price'] + '</td>'; k+= '</tr>' }else{ k+= '<td class="p-2 text-xs border border-purple-900 md:text-base textpurple" colspan=6>found nothing</td>' } k+='</tbody>' document.getElementById('datetime_list').innerHTML = k } }) } dateTimePrices(); }) <form action="" method="GET"> <div class="col-11 p-1 mt-1 mx-auto text-center row rtl "> <p class="col-12 col-sm-6 … -
Django Data import from JSON file to DB not working with OneToOneFields
I'm currently working on an importer which lets me import a json file from a folder which i get from another server. So far i can import all the regular fields of my model but the parts that are using OneToOneFields are not being imported. Instead i get this error message: Something went wrong saving this Facility: Test Facility Field 'id' expected a number but got {'PrimaryAddress': '1234 Test Avenue', 'SecondaryAddress': '', 'City': 'Testcity', 'RegionOrState': 'CA', 'PostalCode': '12345', 'Geolocation': ''}. This is my code including the json i'm importing and the database model: import os import json from data_import.models import Facility, FacilityAddress from django.core.management.base import BaseCommand from datetime import datetime from jsontest.settings import BASE_DIR, STATIC_URL class Command(BaseCommand): def import_facility_from_file(self): print(BASE_DIR) data_folder = os.path.join(BASE_DIR, 'import_data', 'resources') for data_file in os.listdir(data_folder): with open(os.path.join(data_folder, data_file), encoding='utf-8') as data_file: data = json.loads(data_file.read()) for key, data_object in data.items(): Name = data_object.get('Name', None) IssuedNumber = data_object.get('IssuedNumber', None) AddressInfo = data_object.get('AddressInfo', None) try: facility, created = Facility.objects.get_or_create( Name=Name, IssuedNumber=IssuedNumber, AddressInfo=AddressInfo ) if created: facility.save() display_format = "\Facility, {}, has been saved." print(display_format.format(facility)) except Exception as ex: print(str(ex)) msg = "\n\nSomething went wrong saving this Facility: {}\n{}".format(Name, str(ex)) print(msg) def handle(self, *args, **options): """ Call the function to … -
Django handle transaction on filter query
I have a Model that has a "score" attribute and a route that returns the object with the biggest score from the database (MySQL). I want to use multiple instances of the same application (two microservices) and I am afraid that I will face race conditions, both machines returning the same client. How could I make sure that this is not happening? After returning a client, it will be marked as PROCESSED. def getClient(request): client = Client.objects.order_by('-score').filter(state="UNPROCESSED").first() client.state = "PROCESSED" client.save() return HttpResponse(f"<h1>{client.name}</h1>") -
Receiving error message "name 'SaveInput' is not defined" while defining a save method Django
I am trying to create a save method (.save()) for my forms.Form in Django views.py but I keep receiving an error message - name 'SaveInput' is not defined. from django.shortcuts import render from django.shortcuts import redirect from django.urls import reverse from django.http import HttpResponseRedirect from django.http import HttpResponse from django import forms import markdown2 from . import util class AddPageForm(forms.Form): title = forms.CharField(max_length=20) content = forms.CharField(widget=forms.Textarea( attrs={ "class": "form-control", "placeholder": "Tell us more!" }) ) def add_page(request): submitted = False if request.method == "POST": form = AddPageForm(request.POST) entries = util.list_entries() if form.is_valid(): title = form.cleaned_data['title'] content = form.cleaned_data['content'] saveInput = SaveInput(title=data['title'], content=data['content']) saveInput.save() for entry in entries: if title.upper() == entry.upper(): context = { "title": title, "content": content } return render(request, "encyclopedia/errorpage.html", context) else: return HttpResponseRedirect(reverse("/encyclopedia:index/?submitted=True")) else: return render (request, "encyclopedia/addpage.html", { "form": AddPageForm() }) Traceback Switch to copy-and-paste view C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) … ▶ Local vars C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars C:\Users\USER\Downloads\wiki\wiki\encyclopedia\views.py, line 84, in add_page saveInput = SaveInput(title=data['title'], content=data['content']) … ▶ Local vars Kindly tell me what I am doing wrong as the examples I have seen previously regarding the same save method did … -
Cannot delete an item from the Django admin interface
We used the Django admin interface to create some content (a 'Talk' model) and upload a file. The upload failed with a Server Timeout Error (500). Now, we cannot delete or even click on the talk in the admin interface. See screenshot: When we click on the item, we get a Server Error (500) message and Django outputs the following to our log files: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/template/base.py", line 850, in _resolve_lookup (bit, current)) # missing attribute django.template.base.VariableDoesNotExist: Failed lookup for key [non_field_errors] in None DEBUG 2021-10-23 07:29:00,382 base 128 140297891723008 Exception while resolving variable 'non_field_errors' in template 'admin/change_list.html'. Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] TypeError: 'NoneType' object is not subscriptable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/template/base.py", line 837, in _resolve_lookup current = getattr(current, bit) AttributeError: 'NoneType' object has no attribute 'non_field_errors' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/template/base.py", line 843, in _resolve_lookup current = current[int(bit)] ValueError: invalid literal for int() with base 10: 'non_field_errors' When we try to delete the item, we receive a slightly different error: Traceback (most … -
Django, Can not import urls from django.conf.urls
I am working on django restframework project. I build it and it was working well but then I tried makemigrations and I got following error. Please help me. File "/code/eventful/manage.py", line 22, in <module> main() File "/code/eventful/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 412, in execute self.check() File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 438, in check all_issues = checks.run_checks( File "/usr/local/lib/python3.10/site-packages/django/core/checks/registry.py", line 77, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/usr/local/lib/python3.10/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python3.10/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/usr/local/lib/python3.10/site-packages/django/urls/resolvers.py", line 446, in check for pattern in self.url_patterns: File "/usr/local/lib/python3.10/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.10/site-packages/django/urls/resolvers.py", line 632, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python3.10/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.10/site-packages/django/urls/resolvers.py", line 625, in urlconf_module return import_module(self.urlconf_name) File "/usr/local/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, … -
How to make some Django Inlines Read Only
I'm using django admin and adding a TabularInline to my ModelAdmin class. Think Author and the inline is Books. How do I make some of those inlines appear read only and some appear editable based on certain characteristics of the model instance for each specific inline? Say I wanted all the books written before 2001 to be read only. And all the books written after that to be editable. I've tried overriding has_change_permission() and using the obj param, but it is receiving the parent and not the instance of this specific inline. -
how to use request.GET.get() with JsonResponse view - django
i want to create a query base on two dates, i'm using one view for json response, and another view for the template def dateTimePrice(request): start = request.GET.get('from') end = request.GET.get('to') print(start,end)#print None if start and end: datetimes = ImeiInvoice.objects.filter(invoice__created_at__range=(start,end)).annotate( total_price=Sum( (F('price')) - F('discount'),output_field=DecimalField(max_digits=20,decimal_places=3)) ).annotate( total_quantity=( Count('pk') ) ).aggregate( all_price=Sum(F('total_price')), all_qnt=Sum(F('total_quantity')) ) else: datetimes = ImeiInvoice.objects.all().annotate( total_price=Sum( (F('price')) - F('discount'),output_field=DecimalField(max_digits=20,decimal_places=3)) ).annotate( total_quantity=( Count('pk') ) ).aggregate( all_price=Sum(F('total_price')), all_qnt=Sum(F('total_quantity')) ) return JsonResponse(datetimes,safe=False) @login_required def dateTimePriceTemp(request): return render(request,'myapp/datetimes.html') and here is my template <form action="" method="GET"> <div class="col-11 p-1 mt-1 mx-auto text-center row rtl "> <p class="col-12 col-sm-6 mx-auto text-left row"> <img src="icons/date.svg" class="ml-1" alt=""> from <input type="date" class="form-control col-9 mr-1" name="from" id=""> </p> <p class="col-12 col-sm-6 mx-auto text-right row"> <img src="icons/date.svg" class="ml-1" alt=""> to <input type="date" name="to" class="form-control col-9 mr-1" id=""> </p> <button class="btn btn-info col-8 col-sm-5 col-md-3 mx-auto">گەڕان</button> </div> </form> i returned the data with ajax call, it works fine, but i dont know to get from and to values from the template!? i much appreciate your helps .. -
How can I set the accepted content type in django view
I have some views made in Django. I have realised that the endpoints do not fail with an unsupported media type if I call them with, for instance, binary data instead of json (they only accept json). So, my doubt is: how can I specify the allowed content type of an endpoint in django to make it return a 415 error code? Do I need to implement that logic by hand with a middleware? -
Celery beat sends scheduled task only once and then doesn't send task when restarted
I am using Celery beat to perform a task that is supposed to be executed at on specific time. I was trying to excute it now by changing the time just to see if it works correctly. What I have noticed is it sends the task correctly when I run a fresh command that is celery -A jgs beat -l INFO but then suppose I change the time in the schedule section from two minutes or three minutes from now and then again run the above command, beat does not send the task. Then I noticed something strange. If I go to the admin area and delete all the other old tasks that were created in the crontab table, and then run the command again it sends the task again to the worker. The tasks are being traced by the worker correctly and also the celery worker is working correctly. Below are the codes that I wrote to perform the task. celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings from celery.schedules import crontab from django.utils import timezone from datetime import timezone # Set the default Django settings module for the 'celery' program. … -
send_mail Django send as alias email
I'm solving problem, that of course I'm sending an email like sender email, which I authenticated in settings.py, but what if I want to send and email as request.user.email alias? send_mail("Hello", "hello", settings.EMAIL_HOST_USER, [settings.EMAIL_RECEIVER]) is this some reason how to do that? Thanks a lot -
How to pass a cognito generated token while using graphene snapshot testing in django?
i'm just trying to pass HTTP_AUTHORIZATION token to test all my queries and mutations and just getting an error token has not been passed since it needs to get the context of logged in user, i just want to pass hard coded token for now in the Graphene test client query, Any leads appreciated , Thanks :) heres is what i'm trying to achieve: class PostTest(TestCase): def getAllPosts(self): client = Client(schema) self.assertMatchSnapshot(client.execute( """ query{ getPost(first:10){ edges{ node{ title description isLiked } } } } """, context = {"HTTP_AUTHORIZATION:"**HERE IS THE COGNITO GENERATED TOKEN**" ))