Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nginx no access log file
nginx.conf user nginx; worker_processes 8; pid /var/run/nginx.pid; events { worker_connections 2048; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$http_x_forwarded_for - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent $request_time $upstream_response_time "$http_referer" ' '"$http_user_agent"'; access_log /var/log/nginx/access.log main; error_log /var/log/nginx/error.log; server_tokens off; sendfile on; #tcp_nopush on; keepalive_timeout 65; gzip on; gzip_disable "msie6"; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_buffers 16 8k; gzip_http_version 1.1; gzip_types text/plain text/css application/javascript application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript; # set_real_ip_from include /etc/nginx/conf.d/app.conf; } app.conf server { listen 8000 default_server; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; location /ping { access_log off; include uwsgi_params; uwsgi_param SERVER_PROTOCOL $server_protocol; uwsgi_pass unix:///var/data/recommendation/api/run/uwsgi.sock; # uwsgi_pass 127.0.0.1:8000; } location / { include uwsgi_params; uwsgi_param Host $host; uwsgi_param X-Real-IP $remote_addr; uwsgi_param X-Forwarded-For $proxy_add_x_forwarded_for; uwsgi_param X-Forwarded-Proto $http_x_forwarded_proto; uwsgi_param SERVER_PROTOCOL $server_protocol; uwsgi_pass unix:///var/data/recommendation/api/run/uwsgi.sock; # uwsgi_pass 127.0.0.1:8000; } } Docker file FROM public.ecr.aws/nginx/nginx:latest as nginx COPY recommendation/api/nginx/conf.d/ /etc/nginx/conf.d/ COPY recommendation/api/nginx/nginx.conf /etc/nginx/nginx.conf RUN rm /etc/nginx/conf.d/default.conf I am using Nginx + uwsgi + django + docker for my webserver. I need access log to investigate empty_response issue for my django server on local machine(localhost:8000). However, I do not see any of access log or error log created in the desired location. What settings did I put wrong? -
How to run project with Gitlab CI registry variables?
Can you explain. I have Gitlab runner and now I am configuring CI/CD using one guide. It says that runner requires the image names in docker-compose.yml to be named like this: $CI_REGISTRY/organisation/path-to-project/project_image:$CI_ENVIRONMENT_SLUG-$CI_COMMIT_SHA I put this value in a variable in the .env file. But now when I run docker compose up - error pops up - says $CI_REGISTRY, $CI_ENVIRONMENT_SLUG and $CI_COMMIT_SHA are not set. What should I do in this case? Everything was working fine before CI/CD was connected. level=warning msg="The \"CI_REGISTRY\" variable is not set. Defaulting to a blank string." level=warning msg="The \"CI_ENVIRONMENT_SLUG\" variable is not set. Defaulting to a blank string." level=warning msg="The \"CI_COMMIT_SHA\" variable is not set. Defaulting to a blank string." Error response from daemon: no such image: organisation/path-to-project/project_image:-: invalid reference format At the same time docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY in before_script in .gitlab-ci.yml works and variable values are calculated from somewhere. image: docker/compose:alpine-1.28.0 stages: - build - deploy before_script: - apk add make - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY - cp $ENV $(pwd)/src/.env build: stage: build script: - make build push tags: - job:build only: - main environment: name: production deploy: stage: deploy script: - make pull down migrate up … -
jQuery ajax file upload not picking up updated file
Trying to upload a CSV file using HTML form and jQuery. Below are the steps to illustrate the issue 1.) Upload file for the first time, everything goes fine. 2.) Make changes to file and save it (say using MS Excel in this case) 3.) Select the file again and upload 4.) The old file is uploaded, changes made at step2 are not reflecting. 5.) Save-as file with a different name 6.) Upload the file, everything goes fine HTML <form method="post" enctype="multipart/form-data" id="csvform"> <div class="mb-3"> <label class="form-label" for="csvfile">CSV File</label> <input type="file" class="form-control" id="csvfile" placeholder="Select CSV file"> </div> <div class="form-check form-switch mB-20"> <label class="form-check-label" for="update_existing">Update if the record exists</label> <input class="form-check-input" type="checkbox" id="update_existing" name="update_existing"> </div> <button type="submit" class="btn btn-primary btn-color">Upload</button> </form> JS function csv_file_handler() { var fd = new FormData(document.querySelector('#csvform')); $.ajax({ type: 'POST', url: '/uploadcsv/', data: fd, cache: false, processData: false, contentType: false, success: function (response) { $("#upload_status").html(response) $('#csvform').get(0).reset() }, error: function (jqXhr, textStatus, errorMessage) { console.log(jqXhr.responseText) console.log(errorMessage) } }) return false; } $(document).ready(function() { $("#csvform").on('submit', csv_file_handler) }); Page reload doesn't help, tried form reset after each upload etc but no luck. The only thing that works seem to be renaming the file and uploading it. The issue is seen in … -
MultiValueDictKeyError: 'category'
hi guys i am trying to insert information into my database using django and ajax i am quite new to this if i click submit without using ajax the form will submit as expected but if i try using ajax then i get internal server error 500 which make me confusedyour text VIEWS.PY def post_order(request): if request.method == 'POST': order_id = request.POST['order_id'] category = request.POST['category'] product = request.POST['product'] price_per_unit = request.POST['price_per_unit'] quantity = request.POST['quantity'] price_all = request.POST['price_all'] new_order = PoductOrder(order_id=order_id, Category=Category.objects.get(name=category), product=Product.objects.get(name=product), price_per_unit=price_per_unit, qantity=quantity, price_all=price_all ) new_order.save() return HttpResponse('data has being saved') POST.JS $(document).on('submit', '#post_form', function(e){ e.preventDefault(); $.ajax({ type:'POST', url:"/order/postorder", data:{ order_id:$('#order_cart').val(), category:$('category').val(), product:$('#product').val(), price_per_unit:$('#per_unit').val(), quantity:$('#quantity').val(), price_all:$('#total').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, success: function(data){ alert(data); }, error: function(error){ console.log(error) } }); }); MYFORM <div class="row"> <form action="{% url 'post-order' %}" method="post" id="post_form"> {% csrf_token %} <div class="col-sm-4"> <div class="form-group"> <label class="control-label" for="order_id">Order ID</label> <input type="text" name='order_id' class= 'form-control' id='order_cart' > </div> </div> <div class="col-sm-4"> <div class="form-group"> <label class="control-label" for="status">Product Category</label> <select required name="category" id="category" class="form-control"> <option value="">--Select Product Category--</option> {% for category in category %} <option value="{{ category.name }}">{{category.name }}</option> {% endfor %} </select> </div> </div> <div class="col-sm-4"> <div class="form-group"> <label class="control-label" for="customer">Product</label> ` <select required name="product" id="product" class="form-control"> <option value="">--Select Product--</option> {% … -
Problem parsing Django radio button when trying to set checked attribute
I need to build a set of radio buttons using Django. I've taken the approach of doing this in a template rather than a Django Form class as I was hoping it would give me more flexibility. I'm running into a problem when trying to conditionally add a checked attribut to preselect which radio is selected when the form loads. The code below works. It renders the 4 radio buttons and selects the last one. This is just a test obviously as this would always leave the last button selected. But it proves my model, view and template all work. {% for choice in thisSQwithQ.qid.GetChoices %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.choiceid }}" checked="checked" > <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> {% endfor %} But, when I add the Django code to conditionally set checked="checked" for each radio, I'm getting a really odd syntax error. The following code gives me an error "Could not parse the remainder: '==' from 'selected_value=='" {% for choice in thisSQwithQ.qid.GetChoices %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.choiceid }}" {% if selected_value== choice.choiceid %} checked="checked" {% endif %} > <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> {% endfor %} I've had a good … -
Django ModelMultipleChoiceField produces duplicate keys in rls params
I have a form in django with a ModelMultipleChoiceField, but when I submit the data, I have the same parameter repeated in the url for every selected option (like localhost:8000/search/?category=1&category=2). Here's a toy example: #forms.py class SearchForm(forms.ModelForm): category = forms.ModelMultipleChoiceField(Category.objects.all(), required=False) class Meta: model = Document fields = ("start_date", "end_date", "category") #views.py class SearchResultsView(ListView, FormView): model = Document template_name = "archive/document_list.html" context_object_name = "documents" form_class = SearchForm def get_queryset(self): object_list = Document.objects.all() if start_date := self.request.GET.get("start_date"): object_list = object_list.filter(date__gte=start_date) if end_date := self.request.GET.get("end_date"): object_list = object_list.filter(date__lte=end_date) if category := self.request.GET.get("category"): object_list = object_list.filter( category__name=category, ) return object_list.distinct() In the template: <form action="{% url 'search_results' %}" method="get"> <div class="flexline flex-wrap justify-content"> {{ form|materializecss }} <div> <button class="btn" type="submit">Submit</button> </div> </form> The form is displayed correctly: But when I click submit I get the following url: http://localhost:8000/search/?start_date=&end_date=&category=1&category=2 -
How do I allow requests from a frontend server to a django backend to not be prevented by CORS
I have a frontend that sends requests to a django backend. This is some of the contents in my django backend settings.py: INSTALLED_APPS = [ "corsheaders", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", 'api', 'django_extensions', 'rest_framework', 'rest_framework.authtoken', ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "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", ] When sending a request from the frontend which is being run on http://localhost:3000, the following error occurs on django: Forbidden (Origin checking failed - http://localhost:3000 does not match any trusted origins.): /get_user I have also tried adding the following to settings.py in django: CSRF_TRUSTED_ORIGINS = [ "http://localhost:3000", ] This causes the following error instead: Forbidden (CSRF cookie not set.): /get_user Why is this error occuring if I have added the url to CORS_ALLOWED_ORIGINS? -
Django tests - getting BadZipFile with openpyxl
I have an export function for excel files with filters. The file downloads normaly and some manual tests looked fine. I wanted to write unittests to test the filter. For this I read the returned file with openpyxl. There I get the error. export: class DeviceExport(APIView): def get(self, request): response = HttpResponse(content_type="application/vnd.ms-excel") response["Content-Disposition"] = 'attachment; filename="device_export.xlsx"' wb = xlwt.Workbook(encoding="utf-8") ws = wb.add_sheet("device") # write data wb.save(response) return response test: class DeviceExportTest(TestCase): def setUp(self): # some set up def test_filter(self): self.c.login(username="testuser", password="password") mommy.make("app.Device", name="name", serial_number=123) #should be in export mommy.make("app.Device", name="name", serial_number=132) #shouldnt be in export data = {'filter': '{"name": "name", "serial_number": "123"}'} response = self.c.get(reverse('app:export_device'), data) wb = load_workbook(filename=BytesIO(response.content)) #error here ws = wb.worksheets[0].active row_count = ws.max_row error: export with filter ... ERROR ====================================================================== ERROR: test_filter (app.tests.test_device.DeviceExportTest) export with filter ---------------------------------------------------------------------- Traceback (most recent call last): File "/.../app/tests/test_device.py", line 1067, in test_filter wb = load_workbook(filename=BytesIO(response.content)) File "/.../lib/python3.8/site-packages/openpyxl/reader/excel.py", line 315, in load_workbook reader = ExcelReader(filename, read_only, keep_vba, File "/.../lib/python3.8/site-packages/openpyxl/reader/excel.py", line 124, in __init__ self.archive = _validate_archive(fn) File "/.../lib/python3.8/site-packages/openpyxl/reader/excel.py", line 96, in _validate_archive archive = ZipFile(filename, 'r') File "/.../python3.8/zipfile.py", line 1269, in __init__ self._RealGetContents() File "/.../python3.8/zipfile.py", line 1336, in _RealGetContents raise BadZipFile("File is not a zip file") zipfile.BadZipFile: File is not a … -
Django Form ModelMultipleChoiceField issue with saving data to db
I am creating my first proper Django application. It is a Library management system. I have three models: class Authors(models.Model): firstName = models.CharField(max_length=20) lastName = models.CharField(max_length=20) def __str__(self): return f"{self.firstName.title()} {self.lastName.title()}" def save(self): self.firstName = self.firstName.casefold() self.lastName = self.lastName.casefold() super().save() class Books(models.Model): isbn = models.BigIntegerField(primary_key=True, validators=[ MinValueValidator(9780000000000), MaxValueValidator(9799999999999), ]) bookName = models.CharField(max_length=50) authors = models.ManyToManyField(Authors, through='BookAuth') pubName = models.CharField(max_length=20) inventory = models.IntegerField(default=0) def __str__(self): return f"{self.pk} || {self.getName()}" def getName(self): name, bname = self.bookName.split(), "" for x in name: bname += x[0].upper() + x[1:] + " " return bname[:-1] def getAuthors(self): bookAuths = BookAuth.objects.filter(isbn=self.isbn) auth = "" for bookAuth in bookAuths: auth += f"{bookAuth.getAuth()}, " return auth[:-2] def save(self): self.bookName = self.bookName.casefold() self.pubName = self.pubName.casefold() super().save() class BookAuth(models.Model): isbn = models.ForeignKey(Books, on_delete=models.CASCADE) auth = models.ForeignKey(Authors, on_delete=models.CASCADE) def getAuth(self): return Authors.objects.get(id=self.auth.id) def __str__(self): return f"{self.auth} - {self.isbn}" Here I am storing the Books and the Authors separately, and using the BookAuth model to eastablish a ManyToMany relation. I am having problems with adding a new book. For that I have two forms, one to add a new author, and the other to add a new book. The forms.py file looks like this: class AddAuthors(forms.ModelForm): class Meta: model = Authors fields = … -
Django is removing html tags from the description field when we submit the form
I have a model, with description as a field. Basically i am storing the data with html tags like or any other tags for rich text supporting. I have these tags stored in Database until i submit the form , On submit all the tags are lost, and only text is getting saved, after we submit the form. On submit of form I am calling form.save() along with other logics. Tried following ways, gave strip=false in forms, and tried safe filter as wel; and tried few ways with overwriting clean_description methods, nothing seemed to work A solution to store text with tags even after submitting the form -
How can I use this feature of Django in my project?
I just started Django and I faced a problem. I wanna use this {% something %} but the browser consider that as a simple code Picture can explain better this is my code this is the output I did try that on chorome and firefox and the result was same -
How to express a One-To-Many relationship in Django without using foreignkey in class on the side many-relation?
I have a project to manage Assets in company. Asset is the core of project. I need to express One-To-Many relationship and Many-To-Many with Assets and the only way I know that: class List(models.Model): name = models.CharField(max_length=128) class Asset(models.Model): list = models.ForeignKey(List) I don't think that a good way because I have more classs like List in the project and if I do that, Asset will be have too much attributes are not necessary, when I have a new Asset I need to declare the attribute "list" - that impossible if that list doesn't exist (new list in future). Is there any way? Thanks for your help! -
problem in makeing one to one relation in django
I am creating a website where admin will have the right to register the clinic/patient and fill his complete details wile registration Below is my code model.py import django from django.db import models from django.contrib.auth.models import AbstractUser class Registered_user(AbstractUser): is_clinic = models.BooleanField(default=False) is_patient = models.BooleanField(default=False) token = models.CharField(max_length=120, default=None, null= True) forgot_token = models.CharField(default=None, max_length=120, null=True), email = models.EmailField(unique = True, max_length=254, verbose_name='email address') #clinic class Clinic(models.Model): register_user = models.OneToOneField(Registered_user, on_delete=models.CASCADE, primary_key=True,) clnc_name = models.CharField(max_length=255) clnc_phone = models.BigIntegerField(null= True) clnc_contact_name = models.CharField(max_length=255) clnc_Job_Title = models.CharField(max_length=255) clnc_address_line1 = models.CharField(max_length=255) clnc_address_line2 = models.CharField(max_length=255) clnc_county = models.CharField(max_length=255) clnc_postcode = models.CharField(max_length=255) clnc_town_city = models.CharField(max_length=255) clnc_created_at = models.DateTimeField(auto_now_add=True) clnc_status = models.BooleanField(default=False) updated = models.DateTimeField(auto_now=True) published = models.DateTimeField(default=django.utils.timezone.now) View.py from django.shortcuts import render, redirect from adminPanel.models import Registered_user from adminPanel.models import Clinic def create_clinic(request): """This function will handle the process of registering new clinic to the portal, where user can register with following attributes clinic_name, contact_name, Job_Title, address_line1, address_line2, county, postcode, town_city, clinic_email, clininc_phone Args: request: client to server request Returns: title: This will pass the title from backend to the html """ title = 'Create Clinic' request_url = request.get_full_path() if request.method == "POST": domain_name=get_current_site(request).domain token=str(random.random()).split('.')[1] link=f'http://{domain_name}/resetpassword/{token}' clinic_name = request.POST.get('clinic_name') contact_name = request.POST.get('contact_name') Job_Title = request.POST.get('Job_Title') … -
how to secure my db password in django using ini file
Hi Everyone i am working on django project but my db and other password is not secure, i need to secure these password on production server, pls help me out. below i have shared my current code. config.ini [db_setting] SCHEMA = db_schema MAX_CONNECTION_AGE = 600 DB_USER = admin DB_PASSWORD = admin123 DB_HOST = localhost DB_PORT = 5432 settings.py import os from configparser import RawConfigParser home = os.path.dirname(os.path.realpath(__file__)) config_path = str(home) BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Read config file config = RawConfigParser() config.read(os.path.join(config_path, 'config.ini')) LOG_PATH = config['config']['LOG_PATH'] MAX_CONNECTION_AGE = int(config['db_setting']['MAX_CONNECTION_AGE']) DB_USER = config['db_setting']['DB_USER'] DB_PASSWORD = config['db_setting']['DB_PASSWORD'] DB_HOST = config['db_setting']['DB_HOST'] DB_PORT = config['db_setting']['DB_PORT'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'db', 'USER': DB_USER, 'PASSWORD': DB_PASSWORD, 'HOST': DB_HOST, 'PORT': DB_PORT, 'CONN_MAX_AGE': MAX_CONNECTION_AGE, 'OPTIONS': {'options': '-c search_path=' + SCHEMA + ',public'} }, i have trying to using environment variable to secure my sensitive information in above i have already shared on above -
Django Form with If function produce same result for every if combination
I'm still learning Django, and in this project of mine I try to create very simple quizz-like program that will recommend programming language based on user interest. So, There are 3 question, user only need to answer yes/no After the form is submitted, it'll be processed using if and recommendation will be produced according to user answer example: if user answer yes, yes, yes, my program will recommend "Javascript, HTML/CSS, React JS, Angular,Figma". if user answer yes, yes, no, my program will recommend "HTML/CSS, Javascript, Flutter" And the problem is, no matter what combination I use, my program will always return "Javascript, HTML/CSS, React JS, Angular, Figma"(first response in my if) Here is the detail of my code models.py from django.db import models # Create your models here. class User(models.Model): name = models.CharField(max_length=20) def __str__(self): return f"{self.name}" class Answer(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE) webdev = models.BooleanField(default=True) mobdev = models.BooleanField(default=True) uiux = models.BooleanField(default=True) def __str__(self): return f"{self.name.name}, {self.webdev}, {self.mobdev}, {self.uiux}" class Result(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE) response = models.CharField(max_length=50, default='Unidentified') def __str__(self): return f"{self.name.name} {self.response}" forms.py from django import forms class Quizzes(forms.Form): CHOICES = [ (True, 'Tertarik'), (False, 'Tidak Tertarik') ] name = forms.CharField(label='Siapakah nama anda?', max_length=20) wd = forms.ChoiceField( widget … -
Why is Google Chrome ignoring my cookie deletion request?
I am building a web application with Vue for the frontend running on localhost:5173 and using Django with DRF for the backend running on localhost:8000. I had no trouble writing the refresh token in the cookies for the login process. However, now I am trying to implement a logout feature which should delete the refresh token from the cookies, but for some reason it's not working - the cookie that was originally created during login doesn't get deleted and I'm not sure why. The cookie gets deleted just fine in Postman, but when I try to do it in a browser, it does not. Also, you can see in Chrome that the HTTP response header also is set to Set-Cookie: refresh_token=""; expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/ which I believe should signal to the browser to delete the cookie. It appears that the browser is ignoring that request. Any ideas why? In Django, during the login process, I am using the DRF function set_cookie to set the cookie using response.set_cookie(key='refresh_token', value=refresh_token, httponly=True) This works as expected. During the logout process, I am using the DRF function delete_cookie to delete the cookie, which isn't working. My Django views looks … -
Django-eventstream and Channels causes too slow page load
I have django project that users send notifications to my custom admin dashboard, i am using django-channels 3.0.5 and django-eventstream for it. Everything is okay, users can send notifications to my admin dashboard but sometimes when i want to change page, for example i am in contacts page and i want to any other page, page stucks at loading about one minute. Then loads all content with no error. everything is okay again. I think it's because django-channels, when i disable channels in asgi.py all pages loading fast. Here is my code: contact form views.py (it sends notification to me). everything is okay here def contact(request): if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): user_profile = UserProfile.objects.get(user=request.user) contact_message = form.save(commit=False) contact_message.user_profile = user_profile contact_message.save() messages.success(request, "Mesajınız göndərildi") send_event('contact', 'message', {'text': 'hello world'}) else: form = ContactForm() context = { 'form': form, } return render(request, 'site/contact/contact.html', context) asgi.py os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") application = ProtocolTypeRouter({ 'http': URLRouter([ path('contact-events/', AuthMiddlewareStack( URLRouter(django_eventstream.routing.urlpatterns) ), { 'channels': ['contact'] }), path('security-events/', AuthMiddlewareStack( URLRouter(django_eventstream.routing.urlpatterns) ), { 'channels': ['securitycalls'] }), re_path(r'', get_asgi_application()), ]), }) -
Replace data from server with data from local storage if it exists - Django
I know this might seem like a very basic question but I am still a beginner and trying to figure this out. I have created a webpage containing a form in Django. Right now the form comes prefilled with a few values and the user has to fill in the rest. It has different sections like education, work experience, basic info, etc and the user can add or delete multiple sections in education. The form data is ultimately stored in a JSON. Right now every time a user clicks on add or delete the data manipulation happens in the frontend but just so that the changes reflect in the page I have to send it to the backend and reload the page. FRONT END DISPLAY FORM CODE: <h2>Technical Skills</h2> {% for item in resume.techskill %} <fieldset> <div class="tech"></div> <legend>Technical Skill {{ forloop.counter }}</legend> <label for="skillName{{ forloop.counter }}">Skill Name:</label> <input type="text" id="skillName{{ forloop.counter }}" name="skillName{{ forloop.counter }}" value="{{ item.skill_name }}"><br><br> <label for="expertise{{ forloop.counter }}">Expertise:</label> <input type="text" id="expertise{{ forloop.counter }}" name="expertise{{ forloop.counter }}" value="{{ item.expertise }}"><br><br> <label for="yearOfExp{{ forloop.counter }}">Year of Experience:</label> <input type="text" id="yearOfExp{{ forloop.counter }}" name="yearOfExp{{ forloop.counter }}" value="{{ item.year_of_exp }}"><br><br> <button type="button" onclick="deleteTechSkill('{{forloop.counter}}')">Delete Technical Skill</button><br><br> </fieldset> {% endfor %} … -
In Django Rest Framework (DRF) how to do pagination when we are getting page number from request body?
Generally, when we use pagination in Django Rest Framework (DRF), from URL we are sending parameters like some-url/?page=2&page_size=50 Now, in my case, I'm sending a request with those parameters being sent from the request with the below payload. pagination : { "page": 2, "page_size": 50 } How to get this paginated when a request is made with any page number? -
Clean method and validation of individual fields
I have a model with some fields with blank=False. I have a form: class FipiForm(ModelForm): def _validate_ready_for_whole_exam(self, cleaned_data): ... def _validate_modify_spoilt_task(self, cleaned_data): ... def _validate_correspondene_of_modification_to_task(self, cleaned_data): ... def clean(self): cleaned_data = super().clean() # Breakpoint self._validate_ready_for_whole_exam(cleaned_data) self._validate_modify_spoilt_task(cleaned_data) self._validate_and_modify_spoilt_task(cleaned_data) self._validate_and_modify_spoilt_task(cleaned_data) self._validate_correspondene_of_modification_to_task(cleaned_data) return cleaned_data class Meta: model = FipiTask exclude = [] I intentionally left some fields empty. Well, form is not valid. What I'd like to have is delegate validation of fields to Django. And in clean method I would like to validate interdependence between fields. In other words I thought that if method super().clean() has been called, blank=False has already been validated. But I was wrong. Could you tell me what to do: either validate individual fields here, in "clean" method? But that looks contrary to the idea of the framework. -
unable to retrieve data selected in view function
` Hi team i am unable to retrieve only media_data in view function . Please find the data below : "data": { "id": "63f4625a1393d5ff8037a249", "group_name": "Favorites", "slug": "favorites", "parent_id": null, "updated_at": null, "media_data": { "totalAssets": 2, "media": [ { "id": "63f849271393d5ff8037a2e5", "group_id": "63f4625a1393d5ff8037a249", "content_type": "videos", "created_at": "2023-02-24T05:20:39.461000" }, { "id": "640abd2e1393d5ff8037a3cf", "group_id": "63f4625a1393d5ff8037a249", "content_type": "videos", "created_at": "2023-03-10T05:16:30.210000" } ] } }, "status": true } `Here is my view function: def fav_view(request): context={} context= data context['title'] = 'Favourite data return render(request, 'admin/favourite_data.html',context) `When i am printing the data i am getting the whole data but i want to have only media_data. Please assist -
Django mistakes a custom button in list display as a non-existing field in admin.TabularInline
Here is how my model and admin looks like: Model class Event(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=120) description = models.TextField(default="", blank=True) start = models.DateTimeField(default=datetime.now) end = models.DateTimeField(blank=True, null=True) parent_event = models.ForeignKey( to="Event", on_delete=models.CASCADE, blank=True, null=True) Admin EVENT_DISPLAYABLE_FIELDS = ["title", "start", "end"] # Will display and allow adding inline sub events # in tabular format class SubEventInline(admin.TabularInline): model = Event # Do not add empty extra inlines extra = 0 # Will allow only the fields listed below # to be displayed and edited fields = EVENT_DISPLAYABLE_FIELDS # Will allow navigating to its edit page show_change_link = True # Will display the Event edit page on admin site class EventAdmin(admin.ModelAdmin): # Will only display the fields listed below # on the main events page list_display = EVENT_DISPLAYABLE_FIELDS list_display.append('preview') # Enables sub events to be displayed or allowed # to be added in the current event's edit page inlines = [ SubEventInline, ] def preview(self, event): url = reverse('events', kwargs={'id': event.id}) return format_html('<a class="button" href="{}">Preview</a>', url) preview.short_description = 'Preview Event' preview.allow_tags = True The above correctly displays the button on the list display view, but when clicking on any event to navigate to it's change/edit page, django throws an error: django.core.exceptions.FieldError: … -
xhtml2pdf - Creating a pdf and emailing as an attachment
I am trying to create a pdf of a template and then have it automatically send an email to the contractor with the created pdf as an attachment. Emails: I am able to send basic email without any issues Create PDF: I am able to create the pdf with out any issues. The issue is trying to combine the two features. I am not sure if I have to have the pdf automatically save to a location on the server and then attach the pdf to an email or if I can create the pdf and then email out in the same code. def vendorwopdf(request, *args, **kwargs): wonumb = kwargs.get('WorkOderNumb') searchresult = WorkOrders.objects.get(WorkOderNumb=wonumb) template_path = 'workorders/workorderpdf.html' context={"searchresult":searchresult} response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="workorder.pdf"' #response['Content-Disposition'] = 'filename="Workorder.pdf"' template = get_template(template_path) html = template.render(context) pisa_status = pisa.CreatePDF( html, dest=response) if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response subject = "RE: Workorder # " + wonumb message = "Greetings please find attached the approved workorder" from_email = settings.EMAIL_HOST_USER to_list = [emailreceiver] email.attach_file(pisa_status) send_mail(subject, message, from_email, to_list,email.attach_file, fail_silently=False) return render(request,'workorders/vendorwo.html',{"searchresult":searchresult}) -
Redirect from Django template to edit a specific user
I'm trying to allow a link b/w a template http://localhost:8000/userSettings/ and and an individual user account on the admin page (allow admin user the ability to change permissions) http://localhost:8000/admin/auth/user/1/change/ I'm trying to do it w/ an tag within the template: <a target="_blank" href="{% url 'admin:auth_user_changelist' %}">link</a> This works fine for directing to http://localhost:8000/admin/auth/user/ , but I'm trying to get to http://localhost:8000/admin/auth/user/1/change/ I also tried <a target="_blank" href="{% url 'admin:auth_user_changelist' user.id %}">link</a> but I get the error Reverse for 'auth_user_changelist' with arguments '(1,)' not found. 1 pattern(s) tried: ['admin/auth/user/\\Z'] Any idea how I can direct a user to the edit page of a specific user? -
in python how can I display the registered soccer teams in a chart?
below is my code and excel file i generated with this, now i need to display the teams in figure as a knockout tournament, from django.shortcuts import render from .models import Team, TieSheet from openpyxl.utils import get_column_letter from openpyxl.styles import Font from openpyxl import Workbook from django.http import HttpResponse import pandas as pd from openpyxl.styles import Font, PatternFill, Alignment, borders from django.http import HttpResponse from openpyxl import load_workbook from django.core.files import File from django.core.files.base import ContentFile def tie_sheet(request): # Load the Excel template workbook = load_workbook(filename='static/excel/Tie-sheet.xlsx') # Get the active worksheet worksheet = workbook.active # Create merged cell for POLL1 and POLL2 columns and set heading worksheet.merge_cells(start_row=1, start_column=2, end_row=1, end_column=3) worksheet.cell(row=1, column=2, value='POLL1') worksheet.cell(row=1, column=4, value='POLL2') # Get the teams from the database teams = Team.objects.all().order_by('?') # Fill the data into the worksheet row_num = 2 count = 1 col = 2 for team in teams: cell = worksheet.cell(row=row_num, column=col, value=team.title) cell.border = borders.Border(left=borders.Side(style='thin'), right=borders.Side(style='thin'), top=borders.Side(style='thin'), bottom=borders.Side(style='thin')) if col == 2: col = 4 row_num = row_num elif col == 4: col = 2 row_num += 2 count = count+2 # Add spacing between rows and columns for row in worksheet.iter_rows(min_row=1, max_row=1): for cell in row: cell.font = Font(size=12, bold=True) …