Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Will i be able to host my django web app on heruko if i have a github student developer pack
So, I have a Django web app I need to host, and I want to host it for free. But Heroku's service is not free, but I have the Github student developer pack and saw Heroku's service on it. Will I be able to host my Django project on it now, and if yes, then how do I do it? My Django web app has data that goes to the Django console and Firebase real-time database. Or can I get a free alternative? -
What is a better way to use 'request' in a ModelChoiceField
Is there any way to use user=request.user inside ModelChoiceField when I use this method I got an error: NameError: name 'request' is not defined. class AlbumForm(forms.Form): album = ModelChoiceField(queryset=Album.objects.filter(user=request.user) The model: class Album(models.Model): name = models.CharField(max_length=20) user = models.ForeignKey(User, on_delete=models.CASCADE) -
django application on AWS fargate with postgresql persistent database
I have django + reactjs application. It used postgresql db. Currently i am using a docker compose on my pc and able to spin up the applicaiton. I have volume where the postgresql db is stored. Now What the right way to put this application in to the aws ECS. Also i am not sure how to create migrations in fargate, because we may not have access using ssh. -
'int' object is not iterable - sum up 2 variables after an if statement in django/python
I am looking to sum 2 variables together and getting error: 'int' object is not iterable. In summuary, I have a sort of todo list. Every time an action is validated by creating an Validation object model, the action is given 1 point. If all actions within the task have received 1 point, then the task is considered completed. I am stuck at the sum of points. I feel I need to write a sort of for loop after my if statement to add up each point in each action together. I tried different combos, but none seem to work. Am I getting this wrong? (I am sure my code is also far from being optimal, so I wont be offended if you offer an alternative) models class Action(models.Model): name = models.CharField(verbose_name="Name",max_length=100, blank=True) class ValidationModel(models.Model): user = models.ForeignKey(UserProfile, blank=True, null=True, on_delete=models.CASCADE) venue = models.ForeignKey(Action, blank=True, null=True, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) class Task(models.Model): title = models.CharField(verbose_name="title",max_length=100, null=True, blank=True) venue = models.ManyToManyField(Action, blank=True) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) class TaskAccepted(models.Model): name = models.ForeignKey(Task,null=True, blank=True, on_delete=models.SET_NULL, related_name='task_accepted') user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) accepted_on = models.DateTimeField(auto_now_add=True, null=True, blank=True) views def function(request, taskaccepted_id): instance_1 = Action.objects.filter(task__id=taskaccepted_id) action_count = instance_1.count() instance_2 = get_object_or_404(Task, … -
E2E tests using selenium giving requested image's platform does not match the detected host platform (linux/arm64/v8)
For E2E tests for a Django app I was using selenium/standalone-chrome selenium: image: selenium/standalone-chrome container_name: selenium ports: - "4444:4444" but then started to get the following error selenium The requested image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8) and no specific platform was requested How to proceed to get E2E tests? -
Admin. Register model in other app administration
In admin panel I'm looking to having all user related models in one app administration, including Group and Permission models, which are by default included in Authentication and authorization app. Is there a way of changing default render place of model in admin? Also, I'm understand that I can inherit a Group class to make my own, but I'd like to avoid that. I've tried making custom ModelAdmin and to ugregister and register with it, but it's still in Authentication and authorization. My code right now (as starting point): from django.contrib.auth.models import Group class GroupAdmin(admin.ModelAdmin): filter_horizontal = ('permissions',) admin.site.unregister(Group) admin.site.register(Group, GroupAdmin) -
LOG: unexpected EOF on client connection with an open transaction
I am getting LOG: unexpected EOF on client connection with an open transaction from postgresql log when saving object on django admin and no any log or error from django, and browser gives me following error: Everything was fine before I started to use Celery for schedule tasks. I couldn't find where the proble is coming. signals.py @receiver(post_save, sender=Posts) def send_save_obj(sender, instance, created, **kwargs): # Translate to latin relates_to = instance title = to_latin(instance.title) author = instance.author ... # Creating latin obj if created and language == 'uz': def save_latn_obj(): # create latin post post = PostUzLatn.objects.create( relates_to=relates_to, title=title, ... ) post.tags.add(tags) transaction.on_commit(save_latn_obj) # Sending to telegram channel # Get the current time in the server's local time zone server_time = datetime.now() # Create a timezone object for Tashkent tashkent_tz = pytz.timezone('Asia/Tashkent') # Convert the server time to Tashkent time tashkent_time = server_time.astimezone(tashkent_tz) if 'tg' in instance.social_network \ and publish <= tashkent_time: send_news( title=instance.title, ) # Update status after sending msg Posts.objects.filter(id=instance.id).update(is_sent=["is_sent_tg",]) # Delete the cache key to invalidate the cache for this view cache.clear() bot.py def send_news(title): if tizer: bot.send_video(CHANNEL_ID, video=tizer, caption=title, supports_streaming=True) else: bot.send_photo(CHANNEL_ID, image, caption=text) -
Gow ot save info about search in django?
I want to do pagination. And when I press to button 'Next' on my page, my website breaks down. It happens because for the next page variable 'searched' is empty. 'Searched' is name of tag input in my form I don't know how to save variable 'searched' for the next page. def search(request): if request.method == 'GET': # API-call searched = request.GET.get('searched') headers = { 'Authorization' : basic_auth(login, password)} params = {'PIN':searched,'VKORG':'4000','KUNNR_RG':'43282126'} res = requests.post(url_for_search,headers=headers,data=params) if 200 <= res.status_code < 300 : names = get_unique_names(res.json()) if not Profile.objects.filter(NAME__in = names).exists(): # Deserialization serializer = ProfileSerializer(data=res.json()['RESP'],many = True) serializer.is_valid() serializer.save() # Getting data from ORM products = Profile.objects.filter(NAME__in = names).distinct() # Pagintation p = Paginator(products,10) page = request.GET.get('page') page_obj = p.get_page(page) return render(request,template,{"page_obj":page_obj,'searched':searched}) else: return HttpResponse('Error') Maybe you can help me? :) -
Django Chained Dropdown implementation on Django admin
the issue i'm facing is I set a district and the city which is under the district and save it. It saves correctly to the database. And when I come back to the page and change the city and save, the city is set to null and the district too is set to null in the database How do i solve it Context: Trying to overwrite django admin change_form for SchoolProfileForm and for the dependable dropdown of province, district, city and ward. when trying to change the already saved city from before, the district value is resetted to nothing and also the city's value(same issue with the ward , the city is also resetted) Javascript Functions: function resetDistrict() { let $ = django.jQuery; let district_list = '<option value="" selected="">---------</option>' $('#select2-id_district-container').html(district_list); console.log(district_list) } function getDistrict(province_id) { resetDistrict() let $ = django.jQuery; $.get('/school/district/' + province_id, function (resp){ let district_list = '<option value="" selected="">---------</option>' $.each(resp.data, function(i, item){ district_list += '<option value="'+ item.id +'">'+ item.name +'</option>' }); $('#id_district').html(district_list); }); } function getDistrictfromDb(province_id) { let $ = django.jQuery; $.get('/school/district/' + province_id, function (resp){ let district_list = '<option value="" selected="">---------</option>' $.each(resp.data, function(i, item){ district_list += '<option value="'+ item.id +'">'+ item.name +'</option>' }); $('#id_district').html(district_list); }); } function … -
Django asking wrong
I have a problem that my first home page see css file but /about/ page not. In terminal I have Home page asking: static/welcome.css About page asking: about/static/about.css and I don't know how to fix that tried reloading server rewriting code -
Create Django Authentication using Amazon Cognito
I am trying to run my Django login and signup authentication using Amazon Cognito and all other services using default database. But I am not able to find any suitable example for that. I have followed the following documentation. But didn't get any success. https://github.com/labd/django-cognito-jwt I am usinng the following libraries: Django==4.1.7 djangorestframework==3.14.0 django-cognito-jwt==0.0.4 Can anyone please help me in this? Thank you. -
Django, Swagger and Cors
I have a Django Rest Framework API that I have deployed on Azure Web App, I installed and configured coresheaders and drf_yasg as shown below.. BASE_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] THIRD_PARTY_APPS = [ 'rest_framework', 'corsheaders', 'rest_framework_simplejwt', 'rest_framework_simplejwt.token_blacklist', 'drf_yasg', ] CREATED_APPS = [ 'authentication.apps.AuthenticationConfig', 'administrator.apps.AdministratorConfig', ] INSTALLED_APPS = BASE_APPS + THIRD_PARTY_APPS + CREATED_APPS MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", "http://abcdefg.azurewebsites.net", ] I have also added ALLOWED_HOSTS = ["abcdefg.azurewebsites.net", "127.0.0.1"] When I make any kind of request from Swagger UI I get CORS error but when I use an endpoint like http://abcdefg.azurewebsites.net/auth/login/ I do not get any error. What could I have missed in configuring Swagger or CORS? In ALLOWED_HOSTS, why does it fail if I add http:// or https:// to the domain? Packages: drf-yasg==1.21.4 django-cors-headers==3.13.0 -
How to debug this error import error in django
ImportError at / templates doesn't look like a module path Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.1.7 Exception Type: ImportError Exception Value: templates doesn't look like a module path Exception Location: C:\Users\Kabilan KB\Desktop\PK\PFA\registration\venv\Lib\site-packages\django\utils\module_loading.py, line 27, in import_string Raised during: app.views.SignUpPage Python Executable: C:\Users\Kabilan KB\Desktop\PK\PFA\registration\venv\Scripts\python.exe Python Version: 3.11.2 Python Path: ['C:\Users\Kabilan KB\Desktop\PK\PFA\registration', 'C:\Users\Kabilan KB\Desktop\PK\PFA\registration', 'C:\Program Files\JetBrains\PyCharm ' '2022.3.3\plugins\python\helpers\pycharm_display', 'C:\Users\Kabilan ' 'KB\AppData\Local\Programs\Python\Python311\python311.zip', 'C:\Users\Kabilan KB\AppData\Local\Programs\Python\Python311\DLLs', 'C:\Users\Kabilan KB\AppData\Local\Programs\Python\Python311\Lib', 'C:\Users\Kabilan KB\AppData\Local\Programs\Python\Python311', 'C:\Users\Kabilan KB\Desktop\PK\PFA\registration\venv', 'C:\Users\Kabilan ' 'KB\Desktop\PK\PFA\registration\venv\Lib\site-packages', 'C:\Program Files\JetBrains\PyCharm ' '2022.3.3\plugins\python\helpers\pycharm_matplotlib_backend'] Server time: Fri, 31 Mar 2023 09:22:56 +0000 How to solve this type of error in django -
how can i download files in aws s3 buckets with Django and boto3
I've been trying to download a file through this view after users pay for it, but i can't seem to make it work. i first tried using file response urls.py urlpatterns = [ path('download-files/<int:id>/<str:order_id>/', download_file, name='download_file'), ] views.py def download_file(request, id, order_id): obj = Product.objects.get(id=id) order = Order.objects.get(order_id=order_id) file = obj.file response = FileResponse(open(file, 'rb')) return response But all i kept getting was this error venv\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'bool' object has no attribute 'get' I tried using boto3 to download the file viewa.py def download_file(request, id, order_id): obj = Product.objects.get(id=id) order = Order.objects.get(order_id=order_id) file = obj.file client = boto3.client('s3', aws_access_key_id = os.environ.get('AWS_ACCESS_KEY_ID'), aws_secret_access_key = os.environ.get('AWS_SECRET_ACCESS_KEY')) bucket_name = os.environ.get('AWS_STORAGE_BUCKET_NAME') # url = 'https://' + settings.AWS_S3_CUSTOM_DOMAIN + '/media/' + f'{file.name}' url = client.generate_presigned_url('get_object', Params = {'Bucket': bucket_name, 'Key': file.name, }, ExpiresIn = 600, ) return HttpResponseRedirect(url) and i go this error <Error> <Code>NoSuchKey</Code> <Message>The specified key does not exist.</Message> <Key>files/it_report_edited.docx</Key> <RequestId>JR7XHE6A8D7F2872</RequestId <HostId>LiQyKEyHsw/xerU2lJXTEZG+m3obOoUdlVH06d2vE+KHHWQVspOqOb9mN9JmJqBW7DVb8Gc63uZmuLSVqcvbYO7SJ3GNLbzlvNnVAxLOvls=</HostId> </Error> It looks to me that i'm not giving the correct key that's why it can't find it, is there a coorect way to handle this? i've tried everything -
Custom requests in Django REST Framework
I see that Django , in the REST Fremework module provide only CRUD requests made for object of a pre-defined model. Is there a way to create custom Rest API that is available in REST framework or swagger? Thank you. Until now I have a workaround to create a model like "request" or "task" , and manage objects of this model with CRUD requests in Swagger. -
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?