Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I have to add sms.to for sending otp in my django-rest-framework project . I didn't find any python package for that. how can i implement this?
In this project, I have to send opt to the user. I have to use 'sms.to', can someone tell me how I can do this? -
variable inside blocktranslate not shown up when makemessages
I make a simple template like this <button class="btn">{% blocktranslate %}{{ greeting }} Quy!{% endblocktranslate %}</button> with greeting equals hello. I have added the following MIDDLEWARE, and LANGUAGE_CODE = 'vi'. Everything else is left as default. 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', and LANGUAGE_CODE = "vi" TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.1/howto/static-files/ STATIC_URL = 'static/' # Default primary key field type # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' LANGUAGES = [ ('vi', _('Vietnamese')), ('en', _('English')), ] After running django-admin makemessages -l vi, the .po file is created msgid "%(greeting)s Quy!" msgstr "" I added # vi/LC_MESSAGES/django.po msgid "hello" msgstr "chào" or # en/LC_MESSAGES/django.po msgid "hello" msgstr "hi" and then run django-admin compilemessages but "hello" shown up instead of "chào" or "hi". Why I cannot translate the variable -
How can I design a Django Model with existing rows in one of the column?
I have a challenge with designing Django model that has existing rows in one of the column as shown below:- Gaming device in use Gaming Tax on GGR Tax Rate No of shop/places No of slot machines Total Value I have tried to create one Model with column attributes as fields but I don't figure out how to put number of shops/places and number of slot machines in my Model. -
Action to redirect users to URL
Could you tell me how to create an action in the admin site that will redirect users to a certain URL? That is, in the admin site a user chooses this action and finds themselves on Google. def google(modeladmin, request, queryset): """ I myself write some code here to prevent Django from asking users to select an object. """ URL = "https://google.com" ... Here goes the code to redirect the user to URL ... @admin.register(SemanticsCorePhrases) class SemanticsCorePhrasesAdmin(admin.ModelAdmin): actions = [google, ] -
Limit serializer by user
Here is my model serializer: class FoodImagesSerializerGet(serializers.ModelSerializer): current_user = serializers.HiddenField(default=serializers.CurrentUserDefault()) food = serializers.SlugRelatedField( many=False, read_only=False,slug_field='id', queryset=Food.objects.filter(users=current_user) ) Model: class FoodImages(models.Model): food = models.ForeignKey(FoodCourt, related_name='food_images', related_query_name='food_image', on_delete=models.CASCADE, null=True) class Food(models.Model): users = models.ManyToManyField( Profile, related_name='userfoods', related_query_name='userfood', ) I want to limit the serializer by users so only the users of the food can post images . I want to do that Just with the SlugRelatedField -
connection to server at "localhost" (127.0.0.1), port 5432 failed
I am facing this error "OperationalError at /results/ connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? connection to server at "localhost" (::1), port 5432 failed: Cannot assign requested address Is the server running on that host and accepting TCP/IP connections?" when I try to run a django application that I just deployed in railway.app. What is the problem and how can I fix? When I run the application locally it works well, it is my first time deploying a django application to production and I have no idea how to solve that issue, your help is greatly appreciated. -
What would be the best way to return the result of asynchronous task to Django views?
I am building a Djano app that processes image in a Celery task. A post inside the view method handles the input and triggers the task. Inside the task, I create a model instance based on the processed image. In the same view, I wanted to return a response of the de-serialization of the model instance. What is the best way to throw this response? Should a frontend expect this on another url? How can I signal my app that the model instance is ready to be served? # models.py class Image(models.Model): name = models.CharField(max_length=50, blank=True) ... # tasks.py @shared_task def long_running_function(user, data): image = Image.objects.create() ... return image # ? # views.py class RequestImage(APIView): def post(self, request): ... image = celery_task_example.delay( request.user.id, request.data ) # if image is ready serializer = ImageSerializer(image) return Response(serializer.data) -
URL.createObjectURL() providing url that redirects to 404 in AWS production env
I have a django application deployed on AWS EBS. I have a function that takes a blob and create URL of it so that I can download the pdf file from the site. The function is working perfectly on localhost but in prod environment the created url from URL.createObjectURL() is redirecting to the error page or 404 page. Im using nginx as the reverse proxy. I have checked the blob is valid and the django function is generating the pdf layout correctly. Below is my js code to build the pdf download link function showFile(blob){ var newBlob = new Blob([blob], {type: "application/pdf"}) if (!newBlob) { console.error("Blob object is not valid"); return; } // Create a link pointing to the ObjectURL containing the blob. const data = window.URL.createObjectURL(newBlob); console.log(data) var link = document.createElement('a'); link.href = data; link.open="file.pdf"; link.download = 'Calculation.pdf'; link.click() } the console.log(data) is returning https://<mydomain>/d6527ea6-5c1d-457a-bfb2-2b6aff01ae31 Any idea on how I can make it work in my prod env? Thank you I tried to log the flow and everything is returning correctly. So I am not sure what is the issue -
Django implement installable plugins at runtime
I want to made Django app that allows creation and then installation of plugins, or modules, for it, somewhat like you can do in CMS. Creator of plugin should define models, some configuration settings and handler functions for actions. Plugin will provide only REST api, so no templates required. Plugins must be installed at runtime - creator fills form, attaches archive with code, and plugin gets installed and activated. Unfortunately, my understanding of Django internals is way too low for this task. The most tricky part is runtime installation. There is answer how to install django app at runtime, but it feels hacky. Also, there is lib called django-pluggins, but it works with older version of Django and seems unmaintained. -
Enable support for django tags inside js
i currently have to use django template tags inside js. Example: <script> {% for od in object %} [convertDate("{{ od.date_recorded|date:'Y-m-d' }}"), {{ od.value_recorded }}], {% endfor %} </script> visual studio code shows error, is there a way to enable this support? -
While getting employee duration from joining to date.today() in Django query using F() objects and DurationField(), I am getting negative output
I am writing a query to get duration between 2 date fields. One is from django model (dateField) and other is simply datetime.date.today(). I have used F() objects for model column value to avoid memory usage. def duration(self): emp_duration = Employee.objects.values('empName', 'empJoining').annotate( duration=(datetime.date.today() - F('empJoining')) ) return HttpResponse(emp_duration) Output: {'empName': 'xyz', 'empJoining': datetime.date(2003, 1, 21), 'duration': -20028098.0} {'empName': 'Amna', 'empJoining': datetime.date(2022, 8, 9), 'duration': -20218786.0} {'empName': 'abc', 'empJoining': datetime.date(2022, 7, 17), 'duration': -20218694.0} Have a look at duration field. I dont understand why its in negative. Then I used ExpressionWrapper with outputfield as DurationField(). Since F() objects needs ExpressionWrapper to define outputFields. def duration(self): emp_duration = Employee.objects.values('empName', 'empJoining').annotate( duration=ExpressionWrapper( (datetime.date.today() - F('empJoining')), output_field=DurationField() ) ) return HttpResponse(emp_duration) Output: {'empName': 'xyz', 'empJoining': datetime.date(2003, 1, 21), 'duration': datetime.timedelta(days=-1, seconds=86379, microseconds=971902)} {'empName': 'Amna', 'empJoining': datetime.date(2022, 8, 9), 'duration': datetime.timedelta(days=-1, seconds=86379, microseconds=781214)} {'empName': 'abc', 'empJoining': datetime.date(2022, 7, 17), 'duration': datetime.timedelta(days=-1, seconds=86379, microseconds=781306)} Days difference is same in each row and not the right answer though. The substraction is not correct. What is the issue, if someone can give me better approach or point out what am I missing here, that will be a favor. Thanks -
Getting {"error": "invalid_grant" } in Django OAUTH when trying to generate a token using AUTHORIZATION CODE FLOW
I'm trying to access token using authorization code flow. Following documentation at Django OAuth Here's my code that's making the post request: curl --location --request POST 'http://127.0.0.1:8000/o/token/' \ --header 'Content-Type: application/x-www-form-urlencoded' \ --header 'Cache-Control: no-cache' \ --header 'Accept: application/json' \ --data-urlencode 'client_id=ngta3GGa3jP6Rmv5Tspj97Bk4aiitHgv1EQilCDS' \ --data-urlencode 'client_secret=zLwMyuXg7WCSFwUDYBxFP3QxHh5mF6xM2hBsKyvRbypac5lV7fl2NoFeeDG3afWWxLedA7qtzD2Mvf68qyBra3A4iUXXlDXJO4LvxuZv4UULU6NLWlObpD0ylQSXbwZD' \ --data-urlencode 'code=q4NfBMbyTNbcIQZ4j7SfgMWL898psv' \ --data-urlencode 'redirect_uri=http://localhost:8000/no/callback/' \ --data-urlencode 'code_verifier=b'\''SlJDWEgyRzNYMks0RTVQVDlRVkFaOFdDUkxHV1A3QURMTjNITFdaMTBLU0tWQkkzMUVWVEZFU0k='\''' \ --data-urlencode 'grant_type=authorization_code' I'm expecting to get an access token when I make the post request, but I'm getting this error: { "error": "invalid_grant" } -
How to print errors in console while Object.DoesNotExist
I have 2 files with functions and im trying to show my errors in celery worker console but i have an error: "DETAIL: Key ("GUID")=(#some-guid) already exists." I have try except in the second "create_section" file but for some reason its not working and i got an error in console, how can i handle that? Return or raise wont help me bcs i need code to work after this error Btw: if i just put my create_section code in create_obj file it works fine create_obj.py: for item in response.json(): object_list_json = json.dumps(item) object_list = ObjectListSerializer.parse_raw(object_list_json) section_list = object_list.Sections try: object_list_model = ObjectList.objects.get(GUID=object_list.ObjectGUID) object_list_model.name = object_list.ObjectName create_section(section_list, object_list_model, SectionList) except ObjectList.DoesNotExist as e: print(e) object_list_model = ObjectList.objects.create(GUID=object_list.ObjectGUID, name=object_list.ObjectName) create_section(section_list, object_list_model, SectionList) create_section.py: blank_section_list = [] for section in section_list: try: blank_section_list.append(SectionList.objects.get(GUID=section.SectionGUID)) continue except SectionList.DoesNotExist as error: print(error) SectionList.objects.create(GUID=section.SectionGUID, name=section.SectionName, details=section.DetailedSectionName, object_list=object_list_model) object_list_model.section_list.set(blank_section_list) object_list_model.save() -
How do you conditionally display/hide one of two forms with a live search in Django?
I have two forms: from django import forms from .models import Entity, Quote class EntityForm(forms.ModelForm): class Meta: model = Entity fields = ['name', 'website', 'contact'] class QuoteForm(forms.ModelForm): class Meta: model = Quote fields = ['entity', 'text', 'notes'] Initially on page load only the entity name field is displayed along with the whole quote form. The website and contact fields should not be displayed. The user fills in the entity name field. We do a live search to get all values in the entity model that are similar to help them fill in the form. If no results are returned from their input text, the website and contact fields should now be displayed. The live search functionality is fairly simple to implement, however I'm struggling with the hide/unhide functionality and could use some help. The page initially loads the quote text and I'm not sure why. Similarly, when I fill in the entity field with strings I know that aren't in the database there's no hide/unhide toggle. <form> <label for="entity-name">Entity Name:</label> <input type="text" id="entity-name" name="entity-name" onkeyup="searchEntities()"> <div id="search_results"></div> </form> <form id="quote-form"> <div class="form-group"> <label for="quote-text">Quote Text:</label> <textarea class="form-control" id="quote-text" name="quote-text" rows="3"></textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> <script> function searchEntities() { … -
How to reduce more `SELECT` queries which are already reduced by "prefetch_related()"?
I have Country, State and City models which are chained by foreign keys as shown below: class Country(models.Model): name = models.CharField(max_length=20) class State(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=20) class City(models.Model): state = models.ForeignKey(State, on_delete=models.CASCADE) name = models.CharField(max_length=20) Then, I iterate Country and State models with prefetch_related() as shown below: for country_obj in Country.objects.prefetch_related("state_set").all(): for state_obj in country_obj.state_set.all(): print(country_obj, state_obj) Then, 2 SELECT queries are run as shown below. *I use PostgreSQL and these below are the query logs of PostgreSQL and you can see my answer explaining how to enable and disable the query logs on PostgreSQL: Next, I iterate Country, State and City models with prefetch_related() as shown below: for country_obj in Country.objects.prefetch_related("state_set__city_set").all(): for state_obj in country_obj.state_set.all(): for city_obj in state_obj.city_set.all(): print(country_obj, state_obj, city_obj) Then, 3 SELECT queries are run as shown below: Now, can I reduce 3 SELECT queries to 2 SELECT queries or less? -
How to better control the output location of files produced by rollup
I have the following source directory structure: -- browser/ client.html client.js When I run rollup it produces: -- dist/ browser/ client.html assets/ client-7878f.js I'd like it to output: -- dist/ client.html assets/ client-7878f.js How would one achieve that? My rollup options are: { input: 'browser/client.html', }, -
Generating forms based on user choices in Django
I am working on a Django project whose purpose is to allow the user to fill in some forms. In some of these forms, the user must make a choice between several options and, based on the choice made, a particular form must be generated. At the end of all these forms, the data entered must be used to write a pdf file. As for the functionality related to generating the pdf, what I'm interested in for the purposes of the question is the use of data entered in one view in another view using them as context. Here's what I tried to do. First of all I created some forms in forms.py: class ChoiceForm(forms.Form): CHOICES = [ ('1', 'Choice-One'), ('2', 'Choice Two'), ] choice = forms.ChoiceField(choices=CHOICES) class ChoiceOneForm(forms.Form): name_one = forms.CharField(max_length=200) class ChoiceTwoForm(forms.Form): name_two = forms.CharField(max_length=200) Then I created this view in views.py: def contact(request): if request.method == 'POST': num_people = int(request.POST.get('num_people')) people_formset = [forms.ChoiceForm() for i in range(num_people)] return render(request, 'home.html', {'people_formset': people_formset}) else: return render(request, 'home.html') def generate_pdf(request): context = {} return render(request, 'pdf.html', context) And finally I have this HTML file called 'home.html': <h1>Contact</h1> <form method="post"> {% csrf_token %} People number: <input type="number" name="num_people" required> <input … -
Upload Issue - No Resized Images Generated -django-avatar=5.0.0
I am using django-avatar=5.0.0 on django=1.11.4 and pillow=4.2.1. When i try to upload a new avatar, it saves it in the database but the resized image and folder is created for .jpg and .jpeg file but not for.png file. This is the image source the template is looking for but it's not created: <img src="/media/avatars/user/resized/80/9919.png" alt="Avatar object" width="80" height="80"> But for jpeg and jpg file format, the image is retrived from library: <img src="/media/avatars/user/resized/80/9919.jpeg" alt="Avatar object" width="80" height="80"> -
How to return correct model fields in serializer?
I am implementing a search bar that returns the users and the posts. I am able to return the data but when i clear the search bar i get the error returned: AttributeError: Got AttributeError when attempting to get a value for field username on serializer SearchUserSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Post instance. Original exception text was: 'Post' object has no attribute 'username'. My Models: class User(AbstractUser): avi_pic = models.ImageField( max_length=400, null=True, blank=True, upload_to='images') name = models.CharField(max_length=50, blank=True, null=True) username = models.CharField(max_length=30, unique=True) class Playlist(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, default=None ) cover = models.CharField(max_length=300, default='', blank=True) title = models.CharField(max_length=300, default='', blank=True) date = models.DateTimeField(editable=False, auto_now_add=True) My Serializers: class SearchPostSerializer(serializers.ModelSerializer): username = serializers.SerializerMethodField() class Meta: model = Post fields = ('id', title', 'user', 'username', 'cover') def get_username(self, post): return post.user.username class SearchUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'name', 'username', 'avi_pic') and my Views.py: class SearchView(generics.ListAPIView): def get_serializer_class(self): queryset = self.get_queryset() if len(queryset) == 0: return None if isinstance(queryset[0], User): return SearchUserSerializer elif isinstance(queryset[0], Post): return SearchPostSerializer else: return None def get_queryset(self): query = self.request.query_params.get('q', None) if query is not None: queryset_users = User.objects.filter( Q(name__icontains=query) | … -
How to avoid excessive logging by autoreload in django rest framework?
currently I am using logging from django rest framework.But I am getting excessive logging by autoreload. I want to avoid excessive logging of autoreload. -
Django application running on top of Serverless + Lambda + API Gateway HTTP API is rewriting links to be prefixed with default
My Django Application (Largely REST Framework based) is currently producing URLs on the admin page that don't resolve. The expected result is that the Django Admin's login prompt submits the form with a POST to /admin/login. The resultant URL passed by as the form submission URL by Django is /$default/admin/login and that returns a 404 with the even more obtuse /$default/$default/admin/login/. I'm presuming I have some sort of misconfiguration in either my Django configuration or serverless.yml. As per the following serverless.yml I'm using API Gateway V2, Django through WSGI, and Lambda functions. service: api app: api org: myapp frameworkVersion: '3' provider: name: aws runtime: python3.8 functions: serve: handler: wsgi_handler.handler timeout: 20 environment: DB_NAME: ${param:db_name} DB_PASSWORD: ${param:db_password} DB_USER: ${param:db_user} DB_PORT: ${param:db_port} DB_HOST: ${param:db_host} events: - httpApi: "*" migration: handler: migrate.handler timeout: 60 environment: DB_NAME: ${param:db_name} DB_PASSWORD: ${param:db_password} DB_USER: ${param:db_user} DB_PORT: ${param:db_port} DB_HOST: ${param:db_host} custom: wsgi: app: myapp.wsgi.application plugins: - serverless-python-requirements - serverless-wsgi My URLs are pretty standard: from django.contrib import admin from django.urls import path, include from rest_framework.schemas import get_schema_view schema_view = get_schema_view( title="MyApp", description="MyApp Universal API", version="1.0.0", ) urlpatterns = [ path("admin/", admin.site.urls), path("user/", include("myapp.core.urls"), name="user"), path("openapi", schema_view, name="openapi-schema"), ] My configuration is even more standard: import os from pathlib … -
How to upload react build folder to my remote server?
I'm trying to deploy my react build folder to my server. I'm using index.html and static that configured in my settings.py file to do that. (https://create-react-app.dev/docs/deployment/) Since my backend is running on Ubuntu, I can't just copy from my Windows side and paste it. For now, I uploaded my build folder to my Google Drive and I download it on Ubuntu. But I still can't just copy and paste it on my PyCharm IDE, I can only copy the content in each file and then create a new file ony my server and paste the content to the file. This is just so time-consuming. Is there any better way to do this? Thank you. -
How do I handle sending iOS push notifications if my iOS app back end is in python?
I had a question which I have done a lot of googling on but still couldn't find a suitable answer. I am building my iOS app's back end using django rest framework and what I wanted to know since I am new to iOS is how would notifications show on a user's iphone when lets say a model is changed or something or for example if I make a simple GET request then how does a notification get put out on my iOS app? regards and thanks in advance! Tried googling Tried googling and tried googling -
IntegrityError Django ForeignKey sets to none
I've been having an issue with setting the ForeignKey in one of my model fields for the author variable. See below: class BugTracker(models.Model): project_number= models.IntegerField(primary_key=True) assignee= models.ForeignKey(Developer, on_delete=models.CASCADE) priority = models.CharField(max_length=10, choices=priority_choices) summary=models.TextField() status= models.CharField(max_length=20, choices=progress) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_at=models.DateTimeField(default=timezone.now) updated_at=models.DateTimeField(auto_now=True) def __str__(self): return self.summary def get_absolute_url(self): return reverse("bug_list") "IntegrityError at /projects/create/ NOT NULL constraint failed: core_bugtracker.author_id Request Method: POST Request URL: http://127.0.0.1:8000/projects/create/ Django Version: 4.1.5 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: core_bugtracker.author_id" As soon as I add "null=True" to the ForeignKey Field, it works and I don't get an error, but the template shows my variable ({bug.author}} equal to "None" regardless of who I'm signed in as. I tried deleting my database and migration files multiple times, but it still doesn't work. Any help would be appreciated here -
How to get request value in another class in django?
It's an example that's as similar as possible, and it's not exactly the same as the actual code. But I believe it's easy to understand. class Fruits: ... def get_sample_data(self, df): ... data = { 'put_file_attachment': >here<, } ... class DataInputForm(forms.Form): attachment = forms.FileField() class MyView(FormView): template_name = 'view.html' form_class = DataInputForm def get_success_url(self): return str( reverse_lazy("milk") ) def post(self, request, *args, **kwargs): get_file = request.FILES.get('attachment') ... k = Fruits() k.load_data() return self.render_to_response(context) I would like to bring the attachment(In fact, get_file) that the user attached to the web class Fruits's >here< In other words, I would like to save the file(get_file) in DB column (put_file_attachment) by the user's attachment. How can I get a value passed to a request from another class to another class? I tried to get 'get_file' by creating a MyView object in the Fruit class, but it doesn't work. Is that possible in this structure or Am I not understanding the concept of request??