Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I use custom filters inside ViewSet views? Django DRF
I have made a custom filter # filters.py class CustomFilter(filters.BaseFilterBackend): def filter_queryset(self, request, queryset, view): if view.action == 'list': # here's additional filtering of queryset return queryset And now I don't understand, how to apply this filter to my queryset inside the view? # views.py class EventViewSet(ViewSet): filter_backends = [CustomFilter] serializer_class = MySerializer def list(self, request): raw_queryset = MyModel.objects.all() filtered_queryset = # here's should be called filter from filter_backends serializer = MySerializer(filtered_queryset , many=True) return Response(serializer.data) -
In python Django I want to run two statements on if else that is if email is taken show it or if username is taken show it
I have a html registration page where I am displaying if any username or email exists or not so if it exists then display username is taken and if email exists it will display email is taken but the problem is even if I give email in the email field in the html form it says username is taken but not email I tried elif statement it didn't worked the username is taken is working perfectly but not email. I mean both statements should run individually If anyone knows please help This is my views.py def Register(request): try: if request.method == 'POST': username = request.POST.get('username') email = request.POST.get('email') password = request.POST.get('password') try: if User.objects.filter(username = username).first(): messages.success(request, 'Username is taken.') return redirect('/register/') if User.objects.filter(email = email).first(): messages.success(request, 'Email is taken.') return redirect('/register/') user_obj = User(username = username , email = email) user_obj.set_password(password) user_obj.save() profile_obj = Profile.objects.create(user = user_obj ) profile_obj.save() return redirect('/login/') except Exception as e: print(e) except Exception as e: print(e) return render(request , 'register.html') -
Django cannot use order_by when annotating
Am using TrucDate to get count by date for the last 1000 records: test_data = RequestModel.objects.filter(user_id=info.context.user.id).order_by('-id')[:1000] .annotate(date=TruncDate('date_created')).values('date').annotate(c=Count('id')).values('date', 'c') The issue is that it is not counting correctly, am having only 1 as count Output: <QuerySet [{'date': datetime.date(2021, 5, 28), 'c': 1}, {'date': datetime.date(2021, 5, 2), 'c': 1}, {'date': datetime.date(2021, 5, 2), 'c': 1}, {'date': datetime.date(2021, 4, 27), 'c': 1}, {'date': datetime.date(2021, 4, 27), 'c': 1}, {'date': datetime.date(2021, 4, 27), 'c': 1}, {'date': datetime.date(2021, 5, 8), 'c': 1}, {'date': datetime.date(2021, 4, 18), 'c': 1}, {'date': datetime.date(2021, 4, 28), 'c': 1}, {'date': datetime.date(2021, 5, 8), 'c': 1}, {'date': datetime.date(2021, 5, 8), 'c': 1}, {'date': datetime.date(2021, 5, 2), 'c': 1}, {'date': datetime.date(2021, 1, 1), 'c': 1}]> However if I remove the order_by('-id')[:1000] from the query I get the count correctly, but, I want to have last 1000 not whole querySet test_data = RequestModel.objects.filter(user_id=info.context.user.id).annotate(date=TruncDate('date_created')).values( 'date').annotate(c=Count('id')).values('date', 'c') Output: <QuerySet [{'date': datetime.date(2021, 1, 1), 'c': 1}, {'date': datetime.date(2021, 4, 18), 'c': 1}, {'date': datetime.date(2021, 4, 27), 'c': 3}, {'date': datetime.date(2021, 4, 28), 'c': 1}, {'date': datetime.date(2021, 5, 2), 'c': 3}, {'date': datetime.date(2021, 5, 8), 'c': 3}, {'date': datetime.date(2021, 5, 28), 'c': 1}]> How can I count by date for the last 1000 records? -
DRF SerializerMethodField not getting called
This is my serializer: class MetaDataSerializer(serializers.Serializer): bg_colors = ColorSerializer(Color.objects.all(), many=True) button_choices = serializers.SerializerMethodField() class Meta: fields = ('bg_colors', 'button_choices') def get_button_choices(self, obj): return { 'save': 1, 'continue': 2, 'cancel': 3, 'back': 4 } I'm calling this serializer from my view like this: class MetaDataView(RetrieveAPIView): serializer_class = MetaDataSerializer def get(self, request, *args, **kwargs): return Response(self.get_serializer().data) In the response I'm getting only the bg_colors field. The other field is absent from response, and its get_field method is also not called. What am I doing wrong here? -
How to generate Qrcode from data and make all Qrcode images to single PDF within one view in Django?
I need to generate Qrcode images from database objects and make all QRcode images as single pdf in one view in Django. Thanks in advance. -
How to add multiple number of module in one cart (Django)
I'm using PostgresSQL as DB, Django as backend and HTML, CSS, Javascript as Frontend. I have Multiple number of product Modules and I want to add all those module in one cart. So, I had Successfully add One of the module in cart. But I want to add different products like Refrigerator, Fans, Washing Machine, ... etc. in one cart So, how it will work? The Codes goes here: models.py class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField(max_length=200) joined_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.full_name class Regrigeratior(models.Model): image_src = models.URLField(max_length=300,null=True, blank=True) name = models.CharField(max_length=200, db_index=True, verbose_name="processor name") brand = models.CharField(max_length = 300, null=True, blank=True) .... def __str__(self): return self.name class Fans(models.Model): image_src = models.URLField(max_length=300,null=True, blank=True) name = models.CharField(max_length=200, db_index=True, verbose_name="processor name") brand = models.CharField(max_length = 300, null=True, blank=True) .... def __str__(self): return self.name . . . class Cart(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) total = models.PositiveIntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return "Cart: " + str(self.id) # class CartProduct(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) refrigerator = models.ForeignKey(Refrigerator, on_delete=models.CASCADE) rate = models.PositiveIntegerField() quantity = models.PositiveIntegerField() subtotal = models.PositiveIntegerField() def __str__(self): return "Cart: " + str(self.cart.id) + " CartProduct: " + str(self.id) I have succesfully add Refrigerator Module in the cart … -
Atomic transaction to update pair of related objects at once
I have a simple task - mark all User's and its Profiles as "is_active", and I do it like this: users = User.objects.all().select_related('profile') for user in users: user_profile = user.profile user.is_active = True user_profile.is_active = True user.save() user_profile.save() Sometimes it corrupts data, so user's is_active and user.profile's is_active not always synced And the best plan I can think of is to wrap both .save()s into atomic transaction from django.db import transaction users = User.objects.all().select_related('profile') for user in users: user_profile = user.profile user.is_active = True user_profile.is_active = True with transaction.atomic(): user.save() user_profile.save() So, should it work?) The concern is - maybe whole block, including users = User.objects.all().select_related('profile') should be wrapped P.S. I can not use .update() due to complex logic inside -
I am just wondering if I can change primery key in django
I know django set primery key for the object automatically even if I don't do anything... it starts from 1 for first object created. I would like to have primery key start from 100, not 1. is it possible? if so, how could i set this up? -
Django dependent dropdown
So i want to get data from dependent dropdown but i get only the id value not the actual value of data. class Service(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) serv_type = models.ForeignKey(Servicetype,on_delete=models.CASCADE) serv_job_card_no = models.CharField(max_length=100) serv_job_loc = models.CharField(max_length=100,default='') serv_cost = models.CharField(max_length=100) serv_exp_date = models.CharField(max_length=100) class Servicetype(models.Model): serv_type = models.CharField(max_length=100) -
django async ORM sync_to_async executor swap out concurrent.futures.ThreadPoolExecutor when using gevent
The third kwarg that can be passed to asgiref's sync_to_async is an executor the executor is a type of concurrent.futures.ThreadPoolExecutor According to the documentation gevent.threadpool.ThreadPoolExecutor more or less inherits and wraps concurrent.futures.ThreadPoolExecutor Say for example I want to use a werkzeug DispatcherMiddleware, and wrap an ASGI app. Think FastAPI mounted to the inside of an older monolithic django WSGI app ( using eventlet / gevent / monkey patching ) Here's my attempt at doing it. https://github.com/rednaks/django-async-orm/pull/7/files Basically, how to get django async-ish ORM? try: from gevent.threadpool import ThreadPoolExecutor as GThreadPoolExecutor from django.conf import settings if settings.GEVENT_DJANGO_ASYNC_ORM: from gevent import monkey monkey.patch_all() def monkey_patch_the_monkey_patchers(ex): from .patch_gevent import _FutureProxy def submit(ex, fn, *args, **kwargs): # pylint:disable=arguments-differ print(fn, *args, **kwargs) with ex._shutdown_lock: # pylint:disable=not-context-manager if ex._shutdown: raise RuntimeError('cannot schedule new futures after shutdown') future = ex._threadpool.spawn(fn, *args, **kwargs) proxy_future = _FutureProxy(future) proxy_future.__class__ = concurrent.futures.Future return proxy_future ex.submit = submit return ex MonkeyPoolExecutor = monkey_patch_the_monkey_patchers(GThreadPoolExecutor) conf = {"thread_sensitive": False, "executor": MonkeyPoolExecutor(max_workers=1)} executor_ = MonkeyPoolExecutor except Exception as e: print(e) print('defaulting django_async_orm') pass And then called like: await sync_to_async(SomeModel.objects.all, **conf)() https://github.com/rednaks/django-async-orm/discussions/9 https://github.com/abersheeran/a2wsgi related: django 3.0 async orm with concurrent.futures.ThreadPoolExecutor() as executor: ... does not wait -
AttributeError: 'UserViewSet' object has no attribute 'user'
I've currently got an API endpoint that works as I would expect it when I send a request to it manually via Postman. I am now trying to setup unit tests using factory-boy but I'm not able to get it to work due to an error. So far, the important files with regards to the unit tests that I have are: urls.py from django.urls import include, path from rest_framework import routers from rest_framework.schemas import get_schema_view import views router = routers.DefaultRouter() router.register(r"user", views.UserViewSet, basename='user') urlpatterns = [ path('user', views.UserViewSet.as_view({'get': user}), name='user') ] test_user.py import factory from django.test import Client, TestCase from django.urls import reverse from factory import DjangoModelFactory, Faker from models.user import User class UserFactory(DjangoModelFactory): class Meta: model = User class UserViewSetTest(TestCase): def setUp(self): client = Client() def test_user_list(self): response = self.client.get(reverse('user'), format='json') self.assertEqual(response.status_code, 200) When running pytestusing the above, I get an error: AttributeError: 'UserViewSet' object has no attribute 'user' As I mentioned, I've been able to send a request via Postman to the API so I'm not sure it's useful to show my complete code (i.e. the ViewSet, models and serializers). For what it's worth, the viewset currently just returns a list of users in Json format. -
Unable to access uploaded image from aws S3 bucket through Django
I have successfully done the configuration of uploading images to s3 bucket through django settings.py file. this is my config: AWS_ACCESS_KEY_ID = '######################' AWS_SECRET_ACCESS_KEY = '###########################' AWS_STORAGE_BUCKET_NAME = 'divytrust-image' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' I am using Nginx+gunicorn on server. I am successfully able to upload image to s3bucket/pics But when I try to view the image from django admin panel, I get error: This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>InvalidRequest</Code> <Message>The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256.</Message> <RequestId>1F51EJV41QT73FSV</RequestId> <HostId>ZL9W4GqDXDbPluBsX+aC4FvRzVy0CLLjy6mXEPL8U/zAWSFzNi1tAQQixGIhbLgeADS1DV0Mv8c= </HostId> -
Check if a file exist in Django
I have created a newclaim.html and editclaims.html. newclaims.html allows me to upload a file while editclaims.html allows me to retrieve the file. Currently, I am able to retrieve the uploaded file but I want to do an if-else. I want to do an if-else that will delete the old file if a new file is uploaded This is my views.py **# Submit a new Claim** def newclaim(request): context = initialize_context(request) user = context['user'] if request.method == 'POST': receipt = request.FILES['receipt_field'] ins = SaveClaimForm(receipt=receipt) ins.save() print("The Data has been written") return render(request, 'Login/newclaim.html/', {'user':user}) # Edit a claim def editclaims(request,id): context = initialize_context(request) user = context['user'] # get original object claims = SaveClaimForm.objects.get(id=id) if request.method == 'POST': # update original object claims.receipt = request.FILES.get('receipt') # save it with original `ID` claims.save() return render(request, "Login/editclaims.html", {'claims':claims, 'user':user}) -
How can i use AWS SNS Https Endpoint i.e API of my backend server which running in Django?
I want to use my Backend API endpoint in AWS SNS Https endpoint but my backend API Development done in Django Restrframework and it's verifying access token also with the help of aws cognito . If i'll call my API from SNS Endpoint then my backend required access token which is authenticate by user pool of cognito in backend but how i can call my backend endpoint without verifying access token because i'm calling internal server api thatt will not call by user. Actually it will call by SNS Endpont. -
channels_presence.Presence.user: (fields.E300) Field defines a relation with model 'auth.User', which is either not installed, or is abstract
I am trying to use django channels_presence in my project but my user model is present in another project(microservice architechure) named auth which gives me the error: channels_presence.Presence.user: (fields.E300) Field defines a relation with model 'auth.User', which is either not installed, or is abstract. channels_presence.Presence.user: (fields.E307) The field channels_presence.Presence.user was declared with a lazy reference to 'auth.user', but app 'auth' isn't installed. How do I use channels_presence without User model in the same project? -
APITestCase. How to authenticate users outside of the test functions?
Background I used to authenticate users inside each test function Goal now I am trying to authenticate the user in the APITestCase class in order to use the same authentications in mutlable functions. Problem when I add the credentials in the class it seems not effecting the function? class TestTimeSheets(APITestCase): if (not User.objects.filter(username='newusername').exists()): user = User.objects.create( username='newusername', email='newusername@g.com', password='password', is_email_verified=True, is_role_verified=True, is_staff=True, is_superuser=True) else: user = User.objects.get(username='newusername') client = APIClient() lg_res = client.post('/users/login/', {'username': 'newusername', 'password': 'password'}, format='json') client.credentials( HTTP_AUTHORIZATION=f'Bearer {lg_res.data["access"]}') resp = client.get('/statistics/',) print('======================') print(resp.data) #🔴 this returns the correct data print('======================') def test_statstics(self): resp = self.client.get('/statistics/',) # self.assertEqual(create_res.status_code, status.HTTP_201_CREATED) print('======================') print(resp.data) #🔴 but this says you are not authenticated. print('======================') -
GeoDjango: How to create a circle anywhere on earth based on point and radius?
I have a similar question to this one. Using geodjango, I am wanting to draw a circle on a map with a certain radius in km. However, the suggested solution a) does not use km but instead degrees, and b) becomes an oval further north or south. Here is what I do: from django.contrib.gis import geos lat = 49.17 lng = -123.96 center = geos.Point(lng, lat) radius = 0.01 circle = center.buffer(radius) # And I then use folium to show a map on-screen: map = folium.Map( location=[lat,lng], zoom_start=14, scrollWheelZoom=False, tiles=STREET_TILES, attr="Mapbox", ) The result is this: How can I a) draw a circle that is always 3 km in radius, independent from the position on the globe, and b) ensure this is a circle and not an oval at all latitudes? -
django: setting up erlang and rabbitmq but some problem on window os for celery
I downloaded and installed erlnag (latest version:otp_win64_24.0) first and then intalled rabbitmq-server(3.8.16.exe). I tried to check if it works okay so I executed 'rabbitmq-server.bat' ( I did run this as administrator) but error, failed. another question, I would like to do some task, periodic task by celery on my project application. that's why I install this on my computer before deploying webserver. webserver system is ubuntu.... but I am doing this vertual environment anyway. so I think it should be no problem at all. am I right? I am just asking this just in case. -
How to download auto generated file in Django?
I am created a basic ocr system. When user uploads a PDF file to system I read it and created a xlsm file with the same name. I am using remote control with Azure (Windows). I created a download button. When I click it, downloads the file with same name, so it should work but appears a error. How can I fix this problem? <a href= "{% static path %}" class="btn btn-outline-primary btn-sm" download>Download Report File</a> in my views: name = pdf.pdf.name.replace(".xlsm", "").replace(".pdf", "") path = "C:/user/ocr/" + name + ".xlsm" Note: Uploaded and created files are stored outside of the project file. -
Django filter feature with ajax not working
I have a table for tracking job applications and im trying to implement a filter feature. I want to display the results with pagination. However, I am getting errors when trying to do so and can't seem to find my way out of it. I want the results to be displayed without the page being refreshed. Please help.... :((( Here is my code: template file <ul id="filter_list" class="dropdown-menu"> <li><a href="#">Alphabetical Order (A-Z)</a></li> <li><a href="#">Application Date (Ascending)</a></li> <li><a href="#">Application Date (Descending)</a></li> <li><a href="#">Closing Date</a></li> </ul> <div id="table_results"> <div> <script> $(".dropdown-menu a").click(function(){ var selected_filter = $(this).text(); $.ajax({ url:'{% url "stu_filter_applications" %}', data:{ "filter_category": selected_filter, }, dataType:'json', success: function (response) { //I want the page to not refresh here }, error: function (response) { console.log(response.errors); }, }); }); </script> views.py: def stu_filter_applications(request): if request.is_ajax(): filter_cat = request.GET.get("filter_category", None) student = StudentUser.objects.get(user=request.user) int_apps = InternshipApplication.objects.filter(student=student) int_app = [] applications = [] for app in int_apps: #for each application, grab the internship and the recruiter if filter_cat == "Alphabetical Order (A-Z)": internship = Internship.objects.get(id=app.internship.id) int_applications = InternshipApplication.objects.filter(student=student). order_by('internship.internship_title') if filter_cat == "Application Date (Ascending)": internship = Internship.objects.get(id=app.internship.id) int_applications = InternshipApplication.objects.filter(student=student). order_by('application_date') if filter_cat == "Application Date (Descending)": internship = Internship.objects.get(id=app.internship.id) int_applications = InternshipApplication.objects.filter(student=student). order_by('-application_date') if … -
Add ManytoMany in Django models
I am trying to add a m2m relationship with already created model objects like the following: class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) client_name = models.CharField(max_length=500, default=0) client_shipping_address = models.CharField(max_length=500, default=0,blank=True, null=True) class Group(models.Model): emp = models.ForeignKey(Employee, on_delete=models.CASCADE) name = models.CharField(max_length=500, default=0) groupmodels = models.ManyToManyField(GroupModels) sender_clients = models.ManyToManyField(Client) #### this one receiver_clients = models.ManyToManyField(ReceiverClient) warehouses = models.ManyToManyField(Warehouse) Here a group model can have multiple sender_clients. In my serializers I have added the Client serializer as well like the following: class GroupSenderClientSerializer(serializers.ModelSerializer): class Meta: model = Client fields = "__all__" read_only_fields = ('user',) class GroupsSerializer(serializers.ModelSerializer): groupmodels = GroupModelsSerializer(many=True) sender_clients = GroupSenderClientSerializer(many=True) ####this one receiver_clients = ReceiverClientSerializer(many=True) warehouses = WarehouseSerializer(many=True) class Meta: model = Group fields = "__all__" def create(self, validated_data): print("v data", validated_data) items_objects = validated_data.pop('groupmodels', None) sc_objects = validated_data.pop('sender_clients', None) rc_objects = validated_data.pop('receiver_clients', None) ware_objects = validated_data.pop('warehouses', None) prdcts = [] sc = [] rc = [] ware = [] for item in items_objects: i = GroupModels.objects.create(**item) prdcts.append(i) instance = Group.objects.create(**validated_data) print("sc objects", sc_objects) if len(sc_objects)>0: for i in sc_objects: print("id", i['id']) inst = Client.objects.get(pk=i['id']) sc.append(inst) if len(rc_objects)>0: for i in rc_objects: inst = ReceiverClient.objects.get(pk=i['id']) rc.append(inst) if len(ware_objects)>0: for i in ware_objects: inst = Warehouse.objects.get(pk=i['id']) ware.append(inst) instance.groupmodels.set(prdcts) instance.sender_clients.set(sc) instance.receiver_clients.set(rc) instance.warehouses.set(ware) … -
Having trouble getting a double header using HTML
I'm having trouble getting a double header set up. Both headers seem to be one on top of the other, especially when I inspect the header. This is on Django if that changes anything <body> <section><header class="site-header"> ... </header></section> <section><header class="site-header"> ... </header></section> </body> -
Search through hashids if it contains specific value Django-hashids
I am using django-hashids for my IDs and I have to have a search function that looks up the encoded IDs. Right now, this is how it works search_string = request.query_params.get(self.search_param, "") result = view.hashids.decode(search_string) But this one requires the whole hashid to return a specific value. If the hashid is for example qwerty123 I have to input the whole string so that I'll get the right item. Is there any way that even if I just input qwerty, it will return the IDs that contain the inputted string? -
Upload image using its URL and show it on frontend of website in Django
I am new to Django and I am working on a website that required me to upload lots of images because of which the overall size of my website increased to 500+ MB. I had already used Django Imagefield and store the uploaded image in my static folder from the admin panel, instead of that, I want to upload the image using URL from the admin panel and want to show that image into the frontend of my website. How can it be possible? Any help will be really appreciable. This is a code of my models.py class Place(models.Model): place_title = models.CharField(max_length=255) country = models.CharField(max_length=100,default=' ') location = models.CharField(max_length=100,default=' ') description = RichTextField() place_photo = models.ImageField(upload_to='photos/%Y/%m/%d/') place_photo_1 = models.ImageField(upload_to='photos/%Y/%m/%d/') place_photo_2 = models.ImageField(upload_to='photos/%Y/%m/%d/') place_photo_3 = models.ImageField(upload_to='photos/%Y/%m/%d/') place_photo_4 = models.ImageField(upload_to='photos/%Y/%m/%d/') is_recommended = models.BooleanField(default=False) one_strong_point_for_recommendations = models.CharField(max_length=100,default='In 2-3 words',blank='True') architecture = models.CharField(max_length=100) feature1 = models.CharField(max_length=100,default=' ') feature2 = models.CharField(max_length=100,default=' ') feature3 = models.CharField(max_length=100,default=' ') feature4 = models.CharField(max_length=100,default=' ') Explain_each_feature = RichTextField(default=' ') Reasons_to_visit = RichTextField(default=' ') story1 = RichTextField(default=' ') story2 = RichTextField(default=' ') story3 = RichTextField(default=' ') story4 = RichTextField(default=' ') Max_temperature = models.CharField(max_length=100,default='') Min_temperature = models.CharField(max_length=100,default='') sea_level = models.CharField(max_length=10000,default='') no_of_visitors = models.CharField(max_length=1000000,default='Around x million') closeness_of_the_destination = RichTextField() added_date = models.DateTimeField(default=datetime.now,blank=True) place_views … -
Modify field data from a different app on Django
In my website I'm working on I have custom user models in an app called users code: Views.py: from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): is_premium = models.BooleanField(default=False) points = models.IntegerField(default=0) classrooms = models.JSONField(default=dict) posts = models.JSONField(default=dict) admin.py: from django.contrib import admin from .models import CustomUser admin.site.register(CustomUser) This all works but I have a different app called files I need to modify the posts field in the CustomUser model from the views.py file in the files app. I think the answer to this has to do with foreign keys but for some reason I cannot wrap my head round them.