Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why makemessages generates *.html.py file from my *.html in the component (django_components) and base.html template?
I am creating my Django website and using django_components in the project. Now I'm thinking about creating a multilingual site: I created the necessary translate tags, added an i18n loader, created a locale folder in the root of the project. Now I am running the following command: $> python manage.py makemessages --locale=en Today, this command is working correctly. But yesterday, when I was doing it, an error about the inability to read the file dropped out /component/my_widget/my_widget.html.py. Initially, there was no such file at all, there was only my_widget.html and my_widget.py , but this file was created when executing the command. Inside this file there were different sets of letters X and B of different lengths, and in structure it resembled tags from a template my_widget.html . The most interesting thing is that in this file I did not use the translate tag at all. Next is an example of this strange .html.py file: BBBB BBBBBB XXXX XXXXXX XXXXXXX XXXXX XX XXXXXXX XXXXXX XX XXX XX XXXX XXX XXX XXXX XXXXXXXXXXXXXXX XXX BB BBBBBBBBBBBBBBBBB BB BBBBBBBBBBBB XXXX XXXX XX XXXX XXXXXXX XXX XX XXXXXXXXXXXXXXXXXXXXX XXXXXXXX XXXX XXXXXXXXXXXXXXXXXX XXXX XXXXXX XXX XXXXXXXXXX XXXX XXXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXX XX XXXXX XXXX X XXXXXXXXXXXXX … -
Why is simply adding "_id" suffix to a ForeignKey field automatically allowed in Django Serializer?
If I had the following model, I could set foo to foo_id by supplying foo_id = serializers.PrimaryKeyRelatedField(source='foo',queryset=Foo.objects.all() in the BarSerializer. from django.db import models class Bar(models.Model): foo = models.ForeignKey(Foo, on_delete=models.CASCADE) However, I can also set foo to foo_id as follows, without that specified line of code. from rest_framework import serializers class BarSerializer(serializers.ModelSerializer): # foo_id = serializers.PrimaryKeyRelatedField(source='foo',queryset=Foo.objects.all() class Meta: model = Bar fields = ['foo_id'] Why exactly can I provide 'foo_id' rather than 'foo' in the fields list here? One difference is that attempting to save a new Bar object with the BarSerializer results in django.db.utils.IntegrityError: (1048, "Column 'foo_id' cannot be null"), even when {foo_id: 1} is provided in the request data. -
in my API view i want to upload video in background using serializer , i want to return response and i dont want to wait until video upload complete
Here is my ApiView and i am uplaoding video to GCP bucket using serializer and video is filefield i am new to djngo DRF so can you please help me. how can use threading my case? class TestsApi(APIView): def post(self, request, *args, **kwargs): if request.method == "POST": if request.data.get('video') is not None: serializervideo = VideoSerializer(data=request.data) if(serializervideo.is_valid()): serializervideo.save() "Rest of the code" return Response(result) i want to upload video completely in background, i dont want to wait until video uploaded to my bucket i want to return response. Thank you in advance. -
Angular routes to localhost in k8s cluster
I have a problem with my Angular 15 Frontend app inside Minikube cluster. For deploying my app in Minikube, I add the k8s services URLs to environment files and Angular/Nginx sends me back to localhost - not to desired servcice URL. environment.development.ts export const environment = { production: false, serviceURL: 'http://backend.namespace.svc.cluster.local:8000', }; service.ts import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable } from 'rxjs'; import { User } from './user'; import { environment } from '../../environments/environment' @Injectable({ providedIn: 'root' }) export class MainService { baseUrl = environment.serviceURL+'/user/' httpHeaders = new HttpHeaders; constructor( private http: HttpClient, ) { } user(user:any): Observable<User> { return this.http.get<User>(this.baseUrl) } } With these settings Angular sends me back to localhost, where I get an 404 error where cannot find the 'http://localhost:4200/user/' When I try to curl service url ( curl http://backend.namespace.svc.cluster.local:8000 ) from frontend pod I get a correct response. Can someone advise me how to correctly connect angular frontend with django backend, please? -
How to send a file response to a user in Django application after some processing
I'm working on a solution which translates CSV/TSV files from one language to the other. I've built a Django application that accepts the file and the target/source language(s) using a form. Once the user provides the data, the file is processed (which takes some time). Now I know we can return a fileresponse to the user. However, as I mentioned it takes time for the file to be translated and a new file is created which would contain the translated contents. And in the meantime, I don't want to make the user waiting on the form...waiting for the response. The models.py file is: from django.db import models from django.core.validators import FileExtensionValidator file_type_choices = [ ('CSV', 'Comma-Separated Values'), ('TSV', 'Tab-Separated Values') ] valid_extensions = ['tsv', 'csv'] # Create your models here. class FileModel(models.Model): file = models.FileField(upload_to="files", \ validators=[FileExtensionValidator(allowed_extensions=valid_extensions)]) file_type = models.CharField("Choose your file type", choices=file_type_choices,max_length=3) source_language = models.CharField("Choose the language in which file is", max_length=30) target_language = models.CharField("Choose the language to which you want to translate the file", max_length=30) the forms.py file: from django import forms from django.core.validators import FileExtensionValidator file_type_choices = [ ('CSV', 'Comma-Separated Values'), ('TSV', 'Tab-Separated Values') ] valid_extensions = ['tsv', 'csv'] class FileUploadForm(forms.Form): file = forms.FileField(allow_empty_file=False, \ validators=[FileExtensionValidator(allowed_extensions=valid_extensions)]) … -
Database structure on unknown column length excel
I have a program which user will import an excel of product details. It must include "barcode" and "name". But other columns is unknown and the length of column is also unknown. The program will be copy and paste to many client's PC, and each client product detail excel's may contain unknown + 2 columns (2 means the barcode and name). What will the database struture be on this case? Should I create a product table will defualt like 30 columns? "null" on non-used value? Even I create a product table with ID, barcode and Name. And create a "Product Extra Table" to left join the "product Table". I also need to create 30 columns on the "Product Extra Table". As the program will need to read the excel file, this operation will be process on runtime. I am using Django, I found that Django seem not able to support modify models during runtime? If I can modify the model during runtime, I can loop the excel headers and create a same column length model same as the product excel. -
Django Customusermodel was declared with a lazy reference
I am working on an app main and I want to have a custom login, that authenticates with email, not with username as normally in Django. For that I created the following model: class User(AbstractUser): username = None email = models.EmailField(('Email-Adresse'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] and added this model to the settings.py: AUTH_USER_MODEL = 'main.User' Then I replaced the user foreign key in my database: class BrainFeedback(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, blank=True, null=True, db_index=True) Running makemigrations worked perfectly fine, but python manage.py migrate triggers the following error: The field main.BrainFeedback.brain was declared with a lazy reference to 'main.user', but app 'main' doesn't provide model 'user'. What could be the problem? I was using a online guide to do these changes and I did everything how I should. -
Downloading image created using Pillow with Django
I am creating image using Pillow from text input provided by user. I am using Django and django-ninja to process the data and then send the image to user. It will not show the image and my server will not store the image, the user will get to download the image. The process will be like: User type text > User press Download button > Ajax send text to Django backend > Django backend using Pillow create image based on the text > User download the image There is no error and I can see the image from preview in network tab but I am not able to download the image. This is my Ajax: function downloadDoa(){ allDoas = [] for (let i = 0; i < userDoaAll.length; i++) { userCustomMadeDoa = userDoaAll[i]; if (userCustomMadeDoa.classList.contains("customUserDoa")){ allDoas.push(['na',userCustomMadeDoa.innerHTML]) } } console.log(allDoas) $.ajax({ url: "{% url 'api:download_doa' %}", data: { customDoasLists: JSON.stringify(allDoas), csrfmiddlewaretoken: '{{ csrf_token }}', }, method : "post", dataType : "json", headers: {'X-CSRFToken': csrftoken}, mode: 'same-origin', // Do not send CSRF token to another domain. csrfmiddlewaretoken: '{% csrf_token %}', success: function (response) { console.log(response) }, }); } This is from my api.py to process user input: @api.post("/download_doa",url_name="download_doa",auth=None) def download_doa(request): im_io = … -
Cannot find specific ids in html files in django app?
i want to search for specific ids in html files of a django app by using inspect element, so that i can know which html page on the browser links to which html page in the Django app in VS Code. But i am unable to find the ids in the django app. there are template files and alot of them are there and the ids are not found in the app. kindly help? -
Adding a boolean value to a search function
I have a multi-filter function that returns Clinic results based in 5 parameters. I want to add a 6th parameter which is a BooleanField (both in model and form). I want the field to return the corresponding elements if True, but if False, return all the elements according to the other search parameters independently of this BooleanField. if request.htmx: name = request.GET.get('name') city = request.GET.get('city') ward = request.GET.get('ward') speciality = request.GET.get('speciality') english = request.GET.get('english') print(f'english: {english}') if all([len(name) == 0, len(city) == 0, len(ward) == 0, len(speciality) == 0]): qs = None else: qs = Clinic.objects.filter(Q(name__icontains=name) & Q(city__icontains=city) & Q(ward__icontains=ward) & Q(speciality__icontains=speciality)) I tried to add the english variable to the queryset as Q(english_support=english) but without success. If I print out the result, it returns None if not checked, and on if checked. How can I add the condition that if None, return all the results according to the other Q parameters and if True just add it to the other conditions? -
Multiple filters search in Django
I'm trying to build a search system of hospitals, with the following form: class ClinicSearchForm(forms.Form): name = forms.CharField(required=False, initial=None, max_length=100, widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Name of the hospital'})) city = forms.ChoiceField(required=False, choices=BLANK_CHOICE_DASH + Cities.choices, widget=forms.Select( attrs={'class': 'form-control', 'placeholder': 'Choose a city'})) ward = forms.ChoiceField(required=False, choices=BLANK_CHOICE_DASH + Wards.choices, widget=forms.Select( attrs={'class': 'form-control', 'placeholder': 'Choose a ward'})) speciality = forms.ChoiceField(required=False, choices=BLANK_CHOICE_DASH + sorted(Speciality.choices), widget=forms.Select( attrs={'class': 'form-control', 'placeholder': 'Choose a speciality'})) parking = forms.BooleanField(required=False) english = forms.BooleanField(required=False) Those are 6 parameters the user can use to search for clinics. Any of them is required. I'm having problems with rendering results when no content is entered in a field, as it will be an empty string and therefore return all values in the database. I could accomplish or type of search by initializing a queryset variable and then appending the results of the individual fields after checking they are not blank. I would like it to be an and search, that search using the criteria of all the fields the user has entered. if request.htmx: name = request.POST.get('name') city = request.POST.get('city') qs = Clinic.objects.filter(Q(name__icontains=name) & Q(city__icontains=city)) This simple code will return all the results when value is blank (empty string). I tried with Q queries, … -
How to get an app in kotlin to send data back and forth to a Django project
Backend: Django Frontend: Kotlin Android App All data will go through the backend application but I want to make a simple connection between the two. Does anyone recommend any pages/articles or advice on how to do this. Plan: Enter a number in the app -> Send this number to the django app -> searches in the DB (if there: display the info. else:add the info to the db) return all the info to the app I have made a few django apps previously but always just used a web based front end and never an android application and I wanted to do something new -
How to get language of Tranlated Field in django parler?
My Django model looks like this which stores events (Tradeshow) in different languages, class Tradeshow(AbstractPageMethods, EventDateTZ, TranslatableModel): # TODO when a page is deleted, delete the url associated as well content_section = models.CharField(choices=CONTENT_SECTION_CHOICES, default='physician', max_length=100) sitemap_changefreq = models.CharField(default='weekly', choices=SITEMAP_CHANGEFREQ_CHOICES, max_length=100) sitemap_priority = models.FloatField(default=0.7) translations = TranslatedFields( meta_title=models.CharField(max_length=300, blank=True, null=True), meta_description = models.TextField(max_length=300, null=True, blank=True), regions = models.ManyToManyField(EventRegion, help_text='Choose the Region this Webinar belongs in<br />'), event_start=models.DateTimeField(null=True, ), event_end=models.DateTimeField(null=True, ), event_tz=models.CharField(null=True, verbose_name='Event Timezone', max_length=128, choices=[(tz, "{} ({})".format(tz, pytz.timezone(tz).localize( datetime.datetime.now()).tzname())) for tz in pytz.all_timezones]), hide_breadcrumb=models.BooleanField(default=False), hide_headers=models.BooleanField(default=False), hide_footers=models.BooleanField(default=False), exclude_from_search=models.BooleanField(default=False), show_canonical_tag=models.BooleanField(default=True), tags=models.ManyToManyField('general.Tag', blank=True), exclude_from_sitemap=models.BooleanField(default=False), ) For each event there is a translation, enter image description here When I query that django model, for each translation it shows the language as English, >>> for t in Tradeshow.objects.filter(translations__title='FME - France médecine esthétique'): ... t.get_current_language() ... 'en' 'en' 'en' It should show the respective language, fr-fr or es-es. Please advise how to get the correct language? -
Download Image created from Pillow using Django
I am creating image using Pillow from text input provided by user. I am using Django and django-ninja to process the data and then send the image to user. It will not show the image and my server will not store the image, the user will get to download the image. The process will be like: User type text > User press Download button > Ajax send text to Django backend > Django backend using Pillow create image based on the text > User download the image There is no error but I am not able to download the image. This is my Ajax: function downloadDoa(){ allDoas = [] for (let i = 0; i < userDoaAll.length; i++) { userCustomMadeDoa = userDoaAll[i]; if (userCustomMadeDoa.classList.contains("customUserDoa")){ allDoas.push(['na',userCustomMadeDoa.innerHTML]) } } console.log(allDoas) $.ajax({ url: "{% url 'api:download_doa' %}", data: { customDoasLists: JSON.stringify(allDoas), csrfmiddlewaretoken: '{{ csrf_token }}', }, method : "post", dataType : "json", headers: {'X-CSRFToken': csrftoken}, mode: 'same-origin', // Do not send CSRF token to another domain. csrfmiddlewaretoken: '{% csrf_token %}', success: function (response) { console.log(response) }, }); } This is from my api.py to process user input: @api.post("/download_doa",url_name="download_doa",auth=None) def download_doa(request): text_list = json.loads(request.POST.get('customDoasLists')) font_path_a = "Hafs.ttf" font_path_na = "Arial.ttf" font_size_a = 40 font_size_na … -
Django "The process cannot access the file because it is being used by another process" error while trying to delete a videofile
My Post model has relation to a PostMedia model, which can contain images and videos. I have no trouble with deleting images, but when I try to delete video, I face this error: PermissionError: [WinError 32] The process cannot access the file because it is being used by another process. Generally speaking, I have no idea about the reason it happen. Maybe, someone face the problem? models.py class Post(models.Model): author = models.ForeignKey( User, on_delete=models.CASCADE ) title = models.CharField( max_length=200, null=True, blank=True, help_text="Beauty header to start your post." ) body = CharField( max_length=500, help_text='Required.' ) other_file = models.FileField( null=True, blank=True, upload_to="posts/files", help_text="Only .rar, .zip and .pdf files accepted!", validators=[ FileExtensionValidator(allowed_extensions=['rar', 'zip', 'pdf']) ], ) post_date = models.DateTimeField( auto_now_add=True ) likes = models.ManyToManyField( User, through='UserPostRel', related_name='likes', help_text='Likes connected to the post', ) class PostMedia(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name='post_media', ) file = models.FileField( upload_to="posts/post_media", validators=[], ) file_thumbnail = models.FileField( upload_to="posts/post_media/thumbnails", null=True, blank=True, ) servername = models.CharField( max_length=255 ) views.py class PostCreateView(AuthRequiredMixin, SuccessMessageMixin, View): template_name = 'create_post.html' model = Post form = PostCreationForm success_url = reverse_lazy('index') success_message = _('Post created successfully') def get(self, request, *args, **kwargs): form = self.form() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form(request.POST, … -
Django DRF save data for every session (logging user)
I want when a user logins save some data like email, name and ids while the user is logging in And I can get the data anywhere like models.py ## views.py def post(self, request): print('------------login request----------------') serializer = self.serializer_class(data=request.data, ) if not serializer.is_valid(): return api_response(error={"non_field_errors": "Unable to log in with provided credentials"}, status=ApiStatus.fail) user = serializer.validated_data['user'] account_serializer = AccountSerializer(user) token, created = Token.objects.get_or_create(user=user) token = token.key data = account_serializer.data data.pop('password', None) data['token'] = token request.data['account_id'] = user.pk device_serializer = DeviceSerializer(data=request.data) if device_serializer.is_valid(): device_serializer.save() # Save data here like data['db_key'], data['email'] return api_response(data=data) ## models.py from django.db import models class User(models.Model): ## and get data here => data['db_key'] objects = models.Manager().using() -
How to edit Django Crispy field names
I'm trying to edit field names that come with (probably) crispy forms but I cannot find the file anywhere. This is my post_form.html {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">New Post</legend> {{ form.media }} {{ form|crispy }} </fieldset> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> </div> {% endblock content %} I tried to find it from inspect I did find where I wanna change but when I search that file in my project I cannot find it anywhere. I want to change this Content* to Body -
Virtual environment installing packages globally
I have been working on a Django project, which I created and have been running in a virtual environment. I recently made the project folder a GIT repository and pushed the project up to Github. The next time I went to run the development server I got an error message saying that Django wasn't installed. Whilst in the virtual environment I used pip to install Django in my project folder however it is being installed globally and I can run the server outside the virtual environment. I have uninstalled Django and tried again to install it in the virtual environment, however it is still installing globally. (venv) C:\Users\tomge\django_projects\djangodelights>pip uninstall Django Found existing installation: Django 4.1.7 Uninstalling Django-4.1.7: Would remove: c:\users\tomge\appdata\local\programs\python\python310\lib\site-packages\django-4.1.7.dist-info\* c:\users\tomge\appdata\local\programs\python\python310\lib\site-packages\django\* c:\users\tomge\appdata\local\programs\python\python310\scripts\django-admin.exe Proceed (Y/n)? y Successfully uninstalled Django-4.1.7 (venv) C:\Users\tomge\django_projects\djangodelights>py -m pip install django Collecting django Using cached Django-4.1.7-py3-none-any.whl (8.1 MB) Requirement already satisfied: sqlparse>=0.2.2 in c:\users\tomge\appdata\local\programs\python\python310\lib\site-packages (from django) (0.4.3) Requirement already satisfied: tzdata in c:\users\tomge\appdata\local\programs\python\python310\lib\site-packages (from django) (2023.3) Requirement already satisfied: asgiref<4,>=3.5.2 in c:\users\tomge\appdata\local\programs\python\python310\lib\site-packages (from django) (3.6.0) Installing collected packages: django Successfully installed django-4.1.7 WARNING: You are using pip version 22.0.4; however, version 23.0.1 is available. You should consider upgrading via the 'C:\Users\tomge\AppData\Local\Programs\Python\Python310\python.exe -m pip install --upgrade pip' command. … -
How can I edit the message of the email sent by Wagtail when a page is submitted for moderation?
I'm trying to edit the content of the email sent by Wagtail when a page is submitted for moderation, I've dug into the Wagtail source code and it turns out there is a function called send_mail which actually sends the emails to all the subscribers when a page is sent for moderation, this function is called by another one called send_notification which takes some notification templates (HTML and txt files) depending on the type of action (submitted, approved, rejected) of the page, those templates contain the email content and I haven't found the way to override the content of those templates from my Wagtail project. If someone has done that before, I really appreciate your help. Thank you! I'm expecting being able to edit the content of the emails because I want to add some custom fields like comments. -
Auto pre-fill form Django
How to pre-fill form fields in Django. What would be the pre-filled data from the User class when forming the order form. The result need like this: my view def order_create(request): cart = Cart(request) user = request.user if request.user.is_authenticated: if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save(commit=False) if cart.coupon: order.coupon = cart.coupon order.discount = cart.coupon.discount order.save() for item in cart: OrderItem.objects.create(order=order, product=item['product'], price=item['price'], quantity=item['quantity']) cart.clear() order_created.delay(order.id) request.session['order_id'] = order.id return redirect(reverse('payment:process')) else: form = OrderCreateForm() else: return redirect('login') return render(request, 'orders/order/create.html', {'cart': cart, 'form': form}) my form class OrderCreateForm(forms.ModelForm): class Meta: model = Order fields = ['first_name', 'last_name', 'email', 'address', 'postal_code', 'city'] my teplate <form action="." method="post" class="order-form"> {{ form.as_p }} <p><input type="submit" value="Place order"></p> {% csrf_token %} </form> Im try to use initial but with no result. -
Django Equivalent of JSDocs?
I've been tasked to add an automated endpoint documentation tool for our Django codebase. It needs to produce html files that we can then host in our s3 buckets for internal reference. I thought drf-spectacular would be it, but it doesn't seem to actually produce html files, but only documentation for one's local environment. Is there a tool or library that can do this? Something like JSDocs or TypeDoc, where I can run a command, and dump html documentation files into an s3 bucket. Thank you! -
Django Select2 Widget bad rendering?
I tried to implement multi select-boxes from select2. The widget works fine, but the user input is under the field. Screen: enter image description here this how it looks in html. <select class="js-example-basic-multiple" name="states[]" multiple="multiple"> <option value="AL">Something</option> <option value="WY">Wyoming</option> <option value="WY">Somebody</option> </select> <script> $(document).ready(function() { $('.js-example-basic-multiple').select2(); }); </script> I tried to change height, but maybe not its the problem -
Missing table socialaccount_socialapp_sites, how do I fix this?
Whenever I try to add a social app, I get an error that the table socialaccount_socialapp_sites is missing. I had some set up problems because I forgot to include django.contrib.sites at first, but after fixing that I seem to get everything to work up until adding a socialapp. I have already run migrate and makemigrations and looking at showmigrations, it looks like all have been made. Is there something that I am missing? or do I need to go into my DB and create the table manually? -
Bootstrap modal problem in Django project
Im trying to use a bootstrap modal as part of my web application, but the pop up wont show when the button is pressed. I have copied all the code exactly as it is on the bootstrap site. <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalLong"> Launch demo modal </button> <!-- Modal --> <div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> Any help will be appreciated! I tried copying the code directly as it is from the bootstrap website but no joy. -
limit resources for authenticated user in flask or Django
Currently im planning to distribute resources such as memory, cpu and other resources based on the authenticated user. I tried to search on how can i implement it but i only managed to find rate limit for request and ability to gain information of memory and cpu using psutil.