Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-contact-form: using super().save(...) to save a an object field not working
I'm using django-contact-form package and it works well for what I need. But, with my use of super().save(fail_silently=fail_silently, *args, **kwargs), it does not appear to be saving the info from the form as a Contact object field. I had thought this was the way go about it but it doesn't appear to be working. I'd like to save the object in the form.save() method since we're directly using the package's ContactFormView defined in our urls.py path definition for /contact and don't require any customization there. My code: # model: class Contact(models.Model): name = models.CharField(max_length=100, default="") subject = models.CharField(max_length=255, default="") email = models.EmailField() body = models.TextField() def __str__(self): return self.subject[:100] class Meta: ordering = ("-created",) # form: class CustomContactForm(ContactForm): template_name = "core/django_contact_form/contact_form.txt" subject_template_name = "core/django_contact_form/contact_form_subject.txt" name = forms.CharField(label="Full Name") subject = forms.CharField(max_length=255, label="Subject") email = forms.EmailField(label="Email") recipient_list = ['admin@localhost',] class Meta: model = Contact fields = ["name", "subject", "email", "body"] def save(self, fail_silently=False, *args, **kwargs): try: super().save(fail_silently=fail_silently, *args, **kwargs) except Exception as e: print(f"Error saving Contact object: {str(e)}") send_mail(fail_silently=fail_silently, **self.get_message_dict()) There are no exception errors shown, so it looks like I am missing something that would get this to work as intended. What … -
In Django, how do I obtain a queryset of fields in a relate table, and return it along with context data from a class based view?
I have the following model layout class Group(models.Model): group_name = models.CharField(max_length=100, default="New Group") group_created_date = models.DateField(default=date.today) class GroupMember(models.Model): groups_joined = models.ManyToManyField(Group) email = models.EmailField(max_length=100) name = models.CharField(max_length=100) I'm trying, in a class based view, to return a queryset of all group members for a given group. I want to return this queryset, along with context data via a class based view. My attempt so far: class viewgroup(LoginRequiredMixin, SingleTableView): def get_queryset(self): groupid = self.kwargs['groupid'] qs = Group.objects.filter(groupmember__groups_joined__id=groupid).order_by('-id') return qs def get_context_data(self, **kwargs): groupid = self.kwargs['groupid'] group = Group.objects.get(id=groupid) context = { 'group': group, } return context def get_template_names(self): return ['myapp/viewgroup.html'] def get_table_class(self): return GroupTable If I have def_context_data there, I get an error in my template (which mainly just calls render table from django-tables2) that a queryset, not a string was expected. Somehow, the context data gets passed to render_table instead of the queryset. Without trying to pass context data, I get an error because of my query: Related Field got invalid lookup: groups_joined What is the correct way to construct a query to retrieve rows via a relationship, and to pass it as a queryset along with context data from a class based view? -
Django doesn't recognize the Pillow library
The installation was done correctly and appears in (venv). requirements: asgiref==3.7.2 Django==4.2.8 fontawesomefree==6.5.1 pillow==10.2.0 psycopg2==2.9.9 psycopg2-binary==2.9.9 sqlparse==0.4.4 typing_extensions==4.8.0 tzdata==2023.3 (venv) PS C:\Users\adminufpi\PycharmProjects\setorT> python -m pip show Pillow Name: pillow Version: 10.2.0 Summary: Python Imaging Library (Fork) Home-page: Author: Author-email: "Jeffrey A. Clark (Alex)" mailto:aclark@aclark.net License: HPND Location: c:\users\adminufpi\pycharmprojects\setort\venv\lib\site-packages Requires: Required-by: model: class Manutencao(models.Model): id = models.BigAutoField(primary_key=True) veiculo = models.ForeignKey(Veiculo, on_delete=models.CASCADE) data = models.DateField(null=False) descricao_manutencao = models.TextField(max_length=100, null=False) comprovante_manutencao = models.ImageField(upload_to='comprovantes/manutenções/', null=False) def __str__(self): return f"{self.veiculo} - Data: {self.data}" error: SystemCheckError: System check identified some issues: ERRORS: sistema_gerenciamento.Manutencao.comprovante_manutencao: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". Django doesn't find the pillow even though it was installed correctly, any tips on how I can solve this problem? -
msgpack.exceptions.ExtraData When Receiving Messages Deserialization Error in Django Channels on AWS:
I am developing a web application with Django and Django Channels, and I have encountered an issue while handling WebSocket consumer reception events. When receiving messages from the client, the application throws a deserialization error: msgpack.exceptions.ExtraData: unpack(b) received extra data. Context: Frameworks and Versions: I am using an environment deployed via AWS Beanstalk with Linux 2023, Django (version 4.2.6), Django Channels (version 4.0.0), Channels-redis (version 4.1.0). We have a load balancer to redirect traffic to a WSGI server (port 8000 where everything works as expected), and wss traffic to an ASGI server (Daphne) for asynchronous management. Security groups are configured correctly and allow traffic as expected. Elastic Redis cache service has been enabled and it works correctly (we persist and retrieve information without issues). Initially, for the CHANNEL_LAYERS backend, I had selected channels_redis.core.RedisChannelLayer, but the connection was not persistent (the client connected and disconnected within a second), which was resolved by selecting channels_redis.pubsub.RedisPubSubChannelLayer. Channels Backend: I have configured Django Channels to use Redis as the channels backend, CHANNEL_LAYERS in my settings.py I also include my current consumer code, asgi and complete traceback Expected Behavior: I expected the consumer to process incoming messages without issues, but there seems to be an … -
django get all values in many instances?
I have a problem. products = Producto.objects.all() data = products[per_page * page: per_page * (page + 1)] And I want to get all the data from the instance, con ForeignKey and "normal" values. Example: product = <Queryset[[prod_id: 1, name: "Ferrari 1"]. [prod_id: 12, name: "Playstation 5"] [prod_id: 5, name: "Soap"]]> and in the end, what I need is something like this to be parsed to JSON and send it: [[prod_id: "Car", name: "Ferrari 1"]. [prod_id: "Console", name: "Playstation 5"] [prod_id: "Clean Acc", name: "Soap"]] -
Error while using django_countries module
I have a model as below class Person1(models.Model): name = models.CharField(max_length = 20,null = True) country = CountryField() def __str__(self): return self.name while I'm trying to add value to the model fields it is showing the error AttributeError: 'BlankChoiceIterator' object has no attribute '__len__' Is there any issue with new version of django Here the problem is with the country field -
CSRF verification failed. Request aborted . im trying to send data from AJAX to views.py but it's showing this error
registration.html <form method="POST" id="someForm"> {% csrf_token %} <label for="name">Name:</label> <input type="text" id="name" name="name" required /> <label for="email">Email:</label> <input type="email" id="email" name="email" required /> <label for="password">Password:</label> <input type="password" id="password" name="password" required /> <input type="submit" value="Register" name="createuser" /> </form> </div> </div> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <script> let URLd = "{% url 'defaultpg' %}"; let nameInput = document.getElementById("name"); let emailInput = document.getElementById("email"); let passwordInput = document.getElementById("password"); const someForm = document.getElementById("someForm"); someForm.addEventListener("submit", (e) => { e.preventDefault(); // prevent default behavior of the form var csrfToken = $("input[name='csrfmiddlewaretoken']").val(); let nameValue = nameInput.value; let emailValue = emailInput.value; let passwordValue = passwordInput.value; let isNameValid = /^[a-zA-Z]+$/.test(nameValue); let isEmailValid = /^\S+@\S+\.\S+$/.test(emailValue); let isPasswordValid = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/.test( passwordValue ); if (isNameValid && isEmailValid && isPasswordValid) { alert("Successful"); $.ajax({ type: "POST", url: /defaultpg/, headers: { "X-CSRFToken": csrfToken }, data: { name: nameValue, email: emailValue, password: passwordValue, csrfmiddlewaretoken: csrfToken, }, dataType: "json", success: function (data) { // Handle success response alert("Successful msg"); }, error: function () { // Handle error response alert("Failure"); }, }); } else { // Handle validation errors if (!isNameValid) { alert("Please enter a valid Name"); } else if (!isEmailValid) { alert("Please enter a valid Email Address"); } else { alert( "Password must contain letters, capital letter, small letter, special character, … -
Add users to group based on OAuth2 Role - Microsoft Azure AD - social-auth-app-django
I'm trying to use Django-Social-Auth to login to Django. I have the OAuth workflow working and I can login, but I am not part of any groups and have no permissions.. My Azure AD app has various roles configured that are mapped to AD groups.. How can I map the users role to a Django group and in turn give permissions? If I need to create a custom pipeline function, thats fine, but I cant find any reference to access the roles. Thanks. -
Is there a production ready code template to deploy a django app to aws?
I'm looking for a production-ready approach to deploy django apps to aws. The approach must be in a automated fashion and needs minimal changes when deploying for a new app. For example, let's say I have a todo list app. Now I want to deploy it to aws. I will need terraform to create the required infrastructures, and then some way to configure these infrastructure and deploy the django app there. What I want is next time when I have another app - say a blog app, I just need to change a couple of things and use the same approach I used last time to have it deployed. I have checked out a few tutorial online but none of them quite captured what I'm looking for. Using terraform for infrastructure provisioning is the norm, however for deploying django on AWS I see there are a couple of approaches. I'm not an expert in AWS so I just want something with minimal overhead and maximum reproducibility Please help me find such a template. This would help me tremendously in deploying django apps. -
Docker image not working after rebuild with same dependencies
Docker image not working after rebuild with same dependencies. probably related to xmlsec. Same versions for python, nginx, gunicorn, python3saml, xmlsec etc. rebuild and checked that all dependencies are the same. they are the same. Container is running in azure, but problem is reproduced locally. -
Site Can't be reached while creating server on Flask
The VSC terminal says that the server is running on 127.0.0.1:5000 But when I Go there.. It says site couldn't be reached.. Please solve this problem.. Same problem persists while creating a server from Django I asked chatgpt but couldn't find any good solutions . -
Django multiple annotation for one Case-When
I'm currently trying to annotate multiple value with the same When in a Case for a Django QuerySet. Currently I have something like this: my_qs.annotate( dynamic_status_deadfish=Case( when_inactive, when_only_recently_published, when_no_published_ad, when_not_enough_booking, when_low_booking_cnt, default=default, output_field=HStoreField(), ) ) with one of those when looking like this: when_inactive = When( is_active=False, then={"status": stats_cts.INACTIVE, "reason": None}, ) when_only_recently_published = When( Q(is_old_published_ad_exists=False) & Q(is_recently_published_ads_exists=True), then={ "status": stats_cts.PENDING, "reason": OwnerStatsStatusReason.RECENTLY_SUSPENDED, }, ) when_no_published_ad = When( Q(is_old_published_ad_exists=False) & Q(is_recently_published_ads_exists=False), then={ "status": stats_cts.PENDING, "reason": OwnerStatsStatusReason.NO_BOOKABLE_TO_MODERATE, }, ) As you can see my output is a dict, or more exactly an Hstore. Ideally, I'd like one distinct annotation for status and for reason so that I don't have to deal with serialization and have an easier access to the annotation than with this HSTore One way would be to duplicate the when for status and reason as the condition are the same, but I don't like it. Something like this: when_only_recently_published = When( Q(is_old_published_ad_exists=False) & Q(is_recently_published_ads_exists=True), then=Value(stats_cts.PENDING), ) when_only_recently_published_reason = When( Q(is_old_published_ad_exists=False) & Q(is_recently_published_ads_exists=True), then=Value(OwnerStatsStatusReason.RECENTLY_SUSPENDED), ) ... my_qs.annotate( dynamic_status_deadfish=Case( when_inactive, when_only_recently_published, when_no_published_ad, when_not_enough_booking, when_low_booking_cnt, default=default, ), dynamic_status_deadfish_reason=Case( when_inactive_reason, when_only_recently_published_reason, when_no_published_ad_reason, when_not_enough_booking_reason, when_low_booking_cnt_reason, default=default_reason, ) ) Any way to somehow set two annotations in a Case or something similar ? -
django search a value in multiple fields
There is a way to search a determinated value inside of N fields? (Without have to get all the db to filter it with for in) Something like this: db = id name age 1 Juan 10 2 Pedro 31 3 Laura 55 4 3_Manuel 11 search(3) => OUTPUT [[2 Pedro 31] , [4 3_Manuel 11]] search("au") => OUTPUT [[1 Juan 10]] -
How to manage azure blob storage with django in production?
I have a django app and I am using the library django-storages[azure]. When I run the django app local I can upload images via django admin to my storage container on azure. But I also have an web app with url: https://example.azurewebsites.net and I try to upload images from the mentioned url. But that doesn't work - the images are not uloaded to the storage container. So this are my azure settings in the settings.py file: DEFAULT_FILE_STORAGE = 'dierenwelzijn.custom_azure.AzureMediaStorage' STATICFILES_STORAGE = 'DierenWelzijn.custom_azure.AzureStaticStorage' STATIC_LOCATION = "static" MEDIA_LOCATION = "media" AZURE_ACCOUNT_NAME = "dier" AZURE_CUSTOM_DOMAIN = f'{AZURE_ACCOUNT_NAME}.blob.core.windows.net' STATIC_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{STATIC_LOCATION}/' MEDIA_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{MEDIA_LOCATION}/' Question: what I have to change so that I can upload images from the hostmachine with url: https://example.azurewebsites.net ? -
How to store the data of two different django models which share one to many relationship via a single HTML form?
I have a single HTML form to fill up the details of both patient and his/her doctor. I have created a One to many relationship between Doctor and Patient models using ForeignKey. The form(docpatient.html) goes like this: <form action="{% url 'requestlanding' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <h2> Patient Details </h2> <label for="patientName"> Patient's Name: </label> <input type="text" id="patientName" name="patientName" required> <label for="age"> Age: </label> <input type="number" id="age" name="age" required> <label for="gender"> Gender: </label> <select id="gender" name="gender" required> <option value="male"> Male </option> <option value="female"> Female </option> <option value="other"> Other </option> </select> <label for="contactNumber"> Contact Number: </label> <input type="tel" id="contactNumber" name="contactPatient" required> <label for="email"> Email: </label> <input type="email" id="email" name="emailPatient" required> <label for="media"> Upload patient's picture: </label> <input type="file" id="media" name="wrecommend" accept="image/*,video/*,pdf/*"> <h2> Doctor Details </h2> <label for="doctorName"> Doctor's Name: </label> <input type="text" id="doctorName" name="doctorName" required> <label for="specialization"> Specialization: </label> <input type="text" name="specialization" id="specialization" required> <label for="contactNumber"> Contact Number: </label> <input type="tel" id="contactNumber" name="contactDoctor" required> <p> (All the information must be correct and proper) </p> <button type="submit"> Submit </button> </form> I have created Patient and Doctor models as following: from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator class Doctor(models.Model): name = models.CharField(max_length=50, blank=False) phone = models.IntegerField( validators=[MinValueValidator(1000000000), MaxValueValidator(9999999999)], blank=False, ) … -
Are multiple Django indices necessary?
I've a Django model that, among other fields, has time, station and variable. Nearly always, queries will be done providing the three fields - occasionally and very rarely, I might want to query using only one of them. In this case, does it matter if the index is set to models.Index(fields=["station", "time", "variable"]) or models.Index(fields=["time", "station", "variable"]) or other permutation of the three? Would it be useful to add all possible permutation or is it irrelevant? If there any performance penalty or benefit in adding all permutations? Many thanks! -
How to show the results of a many-to-many relationship backward direction via Django admin?
I have two models defined, groups and group_members, with the latter defining a many-to-many relationship to the former: class Group(models.Model): group_name = models.CharField(max_length=100, default="New Group") group_created_date = models.DateField(default=date.today) class GroupMember(models.Model): groups_joined = models.ManyToManyField(Group) email = models.EmailField(max_length=100) name = models.CharField(max_length=100) And then for my admin.py I simply have: admin.site.register(Group) admin.site.register(GroupMember) This works rather well from one side, when viewing GroupMember objects I can see and edit all the groups they belong to. However when viewing Group objects, I can not see the relationship from that side - I cannot see any members who belong to that group. What would I need to add to my admin.py to make this happen? I've been searching on how to do this but the answers either seem to convoluted and/or out of date. -
how to fix the following error? Error connecting Django to MSSQL
File "C:\ProgramData\Anaconda3\envs\test\Lib\site-packages\django\db\backends\base\base.py", line 292, in _cursor self.ensure_connection() File "C:\ProgramData\Anaconda3\envs\test\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\ProgramData\Anaconda3\envs\test\Lib\site-packages\django\db\backends\base\base.py", line 274, in ensure_connection with self.wrap_database_errors: File "C:\ProgramData\Anaconda3\envs\test\Lib\site-packages\django\db\utils.py", line 91, in exit raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\ProgramData\Anaconda3\envs\Lib\site-packages\django\db\backends\base\base.py", line 275, in ensure_connection self.connect() File "C:\ProgramData\Anaconda3\envstest\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\ProgramData\Anaconda3\envs\test\Lib\site-packages\django\db\backends\base\base.py", line 256, in connect self.connection = self.get_new_connection(conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\ProgramData\Anaconda3\envs\test\Lib\site-packages\mssql\base.py", line 366, in get_new_connection conn = Database.connect(connstr, **args) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ django.db.utils.InterfaceError: ('28000', "[28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'user'. (18456) (SQLDriverConnect); [28000] [Microsoft][ODBC Driver 17 for SQL Server]Invalid connection string attribute (0); [28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'user'. (18456); [28000] [Microsoft][ODBC Driver 17 for SQL Server]Invalid connection string attribute (0)") DATABASES = { 'default': { 'ENGINE': 'mssql', 'NAME': 'Test', 'USER': 'user', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } mssql and pyodbc were installed -
Weird bug when looking at a user profile in django
So I have 2 user types: a company and a job seeker. The problem is when I go to the seeker's profile from a job application, or directly go to a seekers profile, it returns the data of the current logged in company. Like this: Here's the view for the JobApplication: class JobApplicationsView(CompanyRequiredMixin, LoginRequiredMixin, DetailView): model = Job template_name = "applications/job_applications.html" context_object_name = "job" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) job = self.get_object() # Get all job applications for the current job job_applications = JobApplication.objects.filter(job=job) context["job_applications"] = job_applications return context Here's the template job_applications.html {% extends "base.html" %} {% block content %} <div class="container mt-5"> <h1 class="mb-4">{{ job.title }} - Job Applications</h1> {% if job_applications %} <ul class="list-group"> {% for application in job_applications %} <li class="list-group-item"> <strong>Applicant:</strong> {{ application.applicant.username }}<br> <strong>Cover Letter:</strong> {{ application.cover_letter }}<br> {% if application.resume %} <a href="{{ application.resume.url }}" download class="btn btn-primary">Download Resume</a> {% else %} <span class="text-muted">No resume attached</span> {% endif %} </li> {% endfor %} </ul> {% else %} <p>No applications for this job yet.</p> {% endif %} </div> {% endblock %} To get it right, the localhost:8000/job-seeker/seeker1 should show the data of the job seeker. This happens to all profiles, when I use … -
Apple Store Server Notification: Python OpenSSL certificate loading fails in "header too long"
On my django server, I'm trying to decode the JWT content sent by the Apple Store Server Notification using Apple's package app-store-server-library-python. Under the official documentation, when starting to do the verification and decoding, we find this line: root_certificates = load_root_certificates() The implementation is not provided unfortunately. By looking here and there, I've tried several implementations that always fail in : OpenSSL.crypto.Error: [('asn1 encoding routines', '', 'header too long')] Here is my implementation: def load_root_certificates(): in_file = open("AppleRootCA-G3.cer", "rb") data = in_file.read() in_file.close() return load_certificate(FILETYPE_ASN1, data) Thanks for the help! -
Why do we return only a limited amount of information from a websocket event?
I'm working on implementing a real-time chat application that uses web sockets and a 3rd party application. This 3rd party application has various events that does not transmit the full message object, but rather a limited set of data. Wouldn't it be better to return the full message object, because it would greatly simplify the process of updating the client? What's happening right now is that I have to engage in complex search and update operations. I guess I am having trouble understanding this design choice because, at least in my eyes, returning the full message object shouldn't take up that much additional bandwidth. Here are some examples. API Responses Dialog (Represents chat between two people) [ { "id": 2, "created": 1704771541, "modified": 1704771541, "other_user_id": "1", "unread_count": 12, "username": "admin", "last_message": { "id": 36, "text": "f", "sent": 1704847056, "edited": 1704847056, "read": false, "sender": "1", "recipient": "2", "out": false, "sender_username": "admin" } } ] Message { "id": 36, "text": "f", "sent": 1704847056, "edited": 1704847056, "read": false, "sender": "1", "recipient": "2", "out": true, "sender_username": "admin" } Web Socket Events New Message {"msg_type": 3, "random_id": -999999, "text": "Hi …", "receiver": "2", "sender_username": "johntaylor"} Message Added {"msg_type": 8, "random_id": -999999, "db_id": 46} Unread count … -
Update OneToOneField Relationship in Django
I want to update to exera field of User models in Django programmatically in my program. how can i update the extra field of User model in Django? def user_profile(request): query_set = str(Group.objects.filter(user=request.user)[0]) if query_set == 'user': user = request.user name = user.first_name family = user.last_name extrainfo = ExtraInfo.objects.get(User=user) extrainfo.title = 'business' extrainfo.save() return render(request, 'user-profile.html', {'name': name, 'family': family, 'title': user.extrainfo.title}) else: messages.warning(request, 'Unauthorized Access!') return render(request, 'warnings.html') from django.db import models from django.contrib.auth.models import User class ExtraInfo(models.Model): User = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) title = models.CharField(max_length=25, blank=True) -
Integrate sslcommerz payment gateway in my Django project
I have alreadt integrated Paypal payment gateway in my django project fllowing this tutorial. Now, I want to integrate sslcommerz for users to give more option to pay. Here are some codes of my project. config/settings.py """ Django settings for config project. Generated by 'django-admin startproject' using Django 5.0. For more information on this file, see https://docs.djangoproject.com/en/5.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.0/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-f=f@1a*+svrxj#j8_4ik%c@gd16_s6@c$(n%4p$(66*6g7we6)' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'product', 'user_account', 'cart', 'order', ] MIDDLEWARE = [ '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', ] ROOT_URLCONF = 'config.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], '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', 'product.context_processors.categories', 'cart.context_processors.cart' ], }, }, ] WSGI_APPLICATION = 'config.wsgi.application' # Database # https://docs.djangoproject.com/en/5.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', … -
Wrong credentials cause sign in alert box
I have react frontend and django backend. I am seeing an alert box when I enter incorrect credentials on my login screen. On Google Chrome I see the network call in pending state When I click on 'Cancel' button on the dialog, I see 401 error (as expected since invalid credentials were entered). Am I missing anything? Why am I seeing this dialog? -
Creating a PDF with PDFkit and Wkhtmltopdf, but encountering an issue where the entire table is being pushed to the next page. How can I resolve this
I'm facing an issue while generating PDFs in Python Django using PdKit and Wkhtmltopdf. Specifically, when the table has more than 10 items, it gets pushed to the next page. I've attempted the following solutions: Added the following CSS styles: page-break-inside: avoid !important; } table { page-break-inside:auto } tr { page-break-inside:avoid !important; page-break-after:auto !important } thead { display:table-header-group !important} tfoot { display:table-footer-group !important} ``` 2. Tried using the JavaScript solution provided - https://github.com/AAverin/JSUtils/blob/master/wkhtmltopdfTableSplitHack/wkhtmltopdf_tableSplitHack.js [![Image 1 ][1]][1] [![Image 2][2]][2] [1]: https://i.stack.imgur.com/TO2Hb.png [2]: https://i.stack.imgur.com/Dt3Wl.png