Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Control UUID as PrimaryKey in Django
I want to see the entire history of the object in the logs (starting with the creation request). Therefore, in the middleware, I assign a UUID to each request. If this is a request to create an object, then I want the UUID of the request to become ID of the object. I'm doing something like this: # middleware.py <...> def __call__(self, request): id = uuid.uuid4() request.id = id self.log_request(request) response = self.get_response(request) self.log_response(response) return response # then I insert the UUID into the request body, but it doesn't seem to be necessary <...> # models.py class Client(models.Model): id = models.UUIDField(primary_key=True, editable=False) phone = models.CharField(max_length=11, unique=True) operator_code = models.CharField(max_length=3, db_index=True, blank=True) def save(self, *args, **kwargs): if not self.id: self.id = kwargs.get("id", uuid.uuid4()) self.operator_code = self.phone[1:4] super().save(*args, **kwargs) But it doesn't work # app.log api.middleware INFO 2024-02-07 11:34:19,641 middleware API Request: POST /api/v1/clients/, 4b3e7620-cbb8-47b6-88b5-cb8111b3536b Body: {'phone': '01234567890', 'id': '4b3e7620-cbb8-47b6-88b5-cb8111b3536b'}, Headers: {...} api.middleware INFO 2024-02-07 11:34:19,657 middleware API Response: Status Code: 201, Body: {'id': '0ecbe66a-e6f3-452c-9ce0-ecd042bbe1e3', 'phone': '01234567890', 'operator_code': '123'}, Headers: {...} You can see that UUID are different. Is there any solution to my problem? -
How can I implement DRY on my Django views that do very similar things but on different targets?
I am implementing a social network project on Django. 2 of my models, have the following fields. class Profile(models.Model): user = models.OneToOneField(User... followers = models.ManyToManyField(Profile... class Post(models.Model): owner = models.ForeignKey(Profile... content = models.CharField(... likes = models.ManyToManyField(Profile... Now I created add_likes, add_followers, and edit_post views and they are very similar to each other. Here is a rundown of what they do: add_likes Receive a JSON object with a "target_post_id" and a boolean "like_status" (for Like or Unlike) Check validity JSON object and convert it to python objects Check if target_post exits Check is user profile does not own the post Add or Remove user profile to Post.likes based on like_status Return JsonResponses based on result (success or reason for failure) add_followers Receive a JSON object with a "target_profile_id" and a boolean "follow_status" (for Follow or Unfollow) Check validity JSON object and convert it to python objects Check if target_Profile exits Check if target is not own user profile Add or Remove user profile to Profile.followers based on follow_status Return JsonResponses based on result (success or reason for failure) edit_post Receive a JSON object with "target_post_id" and "new_content" Check validity JSON object and convert it to python objects Check if target_post exits … -
CrispyError : as_crispy_field got passed an invalid or inexistent field for email field only
I can't expose Email field from User model in django, If I remove email field from register.html there is no error. Also if I use {{ form }} It does not show the email field. It shows username, password1 and password2 with no error. models.py: from django.contrib.auth.models import User class Profile(models.Model): profile_pic = models.ImageField(null=True, blank=True, default='default.jpg') # FK user = models.ForeignKey(User, max_length=10, on_delete=models.CASCADE, null=True) forms.py: from django.contrib.auth.models import User class CreateUserForm(UserCreationForm): class Meta: model = User fields= ['username','email', 'password1', 'password2'] views.py: from .forms import UserCreationForm def register(request): form = UserCreationForm() if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect("my-login") context = {'form': form} return render(request, "register.html", context=context) register.html {% load static %} {% load crispy_forms_tags %} . . . <form action="" method="POST" autocomplete="off"> {% csrf_token %} {{ form.username|as_crispy_field }} # error is here {{ form.email|as_crispy_field }} {{ form.password1|as_crispy_field }} {{ form.password2|as_crispy_field }} <input type="submit" value="submit" /> </form> Django 4.2.10 django-bootstrap4 24.1 django-crispy-forms 1.14.0 pillow 10.2.0 wheel 0.42.0 -
How to implement custom ordering with cursor pagination in Django Rest Framework
I am trying to use cursor pagination (because count(*) takes too long) but I already have some code that implements custom ordering. #view.py class BookViewSet(ModelViewSet): serializer_class = BookSerializer queryset = Book.objects.all() pagination_class = BookCursorPagination filterset_class = BookFilterSet filter_backends = [filters.DjangoFilterBackend] #pagination.py class BookCursorPagination(CursorPagination): page_size = 10 ordering = 'id' # Specify the field by which you want to paginate ordering_param = 'ordering' # The parameter for specifying ordering in the URL def get_ordering(self, request, queryset, view): """ Return the field or fields to use for ordering the queryset. """ ordering = request.query_params.get(self.ordering_param) if ordering: return ordering.split(',') return self.ordering.split(',') #filters.py from django.db.models import F, QuerySet, Func from django_filters import rest_framework as filters from django_filters.constants import EMPTY_VALUES from poll.models import Book class BookCustomOrderingFilter(filters.OrderingFilter): def filter(self, qs: QuerySet, value): if value in EMPTY_VALUES: return qs if any(v in ['test_ordering', '-test_ordering'] for v in value): qs = qs.annotate( author_length=Func(F('author'), function='LENGTH') ) return qs.order_by("author_length", "id") return super().filter(qs, value) class BookFilterSet(filters.FilterSet): ordering = BookCustomOrderingFilter( fields=( ("test_ordering", "test_ordering") ), ) How do I use 'test_ordering' along with Cursor pagination? -
custom column type for django create DB cache table command
I’m currently working with a PostgreSQL database and I want to use a timestamp of type ‘timestamp(0)’. To achieve this, I’ve created a custom column type using the following code: class DateTimeWithoutTZField(DateTimeField): def db_type(self, connection): return 'timestamp(0)' My question is: How can I use this custom ‘timestamp(0)’ type with the DB cache table that is created by running the Django command python manage.py createcachetable -
django using oauth2.0, getting error {"error": "invalid_grant"} when trying to get access token
Following this tutorial, https://django-oauth-toolkit.readthedocs.io/en/latest/getting_started.html on step curl -X POST -H "Cache-Control: no-cache" -H "Content-Type: application/x-www-form-urlencoded" "http://127.0.0.1:8000/o/token/" -d "client_id=${ID}" -d "client_secret=${SECRET}" -d "code=${CODE}" -d "code_verifier=${CODE_VERIFIER}" -d "redirect_uri=http://127.0.0.1:8000/noexist/callback" -d "grant_type=authorization_code" I'm getting an error: {"error": "invalid_grant"} I have checked everything twice, and even re-assembled the app from the ground up as in tutorial, it still gives the error. Please help, thank you! -
Title: Issue with Generating ID for New Address Object
I'm encountering an issue in my project where the ID for a new address object is not being generated as expected when adding a new address. Below is the relevant code snippet from my project: models.py: class Address(EmbeddedDocument): id = fields.ObjectIdField(required=True, default=fields.ObjectId) line1 = fields.StringField() line2 = fields.StringField() city = fields.StringField() state = fields.StringField() zip_code = fields.StringField() class UserExt(Document): addresses = fields.ListField(field=fields.EmbeddedDocumentField(Address)) usercontroller.py: @api_view(["POST"]) def add_address(request, userId): try: data = request.data new_address_id = user_service.add_address(data, userId) return Response({"message": "Address added successfully", "address_id": new_address_id}, status=201) except Exception as e: return Response({"message": str(e)}, status=400) services.py def add_address(data, userId): new_address = repo.add_address(data, userId) return new_address user_repository.py def add_address(data, userId): try: connection = conn_db() new_address = data.get("addresses") # Access the new address data if new_address: result = connection.get_collection("user").update_one( {"_id": ObjectId(userId)}, {"$push": {"addresses": new_address}} ) if result.modified_count > 0: return {"message": "New address added successfully"} else: raise Exception("Failed to add new address") else: raise Exception("No address data provided") except Exception as e: raise e { "id": "65c26ed05186a91e4ef3d7c6", "line1": "abc", "line2": "xyz", "city": "palanpur", "state": "Gujarat", "zip_code": "385515" } Current output: { "line1": "pqr", "line2": "lmn", "city": "gandhinagar", "state": "Gujarat", "zip_code": "382028" } -
Python Django Admin site Custom Query Set
Background I have a Usergroup model class UserGroup(models.Model): name = models.CharField(max_length=255, unique=True) users = models.ManyToManyField(User, blank=True) def __str__(self): return self.name I want to add this on Django’s admin site so that a admin can create User groups and also assign Users to Usergroups A user should only be allowed to be in one User group A user also doesn’t have to be in a group Dont want a usergroup field on my User Model Below is what I have for my admin site at the moment. class UserGroupAdmin(admin.ModelAdmin): list_display = ('name',) search_fields = ('name',) filter_horizontal = ('users',) admin.site.register(UserGroup, UserGroupAdmin) It looks like this when Creating a group adding users ect. My thought was to change the query set to only show Users who are not in a Group and the users who are currently in the group Which means. Under Available Users You will only be allowed to Add / see users who are not yet in a group. Under Chosen User View Users already in this current Group. Question Im not sure how to approach changing the Query set. The below Works great to only show Users not in a group. But now I cant see Users already in … -
Gunicorn not able to load up Global Variables
I have a Django project deployed with Gunicorn configured in the backend, the project generates several files every day for 4 different services (let's say service A, B, C, and D), and the files are named as servicename_date the date is being picked up by a global variable TODAY. from datetime import date TODAY = date.today().isoformat() def func_A(): df.to_csv(os.path.join(os.getcwd(), "data","service_A" + "_" + TODAY + ".csv"), index=False) def func_B(): df.to_csv(os.path.join(os.getcwd(), "data","service_B" + "_" + TODAY + ".csv"), index=False) def func_C(): today = date.today().isoformat() df.to_csv(os.path.join(os.getcwd(), "data","service_C" + "_" + today + ".csv"), index=False) def func_D(): today = date.today().isoformat() df.to_csv(os.path.join(os.getcwd(), "data","service_D" + "_" + today + ".csv"), index=False) and this global variable is used in different functions in the same file. The problem is the value of TODAY is not always correct on the server. Sometimes it is correct I,e Today's date sometimes it picks up previous dates. The problem only occurs with the services that use Global variables I,e Service A and B, other services that use variables initialized inside their specific function don't face this issue I,e Service C and D. I have tried to replicate this issue on my local however wasn't able to replicate the issue. -
How can I know which browser is called by MY script on the server
My web project is deployed on the server and users can upload scripts and click the run button to run the script and call the browser on the server. Now there are multiple users running their own scripts, calling the browser on the server, and then logging in to the server to check the browser's performance, enter image description here How can I know which browser is called by MY script? -
Please help me with this simple Django app that uses 2FA integration with Duo
I'm a junior Python developer with less than a year's experience in Python. I've been given a task to create a login page using Django and then integrate it with Duo for 2 factor authentication. I've managed to create a simple login page with 1FA, but I'm stuck on trying to incorporate Duo into it. Here's a link to the code which I've got - https://github.com/TheLoneWayfarer/django-duo.git I'm quite new to this, so please let me know if you need any more info or if anything in the links is not accessible. The expecation is that the user visits the /duo/login endopoint, provides their details, it directs them to the Duo 2FA page where they get authenticated, and then it needs to go to the home.html page. I'm using this package for Duo - https://pypi.org/project/django-duo-universal-auth/ I've done everything in the link like add the parameters to the settings.py file and add the path into the urls.py file, but I'm getting this error when I try to log in : {"error": "invalid_grant", "error_description": "Invalid redirect URI 'http://127.0.0.1:8000/duo/callback/'."} I'm not sure what I'm missing, so any guidance would be much appreciated. -
Django Filter row by ManyToManyField so that all m2m are a sublist of a list
I have a list [1,2,3,4] and a django model with a manytomany field id If id can contain [1,2,3] or [1,5] How can I return the objects that contain a substring of my list [1,2,3,4] and not anything outside that list [1,5]. I've seen this Django filter queryset __in for *every* item in list. But I only want to return a substring -
How to use if else condition using mathfilters in Django?
I have a question, I'm doing a project in Django and there is a part of the application called Pagos(payments), there I show the following: payments made, total_pagos(total payment) and pending payment, To show the information of these payments I'm using mathfilters because addition and subtraction are used in my templates. For the template it's showing the information properly, only the problem comes when I want to use conditionals since once pending payment is equal to 0.00 it means that the client already pays everything and must show a text that says “PAGADO” (paid), when pending payment it has another number than 0.00 must show a label that says “PENDIENTE” (pending). This is the code that I am using and it works, since it shows me the result of the costo_servicio (amount of the service) cost minus the total_pagos (total payments), whatever it shows is the pending payment, it can show several numbers or 0.00: {% for juicio in juicios %} {{ juicio.costo_servicio|sub:total_pagos }} {% endfor %} But if I put this, it doesn't show the if and therefore doesn't do the subtraction or show the text PAGADO(paid): {% for juicio in juicios %} {% if juicio.costo_servicio|sub:total_pagos == 0.00 %} … -
How can I restrict the images selectable by the user in Wagtail's ImageChooserBlock?
Some image content on my Wagtail site must meet certain requirements (e.g. a differing minimum size for banner images, carousel images, etc.). I know I can validate my image requirements after the edit form data is submitted, but I'd like to make the workflow more user-friendly by restricting the widget to only show images that will pass validation in the first place. What is the best way to go about this? Wagtail 5.2.2 -
Django REST Framework (DRF)'s FileField behave differently in generics view and APIView
I want handle file upload in django. The Model and Serializer are as follow: def save_file(instance, filename): _, ext = os.path.splitext(filename) return f"{instance.id}{ext}" class FileModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=64) file = models.FileField(upload_to=save_file) created = models.DateTimeField(auto_now_add=True) class FileModelSerializer(serializers.ModelSerializer): class Meta: model = FileModel fields = "__all__" When I use generics view like this: class FileListApi(generics.ListAPIView): queryset = FileModel.objects.all() serializer_class = FileModelSerializer The API will be like this, the url is absolute path: [ { "id": "2c5488ec-7b5d-45ab-9c43-058c19d76626", "title": "file.png", "file": "http://127.0.0.1:8000/media/2c5488ec-7b5d-45ab-9c43-058c19d76626.png", "created": "2024-02-07T02:29:29.845808Z" } ] However when I use APIView: class FileListApi(APIView): def get(self, request): serializer = FileModelSerializer(FileModel.objects.all(), many=True) return Response(serializer.data) The url is now relative path: [ { "id": "2c5488ec-7b5d-45ab-9c43-058c19d76626", "title": "file.png", "file": "/media/2c5488ec-7b5d-45ab-9c43-058c19d76626.png", "created": "2024-02-07T02:29:29.845808Z" } ] I can image there will be situations that require absolute path or relative path, in my particular case I want to use relative path. Why DRF behave differently in generics view and APIView? How to make DRF output url differently? -
i deploy a django-React app on fly.io, but the data in redux does not appear
I deploy this app in Fly.io, but when I access the url it shows me the templates and does not access the APIs, I am using redux and it shows everything null I do not know what is happening I'm stuck, i can't fix the problem -
How to add a schema under actions in django_rest_framework
`@api_view(['POST']) def createUser(request): print(to_jsonschema(UserSerializer())) serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=201) else: return Response(serializer.errors, status=400)` For example I would like for this to be returned { "name": "Token Refresh", "description": "Takes a refresh type JSON web token and returns an access type JSON web\ntoken if the refresh token is valid.", "renders": ["application/json", "text/html"], "parses": [ "application/json", "application/x-www-form-urlencoded", "multipart/form-data" ], "actions": { "POST": { "refresh": { "type": "string", "required": true, "read_only": false, "label": "Refresh" }, "access": { "type": "string", "required": false, "read_only": true, "label": "Access" } } } } This is from an built in view from rest_framework_simplejwt. Overall I would like to add a schema such as the actions data which shows for the method post refresh and access are required. I want something like this for my createUser view as I can easily see what attribute the api endpoint takes for example username or password, I looked online and found this https://www.django-rest-framework.org/api-guide/metadata/ but I couldn't get it to work. I looked at other solutions also but they were just showing to create a different view which sends a JSON schema back as get request. Overall I just want something simple that I can easily use to communicate … -
Implement tabs with htmx
I want to implement simple tab functionality with htmx for a Django template. I know of the django_htmx package, but I chose to use htmx directly and I’m now having trouble implementing the tab functionality. I tried using the example from the htmx website using JavaScript but I’m having trouble, all the prospective tabs are divs on the same page. -
Django update_or_create within a loop is duplicating field values, but just a couple fields
It's been a while but I have a somewhat puzzling issue. I am looping over some data being pulled from an api and performing an update_or_create call through django. for product in response['products']: for variant in product['variants']: print(variant['product_id']) obj, created = Product.objects.update_or_create( sku=variant['sku'], defaults={ 'name': product['title'], 'price': variant['price'], 'sku': variant['sku'], 'shopify_product_id': variant['product_id'], 'shopify_variant_id': variant['id'], 'weight_grams': variant['grams'], }, ) During the loop you'll notice I am printing the value of the variant product id. print(variant['product_id']) In the console I see the print results are correct with different variant product ids. 7396903682207 7405275381919 7405275775135 7405273579679 7405278101663 7396921475231 9034125279391 But in the database both the variant['product_id'] and variant['id'] are all the same for every row. Yet the other details such as name and price are all correct and differ per row. I can not for the life of me figure out why this is happening. I am using the sku as the unique identifier to filter on and it is set as unique in my model. No matter what I do or try, it is only those two fields that get duplicated. -
django autofill inlineformset_factory
first of all ,i'm start usin django a few mounth ago also i'm not good using english language so sorry in the first place i've create models like this class Project(models.Model): def __str__(self): return self.name name=models.CharField(max_length=80) class champs(models.Model): def __str__(self): return self.nom def ImageSet(instance,nom): return """/project_manager/static/projects/{}_{}""".format(instance.id,nom) name=models.CharField(max_length=50,unique=True) ordre=models.IntegerField(default=999) illustration=models.ImageField(upload_to=ImageSet, height_field=None, width_field=None, max_length=None,blank=True,null=True) parent=models.ForeignKey(Project, verbose_name="projet", on_delete=models.CASCADE) class commade(models.Model): def __str__(self): return self.description clientFirstName=models.CharField(max_length=50) clientLastName=models.CharField(max_length=50) addres=models.CharField(verbose_name="adresse de l'intervention", max_length=300) email=models.EmailField(max_length=254) tel=PhoneNumberField(blank=True) date_d_intervention=models.DateTimeField(auto_now=False, auto_now_add=False,verbose_name="date d'intervention") project = models.ForeignKey(Project, on_delete=models.CASCADE) description=models.TextField() class Response(models.Model): def __str__(self): return self.champs.name commande=models.ForeignKey(commade, on_delete=models.CASCADE) champs=models.ForeignKey(champs, on_delete=models.CASCADE) valeur=models.CharField( max_length=80) i've create django admin were i can autofill inlineformset of response model champs with values of which have the same project before i choose the project when i chose the project now what i need is how to make it using inlineformset_factory in django forms.py or usin views.py without using js or jquery for security purpos can you teach me please thanks in advence -
How to not save a Django model if certain conditions are not met, and display an error message in the console page
In Django what is the best way to not save a model if certain conditions are met and stay on the change page, and display a custom Django error message in the console -
Input Json data in django models
I have a json file with a huge number of data in it, I have also created a django model to store that data and now I can't figure out how to put that json data into my models. Doing it manually will consume a lot of my time. However, I can use models.JSONField to put that data but that's not what I want. I want to put each data in a model field. Here's a sample of my JSON data: [ { "end_year": "", "intensity": 6, "sector": "Energy", "topic": "gas", "insight": "Annual Energy Outlook", "url": "http://example.com", "region": "Northern America", "start_year": "", "impact": "", "added": "January, 20 2017 03:51:25", "published": "January, 09 2017 00:00:00", "country": "United States of America", "relevance": 2, "pestle": "Industries", "source": "EIA", "title": "Test phase", "likelihood": 3 } ] And this is my model: class myModel(models.Model): end_year = models.PositiveIntegerField(null=True, blank=True) intensity = models.PositiveSmallIntegerField(null=True, blank=True) sector = models.CharField(max_length = 255, null=True, blank=True) topic = models.CharField(max_length = 55, null=True, blank=True) insight = models.TextField() url = models.URLField(max_length = 300) region = models.CharField(max_length = 50, null=True, blank=True) start_year = models.PositiveIntegerField(null=True, blank=True) impact = models.CharField(max_length = 255, null=True, blank=True) added = models.DateTimeField(null=True, blank=True) published = models.DateTimeField(null=True, blank=True) country = models.CharField(max_length = 50, … -
<django.db.models.query_utils.DeferredAttribute object at ... > instead of data value in PostgreSQL database
I am trying to display a value on an html page but the value is just returning as <django.db.models.query_utils.DeferredAttribute object at ... >. The issue is the variable 'card_name'. This is my code files from my Django project: Models.py: class mProSet1990(models.Model): Image = models.CharField(max_length=255, primary_key=True) Card = models.CharField(max_length=255) class Meta: managed = False db_table = '1990 Pro Set' Views.py: def ProSet1990_1(request): # Fetch the card details from the database card_1 = mProSet1990.objects.get(Card="David Seaman #1") # Use the web scraping bot to get the lowest card price lowest_price = get_lowest_card_price(f'{mProSet1990.Set} {mProSet1990.Card}') # Pass the data to the template context = { 'card_1': card_1, 'card_name': mProSet1990.Card, 'lowest_price': lowest_price, } # Render the template with the data return render(request, 'Application/ProSet1990_1.html', context) ProSet1990_1.html body: <body> <h1>{{ card_name }}</h1> {% if lowest_price %} <p>Lowest Price: {{ lowest_price }}</p> {% else %} <p>Price not available</p> {% endif %} </body> mProSet1990.Set and mProSet1990.Card are not pulling the actual values, they are returning as <django.db.models.query_utils.DeferredAttribute object at ... >. -
How do I handle multiple user selected actions when updating my database via CSV?
I'm working on a database of shows which has models for Actors, Characters, and Shows. I'm trying to implement a Bulk Upload feature that accepts a CSV file. I'm starting with bulk uploading shows, here's the relevant model: class Show(models.Model: title = models.CharField(max_length=2083, blank=True, null=True) blurb = RichTextField(blank=True) website = models.CharField(max_length=2083, blank=True, null=True) host = models.ManyToManyField('Host', through='ShowHosts', blank=True) Currently, when the file is submitted, the site checks the 'Title' and 'Host' fields against existing records in the database and, if there are no duplicates, it creates a new instance of the 'Show' and 'Host' and assigns the new 'Host' to the new 'Show'. Where I need assistance is what happens when a duplicate is found. This is how I'd like to handle it: The user is redirected to a new page containing a table. Each row has three columns; the first contains a dict consisting of the uploaded info for the new show, the second contains the Model Object of the duplicate Show/Host that was found in the database already, the third is a element prompting the user to choose how they'd like to handle the duplicate. Here's an example of the results when one of the rows of the … -
Django @csrf_exempt a logging endpoint
I'm making a social media site where users click into posts, and every time they do so, I call an endpoint to log a view for that post. Would it be safe to csrf_exempt this endpoint that only fetches a Post object from a slug and increases the post's view_count by 1?