Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
is it possible to add db_index = True to a field that is not unique (django)
I have a model that has some fields like: current_datetime = models.TimeField(auto_now_add=True) new_datetime = models.DateTimeField(null=True, db_index=True) and data would be like : currun_date_time = 2023-01-22T09:42:00+0330 new_datetime =2023-01-22T09:00:00+0330 currun_date_time = 2023-01-22T09:52:00+0330 new_datetime =2023-01-22T09:00:00+0330 currun_date_time = 2023-01-22T10:02:00+0330 new_datetime =2023-01-22T10:00:00+0330 is it possible new_datetime to have db_index = True ? the reason i want this index is there are many rows (more than a 200,000 and keep adding every day) and there is a place that user can choose datetime range and see the results(it's a statistical website). i want to send a query with that filtered datetime range so it should be done fast. by the way i am using postgresql also if you have tips for handling data or sth. like that for such websites i would be glad too hear thanks. -
HELLO CAN ANYONE HELP ME OUT , I AM EXHAUSTED NOW, PLEASE HELP ME
[settings.py ' gaierror: [Errno 11003] getaddrinfo failed' i am getting this error. ](https:/ /i.stack.imgur.com/OTCj4.png) i am trying this way but not enter image description heregetting accurate output. -
psycopg2.errors.UndefinedFunction: function gen_random_uuid() does not exist
Error occurs when trying to run python manage.py migrate in a django application. complete code git clone https://github.com/saleor/saleor.git cd saleor python manage.py migrate psycopg2.errors.UndefinedFunction: function gen_random_uuid() does not exist LINE 1: UPDATE "account_user" SET "uuid" = GEN_RANDOM_UUID() it doesn't work when running but works in running postgres I created extention in postgres, commited that. postgres=# SELECT gen_random_uuid(); gen_random_uuid f36d69b7-5681-4b92-b37e-9b0217b7d829 (1 row) It works fine with docker. Any help will be appreciated. -
Encrpyt URL Id in django
I was trying to excrypt Update URL id to encrpyted format in the url. from my profile page of a user one edit button is there. that button contains url of the update view. #My profile page. code def profile(request): lst = request.user.id #This line is the problem l=[] for i in lst: i['encrypt_key']=encrypt(i['id']) i['id']=i['id'] l.append(i) return render(request, 'profile.html', {'lst':l}) #The update view code def update(request, id): id=decrypt(id) #Update code. return render(request, 'edit_profile.html', context) In the profile page for that edit button, since it is an iteratable for loop I coded like this is the Html template <li class="ctx-item"> <button class="ctx-menu-btn icon-box"> <span class="material-symbols-rounded icon" aria-hidden="true">edit</span> {% for x in lst %} <span class="ctx-menu-text"><a href="/update/{{x.encrypt_key}}">Edit</a></span> {% endfor %} </button> </li> Since three users are there in my database, three edit links are coming. To restrict it in the profile view I have to change the filteration while retriving the user in lst. If i put request.user.id, It is showing the following error. TypeError at /profile/ 'int' object is not iterable Please help me to correct this error. -
django_bootstrap5 not formatting anything
I'm trying to get basic bootstrap formatting working in a django app, and installed django_bootstrap5 to do so. No formatting, however, is getting applied to any of the pages. Here's the various pages: base.html: <!DOCTYPE html> {% load django_bootstrap5 %} <html lang="en"> <head> <meta charset="UTF-8"> <title> {% block title %} {% endblock %} </title> </head> <body> <div class="container"> {% block body %} {% endblock %} </div> </body> </html> I extend this in a simple index page: <!DOCTYPE html> {% extends 'base.html' %} {% load django_bootstrap5 %} {% block title %} Home {% endblock %} {% block body %} <h1>Hello World</h1> {% endblock %} Hello World, however, is not showing up in a container. This is also failing on a form page: <!DOCTYPE html> {% extends 'base.html' %} {% load django_bootstrap5 %} {% block body %} <div class="container"> <h1>Sign Up</h1> <form method="POST"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" value="Sign Up" class="btn btn-default"> </form> </div> {% endblock %} The form is neither in a bootstrap container, nor does it have any styling at all. What am I missing here? Thank you. -
How can I skip pk in url while redirecting to another url with generic RedirectView in Django?
I am trying to delete a record after displaying it with DetailView and redirecting to the list page again. view.py ... class DailyRecordDeleteConformationView(RequiredBasicDetailsAndContextMixin, DetailView): model = DailyRecord obj_not_found_redirect = reverse_lazy('business:add_daily_records') template_name = 'business/daily_records_detail.html' context_object_name = 'record' def get_object(self): detail = self.model.custom_obj.get_single(self) return detail class DailyRecordDeleteView(RequiredBasicDetailsMixin, RedirectView): pattern_name = 'business:daily_records' def get_redirect_url(self, *args, **kwargs): # Delete the record return super().get_redirect_url(*args, **kwargs) ... urls.py ... path('daily-records/', DailyRecordView.as_view(), name='daily_records'), path('daily-records/<int:pk>/', DailyRecordDeleteConformationView.as_view(), name='daily_record_detail'), path('daily-records/<int:pk>/delete/', DailyRecordDeleteView.as_view(), name='daily_record_delete'), ... Here I am getting this below error when click on the delete button on detail view NoReverseMatch at /business/daily-records/7/delete/ Reverse for 'daily_records' with keyword arguments '{'pk': 7}' not found. 1 pattern(s) tried: ['business/daily\\-records/\\Z'] I am new to class based views, and still not able to figure out how to redirect to url that does not have the pk parameter. I tryed to find any variable for RedirectView or something that can skip the pk of current url while redirecting to another url. Thanks. -
how do python handle asynchronous task
I've strong background in a JS frameworks. Javascript is single threaded language and during the execution of code when it encounters any async task, the event loop plays the important role there. Now I've been into Python/Django and things are going good but I'm very curious about how python handle any asynchronous tasks whenever I need to make a database query in django, I simple use the queryset method like def func(id): do_somthing() user = User.objects.get(id=id) do_somthing_with_user() func() another_func() I've used the queryset method that fetch something from database and is a asynchronous function without await keyword. what will be the behaviour of python there, is it like block the execution below until the queryset response, is it continue the execution for the rest of code on another thread. Also whenever we need to make an external request from python, we uses requests library method without await keyword, r = request.get("https://api.jsonplaceholder.com/users") # will the below code executes when the response of the request arrive? do_somthing() . . . do_another_thing() does python block the execution of code until the response arrives? In JS the async task is handled by event loop while the rest of the code executes normally console.log("first") fetch("https://api.jsonplaceholder.com/users").then(() … -
Converting HEIC Images to JPEG in python works on local windows but not working in ubuntu aws gunicorn and nginx server
I'm saving heic images to aws s3 bucket and try to convert it to jpeg before displaying it in the html page using python library Pillow and pillow_heif here is the code for the convertion import boto3 from PIL import Image from io import BytesIO import pillow_heif response = s3.get_object(Bucket=settings.AWS_STORAGE_BUCKET_NAME, Key=self.media.name) image_bytes = response['Body'].read() pillow_heif.register_heif_opener() img = Image.open(BytesIO(image_bytes)) new_name = self.media.name.replace('.heic', '.jpg') # Convert image to JPEG # Create a BytesIO object to save the image img_bytes = BytesIO() img.save(img_bytes, format='JPEG') img_bytes.seek(0) # Upload the image to S3 s3.upload_fileobj(img_bytes, settings.AWS_STORAGE_BUCKET_NAME, new_name) self.converted_image_name = new_name self.save() # Get the object URL url = s3.generate_presigned_url( ClientMethod='get_object', Params={ 'Bucket': settings.AWS_STORAGE_BUCKET_NAME, 'Key': new_name }, ExpiresIn=60000 # URL expiration time in seconds ) when I run that code in my local machine (Windows) in django using python manage.py runserver command it works fine, but when I deploy the code to the aws instance which is running using gunicorn and nginx the url that that code runs in gives 502 Bad Gateway nginx/1.18.0 (Ubuntu) error. And when I tried to check what is the issue, there is no errors came up in the gunicorn logs and nginx logs also. Can anyone please help me with this … -
Unable to fetch Json file in javascript in Django
I have a json file that I would like to fetch in javascript and create divs for it in the webpage. My issue is that I am providing local path of the json file to the fetch method but it is adding it to the django webpage url. The code below tries to fetch the local path of json file: fetch('../../scrapers/jsonOutputs/linkedin_jobs.json') .then(response => response.json()) .then(data => { const jobListings = data.Jobs; jobListings.forEach(job => { const jobTitle = job["Job Title:"]; const employerName = job["Employer name: "]; const jobLocation = job["Job Location: "]; const jobDetails = job["Job Details: "]; const linkToJob = job["Link To Job: "]; const jobListingElement = document.createElement("div"); jobListingElement.classList.add("job-listing"); jobListingElement.innerHTML = ` <h2>${jobTitle}</h2> <p>${employerName}</p> <p>${jobLocation}</p> <div class="job-description-container"> <div class="job-description"> <p>${jobDetails}</p> <a href="${linkToJob}">View Job</a> </div> </div> `; const jobListContainer = document.getElementById("job-list-container"); jobListContainer.appendChild(jobListingElement); }); }); Now when I run the django webapp and inspect element the webpage, I get the following error [Error] Failed to load resource: the server responded with a status of 404 (Not Found) (linkedin_jobs.json, line 0) [Error] Unhandled Promise Rejection: SyntaxError: The string did not match the expected pattern. promiseEmptyOnRejected (jobsearch-func.js:4) promiseReactionJob The inspect element shows http://127.0.0.1:8000/scrapers/jsonOutputs/linkedin_jobs.json which is problematic since this is not the path to my … -
DRF, why my root api urls are got mixed (combined)?
These are my code snippets: # serializers.py from rest_framework import serializers from .models import User class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = '__all__' class UserActivitySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ( 'id', 'email', 'last_login', 'last_requested_at', ) # urls.py router = routers.DefaultRouter() router.register(r'users', UserViewSet) router.register(r'user-activity', UserActivityViewSet) urlpatterns = [ path('', include(router.urls)), ] This leads to combined Root API urls, like so: However this is not the expected behavior. I wanted 2 separate urls. First with all users (for example, localhost:8000/users with all users and localhost:8000/users/ for specific user). And second with user activity API. with those 4 fields. I don't have clue why my urls got combined when I added router.register(r'user-activity', UserActivityViewSet) to my urls.py. Please help with broad explanation, if possible. Thanks! -
ask jinja if a profile exists
How can I check if the object in profile model does not exist in the database, the crearprofile button appears and if it exists, profile appears? {% if user.profile.is_defined %} <a class="nav-link" href="{% url 'profile' user.id %}">Perfil</a> {% else %} <a class="nav-link" href="{% url 'crearprofile' %}">Crear perfil</a> {% endif %} enter image description here check if the object in profile model does not exist in the database, the crearprofile button appears and if it exists, profile appears? -
Django: cannot cast type integer to time without time zone
I've had some previous testing with models and their functionality integration. There were few fields that were using for time input. At first I thought maybe IntegerField will be enough, but as we continue with more new solutions things changed. So there was check_in_time, check_out_time and etc. Now we want to set it to TimeField, but as we are trying to apply the migrations those errors appear. I'm not an postgres guru so I'm scared of breaking things up, cuz migrations might be an pain in the ass. This is the new migration: class Migration(migrations.Migration): dependencies = [ ('property', '0084_rename_max_tenants_property_max_guests_allowed'), ] operations = [ migrations.AlterField( model_name='property', name='check_in_after_time', field=models.TimeField(null=True), ), migrations.AlterField( model_name='property', name='check_in_before_time', field=models.TimeField(null=True), ), migrations.AlterField( model_name='property', name='check_out_after_time', field=models.TimeField(null=True), ), migrations.AlterField( model_name='property', name='check_out_before_time', field=models.TimeField(null=True), ), ] This is our fields that we want to use it right now as TimeFields: check_in_before_time = models.TimeField(null=True) check_in_after_time = models.TimeField(null=True) notice_days_before_check_in = models.PositiveIntegerField(default=0) check_out_before_time = models.TimeField(null=True) check_out_after_time = models.TimeField(null=True) How can I fix it now and prevent it from happening again when migrating this on other servers? LOG: bin/django migrate property Operations to perform: Apply all migrations: property Running migrations: Applying property.0085_auto_20230122_0304...Traceback (most recent call last): File "/home/dziugas/werent/app/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) … -
Slug returns Reverse for '' with arguments '('',)' not found. 1 pattern(s)
I am trying to make it so when I view a blog from any particular link on my website, the url displays www.example.com/view-blog/slug. I have got it working for my images and image title. But I cannot get it to work with blog titles. It keeps returning the error: Reverse for 'viewblog' with arguments '('',)' not found. 1 pattern(s) tried: ['view\-blog/(?P[-a-zA-Z0-9_]+)/\Z']. Models.py class BlogPost(models.Model): blog_title = models.CharField(max_length=100, null=False, blank=False, default="") slug = models.SlugField() blog_article = RichTextUploadingField(null=True, blank=True, default="ici") blog_image = models.ImageField(null=True, blank=True, upload_to="images", default="default.png") blog_date = models.DateField(auto_now_add=True) blog_published = models.BooleanField(default=False) blog_featured = models.BooleanField(default=False) def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.blog_title) super().save(*args, **kwargs) def __str__(self): return self.blog_title Views.py def viewBlog(request, slug): try: blog = BlogPost.objects.get(slug=slug) except BlogPost.DoesNotExist: print("ViewBlog with this slug does not exist") blog = None return render(request, 'view-blog.html', {'blog': blog, 'slug': slug}) Urls.py urlpatterns = [ path('', views.galleryPage, name='gallery'), path('gallery/', views.galleryPage, name='gallery'), path('contact/', views.contactPage, name='contact'), path('blog/', views.blogPage, name='blog'), path('blogs/', views.blogsPage, name='blogs'), path('search-blogs/', views.searchBlogs, name='searchblogs'), path('view-image/<slug:slug>/', views.viewImage, name='viewimage'), path('view-blog/<slug:slug>/', views.viewBlog, name='viewblog'), path('thank-you/', views.thankyouPage, name='thankyou'), path('about-me/', views.aboutmePage, name='aboutme'), ] **One of my templates I wish to link to viewblog page from ** ( I have tried to replace .id on my urls with .slug but this is what gives … -
how test a value in try except block with pytest and coverage in django setting?
I would like to test a Try/Except block, but I try any method Coverage that says that part is not tested. My goal is to test the Error_Message from the user's django settings, and if the user did not define file_validator_error_message in his Django settings, I would like to consider a default value (file} is not valid). Now I want to test the ERROR_MESSAGE value in the area where I test the Attributeerror error but I don't know how? The point is that in line 10 Coverage says: line 10 didn't jump to line 11, because the exception caught by line 10 didn't happen code : try: # Get Error Message From Django Setting ERROR_MESSAGE = settings.FILE_VALIDATOR_ERROR_MESSAGE except AttributeError: ERROR_MESSAGE = "{file} is not valid" except ImproperlyConfigured: ERROR_MESSAGE = "{file} is not valid" I want to test the ERROR_MESSAGE value in the AttributeerRor error section -
How can I get Total Deposit of Customers
I am working on a Django project with 2 Models; Customer and Deposit and I want to display a list of Customers with their names, deposited dated, account number, and Total Deposited within the year so how do I do it the right way. See what I have tried but Couldn't get the Customers' name in my Django Templates. Models: class Customer(models.Model): surname = models.CharField(max_length=10, null=True) othernames = models.CharField(max_length=20, null=True) account_number = models.CharField(max_length=10, null=True) address = models.CharField(max_length=50, null=True) phone = models.CharField(max_length=11, null=True) date = models.DateTimeField(auto_now_add=True, null=True) #Get the url path of the view def get_absolute_url(self): return reverse('customer_create', args=[self.id]) #Making Sure Django Display the name of our Models as it is without Pluralizing class Meta: verbose_name_plural = 'Customer' # def __str__(self): return f'{self.surname} {self.othernames} - {self.account_number}' class Deposit(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True) acct = models.CharField(max_length=6, null=True) staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True) deposit_amount = models.PositiveIntegerField(null=True) date = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse('create_account', args=[self.id]) def __str__(self): return f'{self.customer} Deposited {self.deposit_amount} by {self.staff.username}' here is my view code: def customer_list(request): #Get Current Date current_date = datetime.now().date() #Get Current Month Name from Calendar current_month_name = calendar.month_name[date.today().month] group_deposits = Deposit.objects.filter(date__year=current_date.year).order_by('acct') grouped_customer_deposit = group_deposits.values('acct').annotate(total `=Sum('deposit_amount')).order_by()` context = { 'customers':grouped_customer_deposit,} Here is how I tried to display … -
menu dissapear in django
I have a problem with menu in html in django the problem is in index page menu works perfectly fine, but in other apps such as projects or blog pages menu loads ok but when you scroll down and scroll up menu dissapears and i have to reload the page, i have added menu in database so i can add things in admin panel, here is my codes: views.py def proindex(request): setting = Setting.objects.all().get() menu = SettingMenu.objects.all().get() proj = Project.objects.all() context = {'setting': setting, 'menu': menu, 'proj': proj, 'navbar': 'projects'} return render(request, "projects.html", context) models.py class Setting(models.Model): Website_Title = models.CharField(max_length=200) Footer_Text = models.CharField(max_length=10000) Header_Text1 = models.CharField(max_length=200, default="Text") Header_Text2 = models.CharField(max_length=200, default="Text") Banner_Text1 = models.CharField(max_length=200, default="Text") Banner_Text2 = models.CharField(max_length=200, default="Text") Banner_Button = models.CharField(max_length=200, default="Text") def __str__(self): return "Website Settings" class SettingMenu(models.Model): Admin_Panel = models.CharField(max_length=200) Admin_Link = models.CharField(max_length=200) Menu_Item1 = models.CharField(max_length=200) Menu_Link1 = models.CharField(max_length=200) Menu_Item2 = models.CharField(max_length=200) Menu_Link2 = models.CharField(max_length=200) Menu_Item3 = models.CharField(max_length=200) Menu_Link3 = models.CharField(max_length=200) Menu_Item4 = models.CharField(max_length=200) Menu_Link4 = models.CharField(max_length=200) Menu_Item5 = models.CharField(max_length=200) Menu_Link5 = models.CharField(max_length=200) Menu_Item6 = models.CharField(max_length=200) Menu_Link6 = models.CharField(max_length=200) Menu_Item7 = models.CharField(max_length=200) Menu_Link7 = models.CharField(max_length=200) Menu_Item8 = models.CharField(max_length=200) Menu_Link8 = models.CharField(max_length=200) def __str__(self): return "Menu Settings" base.html <!-- ***** Header Area Start ***** --> <header class="header-area header-sticky"> … -
Django autocomplete prompts are not working on a search bar text field
I am looking to implement autocomplete on a search field which is in the header of each webpage (layout.html). The search bar searches on a model field named 'Title'. While the search itself is working, I cannot get autocomplete to work, any help is greatly appreciated. I will include the search code as well in case they are somehow in conflict in a way I have not identified. Views.py ################# Search ##################### # attempts to search for title, OR Number, OR Title And Number -> looks to replace the '#' before a number if someone enters it that way, it does not always work with # #It works with a partial name OR full name OR number OR Full Name and Number @login_required(login_url="/login/") def SearchPage(request): srh = request.GET.get('search') title = "" number = "" title_match = re.search(r'(.*)\b(#*\d+)', srh) if title_match: title = title_match.group(1) number = title_match.group(2) number = number.replace("#", "") else: title_number_match = re.search(r'(#*\d+)', srh) if title_number_match: number = title_number_match.group(1) number = number.replace("#", "") else: title = srh title = title.strip() number = number.strip() if title and number: comics = ComicInput.objects.filter(Title=title, Number=number,Category='Sell') elif title: comics = ComicInput.objects.filter(Title__icontains=title,Category='Sell') elif number: comics = ComicInput.objects.filter(Number__icontains=number,Category='Sell') else: comics = ComicInput.objects.filter(Category='Sell') params = {'comics': comics, … -
object has no attribute 'title'. Updating Many to many field
am trying to create a form where by a user can upload image. The image and the Item have different form i join them together. The challenge is that Image is related to Item with manaytomyfield. i want after a user saved this form, the items field in images table to be updated to the title field in Items table i try to get this from django document but i realize that the document explaination is static but in my case i want it to be dynamic. this is my view def itemupload(request): message = 'Invalid Form' # success = 'Success' user= request.user items = Items.objects.all() if request.method =='POST': imageform = ImageForm(request.POST, request.FILES) form =ItemsForm(request.POST, request.FILES) if form.is_valid() and imageform.is_valid: item =form.save(commit=False) item.user =request.user item.save() images=imageform.save(commit=False) **images.save() images.items.title.add(item)** return redirect('index') return message imageforms =ImageForm() itemsform = ItemsForm context = { 'imageforms': imageforms, 'itemsform':itemsform, } return render(request, 'jijiapp/itemform.html', context) this is the model class Items(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE, related_name='useritem') title = models.CharField(max_length=10, null=True, blank =True) price = models.CharField(max_length=20, null=True, blank=True) phone = models.CharField(max_length=20, null=True, blank=True) location =models.CharField(max_length=20, null=True, blank=True) post_date = models.DateTimeField(auto_now_add=True, null=True, blank=True) def __str__(self): return self.title class Meta: ordering =['title',] # verbos_name ='Items' class Images(models.Model): image … -
How to - Implement simple Websocket in a Django DRF project created with CookieCutter that sends a simple `unread_count`
I have a project created using cookiecutter-django and has a uvicorn/gunicorn setup I am able to get a ping websocat wss://<url> -v --ping-interval=5 Now I want to create a url what out give unread_count to the request user Is there any way of doing this without using Channels? I am trying to get this done as simple as pissible -
npm rollup.js ReferenceError: _default is not defined
Have spent hours trying to solve this, but have limited experience creating modules. The error returned is: ReferenceError: _default is not defined tsconfig.json { "compilerOptions": { "target": "es5", "jsx": "react", "module": "esnext", "sourceMap": true, "declaration": true, "outDir": "dist" }, "include": [ "src" , "src/index.tsx" ] } rollup.config.js import typescript from '@rollup-plugin-typescript'; import replace from 'rollup-plugin-replace'; export default { input: { Wordpress: 'src/Wordpress.tsx', ContactForm7: 'src/ContactForm7.tsx' }, output: { dir: 'dist', format: 'cjs', }, plugins: [ typescript({ tsconfig: 'tsconfig.json' }), replace({ 'process.env.MY_VARIABLE': JSON.stringify(process.env.MY_VARIABLE) }), ], external: ['react'], }; package.json { "name": "test-wordpress", "version": "1.0.2", "description": "Test project", "main": "./dist/index.d.ts", "type": "module", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "rollup -c --bundleConfigAsCjs" }, "repository": { "type": "git", "url": "git+https://github.com/test-project/nextjs-wordpress.git" }, "license": "ISC", "bugs": { "url": "https://github.com/test-project/nextjs-wordpress/issues" }, "homepage": "https://github.com/test-project/nextjs-wordpress#readme", "devDependencies": { "@types/axios": "^0.14.0", "@types/node": "^18.11.18", "rollup": "^3.10.1", "rollup-plugin-replace": "^2.2.0", "@rollup/plugin-typescript": "^11.0.0" }, "dependencies": { "axios": "^1.2.3" } } ./dist/index.d.ts import { sendForm } from "./ContactForm7"; import { getPage } from "./Wordpress"; declare const _default: { getPage: typeof getPage; sendForm: typeof sendForm; }; export default _default; -
No static files after deploying Django app
I've deployed a multi container Django application to AWS EB with ECS running on 64bit Amazon Linux 2/3.2.3 platform. Here's the Dockerrun.aws.json file. { "AWSEBDockerrunVersion": "2", "containerDefinitions": [ { "essential": true, "image": "${AWS_ACOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com/${IMAGE_NAME}:${IMAGE_TAG}", "mountPoints": [ { "containerPath": "/code/static", "sourceVolume": "web" } ], "name": "web", "hostname": "web", "memoryReservation": 1200, "portMappings": [ { "containerPort": 8000, "hostPort": 8000 } ] }, { "name": "nginx-proxy", "image": "nginx", "essential": true, "memoryReservation": 128, "portMappings": [ { "containerPort": 80, "hostPort": 80 } ], "mountPoints": [ { "sourceVolume": "nginx-proxy-conf", "containerPath": "/etc/nginx/nginx.conf" } ], "links": ["web"] } ], "volumes": [ { "name": "web" }, { "name": "nginx-proxy-conf", "host": { "sourcePath": "/var/app/current/nginx.conf" } } ] } Here's the nginx.conf user nginx; events { worker_connections 1024; } http { server { listen 80; location /static/ { alias /static/; } location / { proxy_pass http://web:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } } This is the Dockerfile. FROM python:3.10 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apt-get update RUN apt-get upgrade -y COPY ./requirements.txt requirements.txt RUN apt-get install -y realmd RUN pip install -r requirements.txt WORKDIR /code EXPOSE 8000 COPY . . RUN chmod +x entrypoint.sh ENTRYPOINT ["./entrypoint.sh"] and the entrypoint.sh #!/bin/bash python manage.py migrate … -
Django templatetag to access arbitrary form field as defined by argument
This particular block of code repeats about a hundred million times, just with different form fields, and so I want to replace all those lines with templatetags: <label for="{{ form.building_name.id_for_label }}">Building</label> <input name="{{ form.building_name.name }}" value="{{ form.instance.building_name }}"> So instead of writing this: <label for="{{ form.building_name.id_for_label }}"> <!-- plus many more lines just for this one element --> <label for="{{ form.building_title.id_for_label }}"> <!-- plus many more lines just for this one element --> ... I am looking to write this: {% someTag 'building_name' %} {% someTag 'building_title' %} After much mucking about, I arrived at one of the ugliest ways of writing an inclusion tag that I've ever had the misfortune of laying eyes on. The convoluted nature of accessing the field is because I found no other way of accessing an arbitrary field of the form. The tag: @register.inclusion_tag("main/sff.html") def sff(form, field_name, label): field = form._meta.model._meta.get_field(field_name) return {'form': form, 'field': field, 'label' : label, 'ph' : placeholder} sff.html: <label for="{{ field.id_for_label }}">{{ label }}</label> <input type="text" \ name="{{ field.name }}" \ value="{{ form.instance.field }}"> </div> With all of that said and done, here's how I call it from my HTML template: {% sff form 'building_name' 'Enter property name' %} … -
Django validate fileds on form
Мне необходимо сделать проверку полей на форме и вывести ошибку в шаблон FORMS class UserForm(forms.Form): first_name= forms.CharField(max_length=20, label='Имя') last_name= forms.CharField(max_length=20, label='Фамилия') password= forms.CharField(label='Пароль') repassword= forms.CharField(label='Подтвердить пароль') def clean(self): cleaned_data = super().clean() self.password = cleaned_data('password') self.repassword = cleaned_data('repassword') if self.password != self.repassword: raise ValidationError('Пароли должны совпадать') VIEW def index(request): form = UserForm() if request.method == 'POST': form = UserForm(request.POST or None) if form.is_valid(): firstname= form.cleaned_data.get("first_name") lastname= form.cleaned_data.get("last_name") password = form.cleaned_data.get('password') re_password = form.cleaned_data.get('repassword') form = UserForm() context = {'form': form, } return render(request, 'create_users/index.html', context) return render(request, 'create_users/index.html', {'form': form}) В результате получаю ошибку dict' object is not callable -
OAuthlib thinks request is insecure because of reverse proxy
I have noticed that for every request, request.scheme is http. I can't find any official source why, but I have been told by my peers this is because of Cloudflare acting as reverse proxy and a tls terminator, causing my server's hosting provider to see http instead of https. One part of my app uses the Google Classroom API, and I have configured a callback to a secure endpoint of my server. Upon attempting to fetch a token from the callback's absolute uri, oauthlib raises oauthlib.oauth2.rfc6749.errors.InsecureTransportError: (insecure_transport) OAuth 2 MUST utilize https. because it thinks the request is http and insecure. I have researched and found out I can set os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' to mitigate this issue, but I am hesitant to do so because I am unsure if that compromises security. My thought process is to manually change the request url to https when I'm absolutely sure it is secure. Inspecting request.META to find which headers are set in the case of a reverse proxied http request, the code looks like this: authorization_response = request.build_absolute_uri() if ( authorization_response.startswith("http://") and request.META["HTTP_X_FORWARDED_PROTO"] == "https" and request.META["HTTP_ORIGIN"].startswith("https") and json.loads(request.META["HTTP_CF_VISITOR"])['scheme'] == "https" ): authorization_response = "https://" + authorization_response[7:] ... fetch the token passing … -
Is there a way to clear the cache of a django form field in the admin page?
My problem is that, on the website I created using django and hosted with apache, after modifying some models through the admin interface I noticed that there is a URLField that whenever the page is reloaded after I make changes this field always loads in the browser with a value in it (even though that field is null in the database) and whenever I forget to check that field and save the model the field will contain that "cached" value that was loaded with the page and save it in the database, and I don't want that. There is also this piece of code in the ModelAdmin class for the model with the described problem that I thought it was the cause of the problem but I don't think it's from this def get_form(self, request, obj=None, change=False, **kwargs): form = super(ResourceAdmin, self).get_form(request, obj, change, **kwargs) if obj and obj.yt_video_id: form.base_fields['youtube_url'].initial = f'https://www.youtube.com/watch?v={obj.yt_video_id}' return form I tried CTRL + F5 since I heard that this way of refreshing clears the cached resources for that website but it didn't work. Is there a way of getting rid of that value that loads in the field whenever I am changing a model on …