Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to replicate RegisterSerializer.custom_signup for social signups
I have overridden RegisterSerializer.custom_signup (REGISTER_SERIALIZER) to set certain parameters in the user's profile based on cookie values and it works fine when a user registers using email/password. However, what I realized was that it's not getting called when the user registers through social (Google, specifically). I found SocialLoginSerializer.post_signup which sounds like it might be the right place to inject similar logic, but I am not sure how to tell dj_rest_auth to use the overridden class. There does not appear to be an equivalent to the REGISTER_SERIALIZER config variable that points to the new class. I also considered moving this logic to User's post_save signal event, but unfortunately one can't access the request therefore any cookies from there (without some middleware acrobatics). I am using dj_rest_auth 4.0.1 and allauth 0.50.0 Thanks in advance for any pointers. -
How can I filter my contacts by user that it belongs?
I need to show names that belong only to one user.. models.py class Contact(models.Model): name = models.CharField(max_length=50, null=False, blank=False, unique=False) surname = models.CharField(max_length=50, null=True, blank=True, unique=False) father_name = models.CharField(max_length=50, null=True, blank=True, unique=False) dob = models.DateField(null=True, blank=True, unique=False) photo = models.ImageField(upload_to='static/photos/', null=True, blank=True) email = email = models.EmailField(max_length=254, null=True, blank=True, unique=False) phone_number = models.CharField(max_length=12, null=False, blank=False, unique=False) contact_belongs_to = models.ForeignKey(User, on_delete=models.CASCADE) views.py def post(self, request:HttpRequest)->HttpResponse: form = ContactForm(request.POST) if form.is_valid(): Contact.objects.create(name=form.cleaned_data['name'], surname=form.cleaned_data['surname'], father_name=form.cleaned_data['father_name'], dob=form.cleaned_data['dob'], photo=form.cleaned_data['photo'], email=form.cleaned_data['email'], phone_number=form.cleaned_data['phone_number'], contact_belongs_to=request.user).save() return HttpResponse('OK') else: return render(request, 'contacts/contact_form.html', context={'form':form}) this is how 'contact_belongs_to' takes value->user And when user wants to see only his own contacts I should filter them by 'contact_belongs_to' or no? Could you help please... -
Unable to list all api endpoints in swagger file in django and drf spectacular
Unable to list all api endpoints in swagger file. API endpoints are working as expected wrt functionalities. I'm using py3 and gunicorn as I need this deployed. Settings.py of djServer project has all req settings REST_FRAMEWORK = { 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema' } # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'drf_spectacular', 'corsheaders', 'djApi', 'djBookings', 'sample', ] #djServer/djServer/urls.py """ URL configuration for djServer project. The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/5.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from drf_spectacular.views import( SpectacularAPIView, SpectacularSwaggerView, ) from django.contrib import admin from django.urls import path, include, re_path from django.contrib import admin from django.urls import path, include, re_path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('help/Schema/',SpectacularAPIView.as_view(),name='help-schema'), path('help/Docs/',SpectacularSwaggerView.as_view(url_name='help-schema'),name='help-docs'), path('sampleApi/', include('sample.urls')), path('api/', include('djApi.urls')), path('bookings/', include('djBookings.urls')), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) While the project has many djnago apps … -
Chaining django queries on dates not working as expected
I have a Django 4.2 app with a model Album. The Album model has a DateTimeField called date. I run a query to select albums by the year in launch_date: >>> launch_date = datetime(2014, 5, 10) >>> albums = Album.objects.filter(date__year=launch_date.year) >>> albums <QuerySet [<Album: 732 - September 30, 2014>, <Album: 734 - February 6, 2009>, <Album: 735 - March 29, 2010>, <Album: 736 - April 5, 2010>, <Album: 738 - May 20, 2014>]> >>> for a in albums: print(a.album_id, a.date.year, a.date.month) 732 2014 10 734 2014 10 735 2014 10 736 2014 10 738 2014 5 Which is what I expected. However, when I run this query to further filter the albums by month, it fails. I expected the query to return the one album with album_id = 738: >>> albums.filter(date__month=launch_date.month) <QuerySet []> These chained filters do not produce the results I expected, either: >>> Album.objects.filter(date__year=2014, date__month=5) <QuerySet []> >>> Album.objects.filter(date__year=launch_date.year).filter(date__month=launch_date.month) <QuerySet []> What am i doing wrong? -
Django messages with javascript fetch() API and redirect
I am doing a request with the fetch() API to a django view, which will set a message with the messages app and redirect the request. I can capture the redirect with response.redirected and the messages-cookie is set, but when i do the redirect with location.replace, the messages get lost. How do i pass on the messages from the original response? The django view: def add(request): if request.method != 'POST': return HttpResponse("not post") pproject = request.POST['pproject'] print("pproject:", pproject) messages.add_message(request, messages.INFO, "Test.") return redirect("project_detail") my urls.py: path('project/add/', views_project.add, name='project_add'), and in my template (javascript): var csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; const headers = new Headers(); headers.append("X-CSRFToken", csrftoken); const form = new FormData(); form.append("pproject", "{{ project.id }}"); const ops = { method: "POST", headers: headers, body: form, credentials: "same-origin" }; const req = new Request("{% url 'project_add' %}"); fetch(req, ops) .then((response) => { if (response.redirected) { console.log("response redirect:", response); window.location.replace(response.url); return false; } else if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } else { return response.json(); // Parse JSON response } }) -
Passing Form Data to pre-select django-filter sets before loading view
My problem: I'm utilizing Django and bootstrap4 crispy forms to simply display data from one of my database tables with a django-filters included in order to provide more in-depth information. The issue is, this table can have upwards of 20 million records. Though I've implemented a pagination technique to allow for loading all 20 million records rather quickly... it is still not ideal! What I would like to do is create a non-model-based form that I can use to get the request.POST.get() data and load the view with 2 of my django-filters selected and "locked." I already have the form and structure in place to successfully load all records and filter, I'm just not quite sure how to actually pass the data from my form to my view and render it with 2 filters pre-selected, locked so users can't change them... I know I'll need to load the model based on the filter selection but need help with how to pass that data and use it to render the view with filters pre-selected and applied. Consider the example/flow below as expected behavior: example flow -
Websites and their release on the Internet [closed]
Hello, I need to bring the site online, I have html and css, how do I bring them online, should I use something? according to the Django/React type, how were sites displayed before? to put them on the server I do not know what to try and how to start, I think to start with django or what? -
Do redirect with a imported function in a called view
I have a Django App "A" with a view "view_A" where I execute a function: from app_B.views import usercheck_B def view_A(request): function_B(request) return render(request) And in my Django App "B" with a function "usercheck_B": def usercheck_B(request): if not request.user.is_authenticated: redirect('view_B:login') What I want is, that a directly redirect the client if he is not logged in in the called function. But that is not working. I only can return a Httpresponse to my first called view "view_A" a redirect to login. My idea is to place the usercheck_B function in every view I have and redirect visitors. But I want to do this check also in special cases if for exapmple other parameters are not fitting. -
if user is already logged in do not show sign in form
I have used User Creation Form for user registration. class UserSignUpView(SuccessMessageMixin, FormView): form_class = UserCreationForm success_url = reverse_lazy('login') template_name = 'core/signup.html' success_message = 'Account created successfully.' When user is already logged in it should not see the signup form -
TypeError: 'module' object is not iterable. Django DeleteView
I am writing Django app named polls I decided to put Deleteview there in polls/views.py I put from django.views.generic.edit import DeleteView class QuestionDelete(DeleteView): model = Question success_url = reverse('polls:index') in polls/urls.py in urlpatterns I added a line path('createnewchoice/', views.create_question_with_choices, name="create_new_choice_question"), and in templates/polls I created question_confirm_delete.html <form method="post">{% csrf_token %} <p>Are you sure you want to delete "{{ object }}"?</p> {{ form }} <input type="submit" value="Confirm"> </form> Before that always worked fine but after I run python manage.py runserver I get folowing Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/myuser/PycharmProjects/mypolls1/venv/lib/python3.11/site-packages/django/urls/resolvers.py", line 740, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/threading.py", line 1038, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "/Users/myuser/PycharmProjects/mypolls1/venv/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/myuser/PycharmProjects/mypolls1/venv/lib/python3.11/site-packages/django/core/management/commands/runserver.py", line 133, in inner_run self.check(display_num_errors=True) File "/Users/myuser/PycharmProjects/mypolls1/venv/lib/python3.11/site-packages/django/core/management/base.py", line 486, in check all_issues = checks.run_checks( ^^^^^^^^^^^^^^^^^^ File "/Users/myuser/PycharmProjects/mypolls1/venv/lib/python3.11/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/myuser/PycharmProjects/mypolls1/venv/lib/python3.11/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) ^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/myuser/PycharmProjects/mypolls1/venv/lib/python3.11/site-packages/django/core/checks/urls.py", line 24, in check_resolver return check_method() ^^^^^^^^^^^^^^ File "/Users/myuser/PycharmProjects/mypolls1/venv/lib/python3.11/site-packages/django/urls/resolvers.py", … -
Troubleshooting TemplateDoesNotExist Error in Django Despite Correct Configuration
I'm relatively new to Django and encountering an issue with template loading in my project. Despite following tutorials and setting up my project structure correctly, I'm facing a TemplateDoesNotExist error. Here's my project structure: storefront\__pycache__ storefront\storefront\__init__.py storefront\storefront\asgi.py storefront\storefront\settings.py storefront\storefront\urls.py storefront\storefront\wsgi.py playground playground\__pycache__ playground\migrations playground\templates playground\__init__.py playground\admin.py playground\apps.py playground\models.py playground\tests.py playground\urls.py playground\views.py db.sqlite3 manage.py In my settings.py, the template configuration is as follows: python TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] However, when trying to render a template using the render function in my view: #python from django.shortcuts import render def say_hello(request): return render(request, 'playground/hello.html') I'm encountering the TemplateDoesNotExist error for playground/hello.html. I've verified my project structure, and it appears to be correct. Could someone provide guidance on what might be causing this issue and how to resolve it? Any beginner-friendly explanations or suggestions would be greatly appreciated! -
Django behind Apache and Traefik and CSRF
I use Cookiecutter Django as a starter for my projects, and it uses Traefik (within a Docker container) to generate certificates using Let's Encrypt. However, my company mandates the use of Apache as the proxy for all servers, and the management of the Apache server is handled by another team. To accommodate this, I disabled the Traefik certificate generation, made necessary configuration changes, etc. Everything was functioning correctly, except for the CORS protection. I encountered a 403 error on every POST request, and the log indicated the following warning: WARNING 2024-02-09 08:49:15,953 log Forbidden (Origin checking failed - https://example.com does not match any trusted origins.): /accounts/login/ Upon investigating, I found that adding the setting CSRF_TRUSTED_ORIGINS solves my problem. Adding CSRF_TRUSTED_ORIGINS=https://example.com to my config file resolved the issue. My question is: is this approach considered unsafe? -
Django Ajax & the Prevention of Refresh on Form Submission
So I have Django-based from which works perfectly (I know, something actually works for once, whoop-de-do! Who knew?), submits as expected with no issues whatsoever. However, Ajax is another kettle of fish. This Ajax script is supposed to tell the browsers not to refresh the page when the user submits information using the form below. Although strictly speaking it, it actually does stop the browser window from refreshing, it also turns the submission button into a dead. You click it, & nada. <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> </head> {% if request.method == 'POST' %} <h1>Thank you for your feedback.</h1> <h2>If you have provided your contact details, we will be in touch shortly.</h2> <p>Your feedback wll be invalvuable to us. In the meantime why not:</p> <a href="#" title="Browse our other vacancies">Browse our other vacancies.</a> {% else %} <h1>Apply for this position</h1> <H2>Apply for this position. Please fill this to with the accuracy to the best of your knowledge.</H2> <form method="POST" id="post-form" enctype="multipart/form-data"> {% csrf_token %} <!--Form fields--> <button type="submit" class="btn btn--primary">Submit</button> </form> {% endif %} <script> $(document).on('submit', '#post-form', function(e) { e.preventDefault(); $.ajax({ type:'POST', url:"{% url 'careers' %}", <!--Sourced from 'path('',views.careers, name="careers"),' in `urls.py`--> data:{ id_name:$('#id_name').val(), id_message:$('#id_message').val(), id_email:$('#id_email').val(), id_number:$('#id_number').val(), <!--Taken from … -
Django translation files not generated inside locale directory in a specific app
I have no issue with running django-admin makemessages --all from the base directory and the .po files are being generated inside the locale directory in my main app but I have an issue with generating the same files in my specific apps. my project looks like this ├── about_page ((but this one is not filled) ___ en ___ de ___ es ___ fr ├── accessories ├── callibrators ├── careers ├── contact_page ├── db.sqlite3 ├── dimensional_measurement ├── leak_testing ├── locale ___ en (these files are filled with .po files) ___ de ___ fr ___ es ├── manage.py ├── mysite ├── newsnevents_page ├── polls ├── products_page └── services my settings.py has from django.utils.translation import gettext_lazy as _ LANGUAGES = [ ('en', _('English')), ('de', _('German')), ('fr', _('French')), ('es', _('Spanish')), ] LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale'), os.path.join(BASE_DIR, 'about_page', 'locale'), ] # Application definition INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'about_page.apps.AboutPageConfig', 'contact_page.apps.ContactConfig', 'products_page.apps.ProductsPageConfig', 'careers.apps.CareersConfig', 'newsnevents_page.apps.NewsneventsPageConfig', 'dimensional_measurement.apps.DimensionalMeasurementConfig', 'leak_testing.apps.LeakTestingConfig', 'callibrators.apps.CallibratorsConfig', 'services.apps.ServicesConfig', 'accessories.apps.AccessoriesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_recaptcha', 'rosetta', #NEW ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' when I execute this from the project's base directory django-admin makemessages --all the locale in base directory is filled but the about_page's … -
http://127.0.0.1:8000/ This site can’t be reached127.0.0.1 refused to connect
I created my program in pycharm. It is a series of questions for the user that adds their inputs and get a result from it, pretty basic stuff. I want to share the program with my colleagues, but they are not interested in the coding part, they want to see how it works. So I thought did a little research and decided to test Django. I installed django 4.2.10 and followed chatgtp's steps. Now I have the following folders and files: HYSPI_project/ |-- HYSPI_app/ # Your Django app |-- HYSPI_project/ # Your Django project folder | |-- __init__.py | |-- asgi.py | |-- settings.py | |-- urls.py | |-- wsgi.py |-- db.sqlite3 |-- manage.py |-- python Everything looks good, but when I run python manage.py runserver, the only thing that happens is that my program starts, in bash (mamba). If I try to open http://127.0.0.1:8000 in the browser it says the site cannot be reached. I have verified everything, connection, firewall, and all suggestions from chatgpt. Maybe the problem is in one of my files, manage.py, urls.py, settings.py, but when I ask chatgpt it always says that everything looks ok, and asks me for more information on the error when … -
How to import and use a file in django project folder
Project structure I'm trying to import the file "am_model.py" in backend/api/views.py. The "am_model.py" uses files from the easy_ViTPose folder (it is a github directory). Relative import does not work as it gives me: ImportError: attempted relative import beyond top-level package. Any ideas how can I import this in views.py? Thank you. -
How to show all questions and answer inputs in Django?
I made this models, urls, etc, but it doesn't show all questions/pertanyaan that I made. It also didn't save the answers/jawaban through database. Idk which one is having error. Here's my code, though : views.py from django.shortcuts import render, redirect from .models import Pertanyaan from django.contrib.auth import authenticate, login from django.contrib.auth.decorators import login_required from .forms import JawabanForm from django.contrib import messages @login_required def get_pertanyaans(request): if request.method == 'POST': jawab_form = JawabanForm(instance=request.user, data=request.POST) if jawab_form.is_valid(): jawab_form.save() messages.success(request, 'Anda berhasil menjawab kuisioner') else: messages.error(request, 'Anda gagal menjawab kuisioner') else: jawab_form = JawabanForm(instance=request.user) return render(request, 'survey/kuisioner.html', {'jawab_form':jawab_form}) models.py from django.db import models from django.contrib.auth.models import User class Kuisioner(models.Model): judul = models.CharField(max_length=255) alias = models.SlugField(max_length=255, unique=True) class Meta: ordering = ['judul'] def __str__(self): return self.judul class Pertanyaan(models.Model): kuisioner = models.ForeignKey(Kuisioner, related_name='pertanyaans', on_delete=models.CASCADE) pertanyaan = models.CharField(max_length=255) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created'] def __str__(self): return self.pertanyaan class Jawaban(models.Model): pertanyaan = models.ForeignKey(Pertanyaan, related_name='jawabans', on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) jawab = models.PositiveIntegerField() urls.py inside survey app from django.urls import path, include from . import views from django.contrib.auth import views as auth_views urlpatterns = [ path('kuisioner/', views.get_pertanyaans, name='get_pertanyaans') ] urls.py in my project urlpatterns = [ path('admin/', admin.site.urls), path('account/', include('account.urls')), path('survey/', include('survey.urls')), ] forms.py from django … -
many attributes in manyTomanyField does not have a attribute called .all() |Help needed Beginner|
I have created a model named Flight which is connected to another model named Passengers flights = models.ManyToManyField(Flight, blank=True, related_name="passengers") i tried to use Passengers = Flight.Passengers.all() it throws an error saying that Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'ManyToManyDescriptor' object has no attribute 'all' need help with it! i want only the realted fields from flight and passengers into my html but it throw an error whenever i try to access using Flight.Passengers.all() and Flight.Passengers.get() it can be bypass using Passengers.objects.all() but i don't need that otherwise there will be no relation between my databases! -
Django SessionWizardView weird behaviour
I'm trying to build a SessionWizardView used to create an instance of my model Servizio, with 3 different steps/ModelForms. class ServizioWizard(SessionWizardView): template_name = 'core/wizard_form.html' file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'wizard_storage')) form_list = [ServizioModelForm1, ServizioModelForm2, ServizioModelForm3] def get(self, *args, **kwargs): print(f"{self.get_form().fields=}") return super().get(*args, **kwargs) def post(self, *args, **kwargs): print("step before super().post():", self.steps.current) print("POST data:", self.request.POST) response = super().post(*args, **kwargs) print("step after super().post():", self.steps.current) return response def render_revalidation_failure(self, step, form, **kwargs): print(f"{form.errors=}") print(f"{step=}") return super().render_revalidation_failure(step, form, **kwargs) def done(self, form_list, **kwargs): print("done?") print(f"{self.request.POST=}") s = process_widard_forms_data(form_list) s.hub = self.request.user.referente.hub s.save() return redirect('core:home') def get_context_data(self, form, **kwargs): ctx = super(ServizioWizard, self).get_context_data(form=form, **kwargs) print(f"{self.request.session.keys()=}") print(f"{self.request.session['wizard_servizio_wizard']=}") r = self.request.user.referente ctx['referente'] = r ctx['hub'] = r.hub return ctx The issue I'm meeting is that whenever I load the first of those steps, I get the following output in my console: self.get_form().fields={'nome': <django.forms.fields.CharField object at 0x706f84fe6800>, 'tipo': <django.forms.fields.TypedChoiceField object at 0x706f84fe6650>, 'categoria': <django.forms.models.ModelChoiceField object at 0x706f84fe6a40>, 'descrizione': <django.forms.fields.CharField object at 0x706f850289a0>, 'informazioni': <django.forms.fields.CharField object at 0x706f85028b20>} self.request.session.keys()=dict_keys(['_auth_user_id', '_auth_user_backend', '_auth_user_hash', 'wizard_servizio_wizard']) self.request.session['wizard_servizio_wizard']={'step': '0', 'step_data': {}, 'step_files': {}, 'extra_data': {}} [09/Feb/2024 11:16:05] "GET /crea-servizio/ HTTP/1.1" 200 131264 self.get_form().fields={'nome': <django.forms.fields.CharField object at 0x706f850295a0>, 'tipo': <django.forms.fields.TypedChoiceField object at 0x706f85029120>, 'categoria': <django.forms.models.ModelChoiceField object at 0x706f85028ca0>, 'descrizione': <django.forms.fields.CharField object at 0x706f850293c0>, 'informazioni': <django.forms.fields.CharField object at … -
I am using Django Admin action but I want to use it in modal form
I am new to django and I am using Django admin actions which gives us action admin action dropdown. I am using django-admin-actions 0.1.1 I created view # views.py from django.http import HttpResponse from django.template.loader import render_to_string from weasyprint import HTML, CSS from .models import StudentEnrollment # Django actions def generate_enrollment_form_pdf(request): # Query Student Enrollment data enrollments = StudentEnrollment.objects.all() # Render HTML template with data html_string = render_to_string('enrollment_form.html', {'enrollments': enrollments}) # Create PDF from HTML with A5 size pdf_file = HTML(string=html_string).write_pdf(stylesheets=[CSS(string='@page { size: A6; }')]) # Return PDF response response = HttpResponse(pdf_file, content_type='application/pdf') response['Content-Disposition'] = 'filename="enrollment_form.pdf"' return response # Django actions over and setup urls.py # urls.py from django.urls import path from .views import * urlpatterns = [ path('generate-enrollment-pdf/', generate_enrollment_form_pdf, name='generate_enrollment_pdf'), ] In admin.py I create a function for my plan execution xD # Function for Prep Enrollment Print def print_enrollment_form_pdf(modeladmin, request, queryset): # Query Student Enrollment data enrollments = queryset # Render HTML template with data html_string = render_to_string('enrollment_form.html', {'enrollments': enrollments}) # Create PDF from HTML pdf_file = HTML(string=html_string).write_pdf() # Return PDF response response = HttpResponse(pdf_file, content_type='application/pdf') response['Content-Disposition'] = 'filename="enrollment_form.pdf"' return response print_enrollment_form_pdf.short_description = "Print Enrollment Form PDF" and then i call that action in my modalAdmin @admin.register(StudentEnrollment) class … -
Django THOUSAND_SEPARATOR issue
I want to display my numbers in the template (Frontend) in the following format: 1.000.000 # for one million 0,5 # for 1/2 This is my current setting: LANGUAGE_CODE = "es-cl" USE_I18N = True USE_L10N = True NUMBER_GROUPING = 3 USE_THOUSAND_SEPARATOR = True THOUSAND_SEPARATOR = "." DECIMAL_SEPARATOR = "," The thousands separator is not used.. Why? My browser language is Spanish and I am currently in Germany. Maybe that has an effect? but the LANGUAGE_CODE should have precedence or not? But currently this is the output: 1 000 000 # for one million 0,5 # for 1/2 I am using django 4.2.9 with python 3.8 -
django migrate with clickhouse
I have a project with two databases: PostgreSQL and Clickhouse. To interact with Clickhouse, I use the django-clickhouse-backend lib. For a long time, I did not use the created migrations for this database, but created tables using raw SQL. Now it's time to apply all the previous migrations, but I ran into a problem. To avoid all conflicts, I had to significantly edit the existing migration files, after that I locally modeled and checked the application of these migrations in the existing database and everything was OK. But when I tried to apply these migrations on the production server, I got the following error: # python manage.py migrate --database clickhouse --fake-initial Operations to perform: Apply all migrations: admin, auth, authtoken, celery_app, contenttypes, django_dramatiq, edl, sessions, users Running migrations: Applying contenttypes.0001_initial...Traceback (most recent call last): File "/usr/local/lib/python3.11/site-packages/clickhouse_driver/dbapi/cursor.py", line 111, in execute response = execute( ^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/clickhouse_backend/driver/client.py", line 53, in execute rv = self.process_ordinary_query( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/clickhouse_driver/client.py", line 571, in process_ordinary_query return self.receive_result(with_column_types=with_column_types, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/clickhouse_driver/client.py", line 204, in receive_result return result.get_result() ^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/clickhouse_driver/result.py", line 50, in get_result for packet in self.packet_generator: File "/usr/local/lib/python3.11/site-packages/clickhouse_driver/client.py", line 220, in packet_generator packet = self.receive_packet() ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/clickhouse_driver/client.py", line 237, in receive_packet raise packet.exception … -
Upload issue in Django
Please can someone help with an issue i'm having in Django? I've created a recipe app for a course project and want the user to upload images. I've set the model up and when I upload an image from the django admin page it works perfectly, however when I try and upload an image from the user interface, it doesn't work and it should be using the same model. The other CharField, TextField and IntergerField all work but not the ImageField and I don't know why. There is also a default no_picture.jpg however it doesn't use that either. when the Img works the url shows as and when it doesn't the /recipes/ is missing from the URL However I don't think there is an issue with my urlpatterns as the other data works its just the image. Here is the models.py class Recipe(models.Model): name = models.CharField(max_length = 120) cooking_time = models.IntegerField(help_text = 'in mintues', default = 0 ) ingredients = models.CharField(max_length = 300) description = models.TextField() pictures = models.ImageField(upload_to = 'recipes', default = 'no_picture.jpg') forms.py class CreateRecipeForm(forms.Form): name = forms.CharField(max_length=50, required=False) cooking_time = forms.IntegerField(help_text='in minutes', required=False) ingredients = forms.CharField(max_length=300, required=False) description = forms.CharField(max_length=500, required=False) pictures = forms.ImageField(required=False) views.py @login_required def … -
ValueError at (url) seek of closed file in Django app
I am trying to add an image processing library inside a webodm django app that takes input image path, output directory path. I do not want to save the input image inside the database so I was implementing the image processing on the fly. I end up getting: ValueError at /plugins/diagnostic/ seek of closed file here is part of my view that handles the image processing: def vegetative_indices_view(request): print(cv2.__version__) if request.method == 'POST': form = VegetativeIndicesForm(request.POST, request.FILES) if form.is_valid(): uploaded_image = form.cleaned_data['input_image'] # Read the uploaded image into memory uploaded_image.seek(0) image_data = uploaded_image.read() uploaded_image.close() # Create an in-memory file-like object for the image in_memory_file = BytesIO(image_data) in_memory_file.name = uploaded_image.name # Normalize the uploaded image normalized_image = normalize(Image.open(in_memory_file)) # Call the vegetative indices calculation logic indexes = calculate_vegetative_indices(normalized_image) return render(request, self.template_path('vegetative_indices_results.html'), {'indexes': indexes}) else: form = VegetativeIndicesForm() return render(request, self.template_path("vegetative_indices.html"), {'form': form}) and in the terminal the error is printed like so: webapp | return func(*args, **kwargs) webapp | ValueError: seek of closed file What could be the issue here where the image file is prematurely closed? -
Can not access the values of dictionary using jinja
Here is my views.py def following(request): currentUser = User.objects.get(pk=request.user.id) currentUser_followings = Following_System.objects.get(user=currentUser).following allPosts = Post.objects.all().order_by("-timestamp").reverse() followingPosts = [] for user in currentUser_followings.all(): for post in allPosts: if post.author == user: followingPosts.append(post) **post_likers_ids = {post.id: list(post.likers.values_list('id', flat=True)) for post in followingPosts}** # Show 10 posts per page. paginator = Paginator(followingPosts, 5) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, "network/following.html",{ "page_obj": page_obj, "post_likers_ids" : post_likers_ids }) I debug, and the post_likers_ids return: ({4: [2], 2: [1,3,5]}) And now in my following html why the if condition is always false (Although it should be true for some, cause I know the expected input output): {% for post in page_obj %} <div class="list-group-item"> {% with post_id=post.id %} {% if user.id in post_likers_ids.post_id %} <p>The user liked this </p> {% else %} <p>The user have not liked this </p> {% endif %} {% endwith %} </div> {% endfor %} Here is my model if that helps: class Post(models.Model): content = models.TextField(blank=False) author = models.ForeignKey("User", on_delete=models.CASCADE, related_name="author") timestamp = models.DateTimeField(auto_now_add=True) likers = models.ManyToManyField("User", related_name="liked_posts", blank=True) def serialize(self): likes_count = self.likers.count() # likers = [user.id for user in self.likers.all()] return { "id": self.id, "content": self.content, "author": self.author.username, "author_id": self.author.id, "timestamp": self.timestamp.strftime("%b %d %Y, %I:%M %p"), "likes": …