Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error Django - SQL Server near "EXEC": syntax error
I have a problem calling Stored Procedured in Django, can you please help, below is the error: My funtion view def homeKTA(request): cursor = connection.cursor() try: cursor.execute("EXEC dbo.processos") result = cursor.fetchall() finally: cursor.close() return render(request, "homeRCKTA.html", result) yes that's exactly what is expected -
Revoke/replace Celery tasks under certain conditions
Let's say I've got a class Foo and a function which can be called like that: calculate(foo, dt) (the first argument is an instance of Foo, the second a datetime.datetime instance). Also, calculate updates various things related to foo in a database, calculate is decorated with @transaction.atomic to avoid reaching an inconsistent state in case of issue, behind calculate lies a recurrence relation, running it is computationally expensive, this is one of the reasons why it's called through a Celery task, when dateX > dateY, running calculate(foo, dateX) is pointless if you know you'll have to run calculate(foo, dateY) anyway, because the set of values updated by calculate(foo, dateX) is included in the set of values updated by calculate(foo, dateY). Now, how to run calculate as often as necessary without unnecessary calculations? In other terms, I think I'm looking for a function schedule_calc, taking 2 arguments foo and dt (like calculate), also matching the following requirements: when there isn't any task related to foo, a new one is created which will eventually run calculate(foo, dt), when there is such a task which will eventually run calculate(foo, date1), let's call it T1, several possible outcomes: if date1 <= dt and T1 … -
How to upload mutiple images in the django admin
It involves uploading multiple images to the django admin and the only one should show in the listings.html , and then in that instance post the other images should display there . I have done majority of the work to ensure the post is saved. Please bear in mind that i use an html page (pro.html) where i have the form my users will input whatever they want to post . Once the post in submited , it is automatically saved in the django admin . Amongst the form i require 8 images . The thing now is, if i upload 8 images it is going to save 8 times instead of once. This is my views.py from django.conf import settings from django.conf.urls.static import static from .forms import PostForm from django.shortcuts import render, get_object_or_404 from .models import Post, PostImage from django.http import HttpResponse # Create your views here. def post_create(request): form = PostForm() if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): form.save() for file in request.FILES.getlist('image'): image = Image(image=file) image.save() else: form = PostForm() return render(request, 'estateapp/pro.html', {'form': form}) def home(request): return render(request, 'estateapp/home.html') def Listings(request): posts = [] for post in Post.objects.all(): post = { 'title': post.title, … -
Django Management Command Triggers URLs When Checking Database Connection
I've encountered an unexpected behavior while working on a Django project involving a custom management command. The command I've created, named wait_for_db, is intended to test whether the database connection is ready before proceeding with other tasks. However, when I trigger this command using python manage.py wait_for_db, it seems to be invoking some URLs, leading to database-related errors. I've structured the management command to primarily check the database connection's readiness without interacting with URLs or the web server. The goal is to ensure that the database is available before proceeding with other operations. Here's a simplified version of my management command: """ Django command to wait for the database to be available. """ import time from psycopg2 import OperationalError as Psycopg2OpError from django.db.utils import OperationalError from django.core.management.base import BaseCommand class Command(BaseCommand): """Django command to wait for database.""" def handle(self, *args, **options): """Entrypoint for command.""" self.stdout.write('Waiting for database...') db_up = False while db_up is False: try: self.check(databases=['default']) db_up = True except (Psycopg2OpError, OperationalError): self.stdout.write('Database unavailable, waiting 1 second...') time.sleep(1) self.stdout.write(self.style.SUCCESS('Database available!')) Despite my best efforts, when I execute python manage.py wait_for_db, it seems to trigger some URLs or components that access the database. As a result, I receive errors indicating that … -
Django static and media files in production
I've deployed my first django ( learning ) project to a hosting server. I turned "DEBUG" off and run "collectstatic" so I have "static" and "media" folders in my main directory ( besides "manage.py" and ... ). But static and media files are not accessible unless I move the their folders to "public-html" directory every time. How can I change my root directory from "public-html" to "social" (main django folder). And does this fix the problem? Note: In my cpanel there is no apache configs available in etc folder. I asked the hosting provider to change the root directory for me but they said it can be done by me through some .htaccess configs. I added this to .htaccess file: RewriteEngine On RewriteCond %{HTTP_HOST} ^sadeqmousawi.ir [NC] RewriteRule ^(.*)$ /social/$1 [L] But it didn't work. -
Edit Django Admin JS Sheet Element
I am using this js form to select users: <style> .selector { float: none; display: block; height: 330px; } .selector-available, .selector-chosen { float: left; width: 380px; height: 330px; text-align: center; margin-bottom: 8px; } .selector ul.selector-chooser { float: left; width: 22px; height: 330px; background-color: var(--selected-bg); border-radius: 10px; margin: 10em 5px 0 5px; padding: 0; } .selector input[type="submit"] { display: block; clear: both; } .selector h2 { font-size: 15px; } textarea { display: block; width: 450px; } </style> Which results in a page rendering: I am trying to put the remove all button as well as the directional arrows between the Available users and Selected Users boxes so everything is even but, I am not sure how to do so. Could someone point me in the right direction? -
Prevent LDAP users from being automatically created in the Django admin site
I setup an LDAP authentication to login to a Django admin site from an active directory(AD) After logging in, the user are populated in the Users of Django admin site. Is there a way to prevent that the users are populated in the Django admin site? I though that AUTH_LDAP_USER_ATTR_MAP is what populates the user but I removed it and the users are still populated after logging in. Here is the settings.py import ldap from django_auth_ldap.config import LDAPSearch, GroupOfNamesTypes, LDAPGroupQuery AUTHENTICATION_BACKENDS = [ 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend' ] AUTH_LDAP_SERVER_URI = "ldap://server.name" AUTH_LDAP_BIND_AS_AUTHENTICATING_USER = True AUTH_LDAP_BIND_DN = "cn=user,ou=group,dc=example,dc=example" AUTH_LDAP_BIND_PASSWORD = "password" AUTH_LDAP_GLOBAL_OPTIONS = { ldap.OPT_REFERRALS : False } AUTH_LDAP_USER_SEARCH = LDAPSearch( "dc=example,dc=com", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)" ) AUTH_LDAP_ALWAYS_UPDATE_USER = True AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr="cn") AUTH_LDAP_MIRROR_GROUPS = True AUTH_LDAP_GROUP_SEARCH = LDAPSearch( "ou=group,dc=example,dc=com", ldap.SCOPE_SUBTREE, "(objectClass=group)" IS_STAFF_FLAG = ( LDAPGroupQuery("cn=group,ou=group,dc=example,dc=com") | LDAPGroupQuery("cn=group,ou=group,dc=example,dc=com") ) AUTH_LDAP_USER_FLAGS_BY_GROUP = { 'is_staff': IS_STAFF_FLAG, 'is_superuser': "cn=group,ou=group,dc=example,dc=example" } AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_TIMEOUT = 3600 -
Relation programmingError
I have model code for which migrations have successfully created and passed: from django.db import models from django.contrib.auth.models import AbstractUser class Employee(AbstractUser): probation = models.BooleanField(default=False) position = models.CharField(max_length=50, blank=True) groups = None user_permissions = None class Order(models.Model): name = models.CharField(max_length=100) description = models.TextField() employee = models.ForeignKey('employee', on_delete=models.CASCADE) def __str__(self): return self.name after which I registered them in the admin panel from django.contrib import admin from .models import Employee, Order @admin.register(Employee) class EmployeeAdmin(admin.ModelAdmin): list_display = ('username', 'first_name', 'last_name', 'email', 'probation', 'position') list_filter = ('probation', 'position') search_fields = ('username', 'first_name', 'last_name', 'email') @admin.register(Order) class OrderAdmin(admin.ModelAdmin): list_display = ('name', 'employee') list_filter = ('employee',) search_fields = ('name', 'employee__username', 'employee__first_name', 'employee__last_name') then when I try to add a new employee through the admin panel, I get an error relation "main_employee" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "main_employee" ^ Please tell me what is wrong with my code, I will be grateful -
Statistic on Django admin Index page
I know that Django admin main page is in index.html. I want to change this page, and add some statistic things, like last 5 errors from DB. My question is: that it is possible, create model for main admin page and show in there some information like I can when I will create some custom models and views? Do you have some example for that somewhere ? -
How to schedule a function in aiogram
I have Django+aiogram bot and that's how my mailing works: Manager/admin create a instance of the Post/Poll model in the admin panel -> Admin approve/disapprove it in telegram PM with inline keyboard -> if approves ("post" callback data) -> do_mailing function immediately works But I added the "scheduled_time = models.DateTimeField" field in my Post/Poll models and I want do_mailing function to work in that scheduled_time once, without repeats. Post model: class Post(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='Менеджер') text = models.TextField(verbose_name='Текст') scheduled_time = models.DateTimeField(blank=True, null=True, verbose_name="Дата и время рассылки") approved = models.BooleanField(default=False, verbose_name='Подтверждён') total_media_count = models.PositiveIntegerField(default=0, verbose_name='Сколько фотографий загрузите?') group = models.ForeignKey('bot_users.BotUserGroup', on_delete=models.SET_NULL, null=True, blank=True, verbose_name='Группа пользователей бота') created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True, verbose_name='Создано') There's a handler for "post" callback data which works after admin's approval: @dp.callback_query_handler(lambda query: query.data == 'post', state="*") async def post_handler(callback_query: CallbackQuery, state: FSMContext): admin = callback_query.message['chat']['id'] message = callback_query.message.text.split('\n') await change_post_status(message[0].split(': ')[1]) await do_mailing(message) logging.info(f"Пост {message[0].split(': ')[1]} был одобрен на рассылку админом") await bot.send_message(chat_id=admin, text=f"Рассылка поста {message[0].split(': ')[1]} одобрена!") await bot.send_message(chat_id=message[-1].split(': ')[1].split(' ')[0], text=f"Рассылка поста {message[0].split(': ')[1]} одобрена!") So do_mailing function is what I need to schedule. I can get "scheduled_time" field from the "message" variable, so don't think about it, let's just say … -
Understanding TemplateDoesNOtExist at home.html
I am working on django for beginners and the code provided does not work. I have copied and pasted after manually typing it in and the error persists around this class based view. It claims that home.html does not exist. The file certainly does. There is an odd home = value in the code that I do not understand why it is there as it is outside the norm. However I clearly see the hashtag # new which means to include the new code. I tried the extra removing home= and a red squiggly line immediately appeared as an error. The error message reads: Traceback (most recent call last): File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/core/handlers/base.py", line 220, in _get_response response = response.render() File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/template/response.py", line 114, in render self.content = self.rendered_content File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/template/response.py", line 90, in rendered_content template = self.resolve_template(self.template_name) File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/template/response.py", line 72, in resolve_template return select_template(template, using=self.using) File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/template/loader.py", line 47, in select_template raise TemplateDoesNotExist(", ".join(template_name_list), chain=chain) Exception Type: TemplateDoesNotExist at / Exception Value: home.html Another problem I am experiencing is that I went to a prior commit and github is saying hey, you need to do a pull request on the most … -
Change font color in Django ModelChoiceField widget after selection made
I have styled the font and font color for the select menu in my Django form using the widget. Is it possible to change the font color once a selection is made? For example, select menu text starts off white and after selection is made it turns green. I am using Crispy Form tags on the front end. class FootballLineup(forms.ModelForm): class Meta: model = FootballContestEntry fields = ['qb'] qb = forms.ModelChoiceField(label='', queryset=NFLPlayer.objects.filter(active=True, position='QB'), empty_label="Select Quarterback", required=True) qb.widget.attrs.update({'class': 'text-center lineup-select marker'}) -
Django logging issue on IIS
I'm new to Django and IIS server. I have a web server deployed with IIS, and I'm encountering an issue with the code. I'd like to try fixing it on my own, but I don't have a console (like in development mode) to show me what's going on. So, I started trying the logging functions in settings.py. Here's my configuration FORMATTERS = ({"verbose": {"format": "{levelname} {asctime:s} {name} {threadName} {thread:d} {module} {filename} {lineno:d} {name} {funcName} {process:d} {message}","style": "{",},"simple": {"format": "{levelname} {asctime:s} {name} {module} {filename} {lineno:d} {funcName} {message}","style": "{",},},) HANDLERS = {"console_handler": {"class": "logging.StreamHandler","formatter": "simple","level": "DEBUG"},"info_handler": {"class": "logging.handlers.RotatingFileHandler","filename": f"{BASE_DIR}/logs/blogthedata_info.log","mode": "a","encoding": "utf-8","formatter": "verbose","level": "INFO","backupCount": 5,"maxBytes": 1024 * 1024 * 5, # 5 MB},"error_handler": {"class": "logging.handlers.RotatingFileHandler","filename": f"{BASE_DIR}/logs/blogthedata_error.log","mode": "a","formatter": "verbose","level": "WARNING","backupCount": 5,"maxBytes": 1024 * 1024 * 5, # 5 MB},} LOGGERS = ({"django": {"handlers": ["console_handler", "info_handler"],"level": "INFO",},"django.request": {"handlers": ["error_handler"],"level": "INFO","propagate": True,},"django.template": {"handlers": ["error_handler"],"level": "DEBUG","propagate": True,},"django.server": {"handlers": ["error_handler"],"level": "INFO","propagate": True,},},) LOGGING = {"version": 1,"disable_existing_loggers": False,"formatters": FORMATTERS[0],"handlers": HANDLERS,"loggers": LOGGERS[0],}` taken from this explaination [https://www.youtube.com/watch?v=m_EkU56KdJg ](here): this code generates 4 files: blogthedata_detailed.log blogthedata_error.log blogthedata_info.log the detailed.log contains this:INFO 2023-08-25 11:53:47,710 Thread-1 (process_request_thread) 8792 basehttp basehttp.py 212 django.server log_message 12856 "GET /static/js/login_script.js HTTP/1.1" 200 751INFO 2023-08-25 11:53:47,780 Thread-2 (process_request_thread) 20080 basehttp basehttp.py 212 django.server log_message 12856 "GET /static/js/jQuery.js HTTP/1.1" … -
I get an error { "error": "Invalid email or password" }
I want to implement the ability to log in to my account, he says that I have the wrong email or password, but I checked the correct email and password through the administrative line. help me understand why the error comes out and how to fix it class LoginView(APIView): serializer_class = LoginSerializer # def get(self, request): # return render(request, 'login.html') def post(self, request): email = request.data.get('email') password = request.data.get('password') user = authenticate(request, email=email, password=password) if user is not None: login(request, user) token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key}, status=status.HTTP_200_OK) return Response({'error': 'Invalid email or password'}, status=status.HTTP_401_UNAUTHORIZED) class LoginSerializer(serializers.Serializer): email = serializers.CharField() password = serializers.CharField() def validate(self, data): user = authenticate( username=data['email'], password=data['password'] ) if not user: raise serializers.ValidationError('Неверные учетные данные') data['user'] = user return data class User(models.Model): email = models.EmailField(max_length=255, unique=True) password = models.CharField(max_length=128) -
Changing Year, Month, or Day in a Django model's date field using annotate
I have a Django model MyModel class MyModel(models.Model): """My Model that stores date.""" date = models.DateField() In my API I am receiving a param, review_month I need to get all the entries in MyModel and replace their date's year value. I have the following condition for what year to add: -> If date__month is greater than review_month the year will be current year otherwise the year will be previous year. I need these new date fields with updated years for every entry of the MyModel queryset MyModel.objects.annotate( updated_year=Case( When( Q(review_date__month__gt=review_month.month), then=previous_year), default=current_year, output_field=IntegerField(), ), ) ) This only give me year separately but I want an updated_date that has day and month of date field and this new updated year in it and must be a DateField as I need to apply sorting to it. -
user match query does not exist
I have been tasked to create separate user model for third_party users who are to access our endpoint so i created separate user named ApiCliet and inherited the Abstract user model of Django i also created a custom authentication for that user model only and then crated two mutation to create an api client and also generate and access_toekn for the existing user how ever i get user matching query does not exist which is baffling after debugging i get the username is correct and the password is correct below is my code . Model class ApiClientManager(BaseUserManager): def create_user(self, username, email=None, password=None, **extra_fields): if not username: raise ValueError("The Username field must be set") email = self.normalize_email(email) if email else None user = ApiClient(username=username, email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email=None, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(username, email, password, **extra_fields) class ApiClient(AbstractBaseUser, PermissionsMixin): id = models.AutoField(db_column="Api_client_ID", primary_key=True) uuid = models.CharField(db_column="Api_clientUUID", max_length=36, default=uuid.uuid4, unique=True) username = models.CharField(db_column="Api_client_username", max_length=100, unique=True, default='test_username') email = models.EmailField(db_column="Api_client_email", blank=True, null=True) access_token = models.CharField(db_column="Api_client_access_token", max_length=100, blank=True, null=True) date_created = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) … -
Compare Python Dictionary values with Django Database fields
I'm looking for a way to compare a python dictionary values with Django ORM entries. I have a dictionary contains product information like following: product_1 = { "ProductId": "552049", "BarCode": "552049", "Height": 200, "WholesalePrice": 10.65, "RetailPrice": 18.78, "Length": 62, "LongDescription": "Spray 400ml", "ShortDescription": "Spray 400ml", "Volume": 818, "Weight": 354, "Width": 66, } These values stored on a Django database. The number of products are very big, about 200.000 products and after a few days I need to compare and update the products if something change. I know that a way is to iterate to products and compare values but I'm looking for a better approach to compare products more faster. I'm thinking about to create a checksum and stored as a field in database and later when I update the products, first compare the checksum and if is different then update the database field. But I don't know if this the best way. Can someone suggest me a fast way for this? -
Django forms value getting the last id but wanted specfic id and first save is working the rest is not working
**I have a Django code where i am retrieving the tin number and tin type ** ``if ("_generate_form_1099" in self.request.POST) and self.request.POST["_generate_form_1099"] == "Generate Form 1099": elif ("_send-bulk-email" in self.request.POST) and self.request.POST["self-bulk-email"] == "Send Bulk Email": elif ("action" in self.request.POST) and self.request.POST["action"] == "Save Tin": user_id = self.request.POST.get('user_id') tin = self.request.POST.get('tin_value') tin_type = self.request.POST.get('tin_type') input_name = f"tin_value{{ user.id }}" if input_name in self.request.POST: tin_value = self.request.POST[input_name] user = CustomUser.objects.get(id=user_id) user.seller_tin = tin user.tin_type = tin_type user.save() context = {'user_contexts': user_contexts} return render(self.request, 'admin/generate_form.html', context) elif ("_send-tin-email" in self.request.POST) and self.request.POST["_send-tin-email"] == "Send Email": user_id = self.request.POST.get('user_id') user_name = self.request.POST.get('user_name') email_mess = {"seller": user_name} send_notification([user_id], 'notification_31', email_mess) ` `{% extends "admin/base_site.html" %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <div> <input type="submit" class="action-button" value="Generate Form 1099" name="_generate_form_1099"> </div><br> {% if download_link %} <a href="{{ download_link }}" target="_blank" class="download-button"> <div style="display:inline-block">Download</div> </a> {% elif download_link %} <div><p>The Form 1099 has not been generated for the specified fiscal year. Click on Generate Form 1099</p></div> {% endif %} {{ block.super }} </form> <div> <h2>Seller Information Without Tin</h2> <table> <tr> <th class="header-table">USER ID</th> <th class="header-table">Name</th> <th class="header-table">Email</th> <th class="header-table">TIN Details</th> <th class="header-table">Actions</th> </tr> {% for user in user_contexts %} … -
dj-rest-auth patch and put not working in custom user model
I am developing an API for a mobile app and using dj-rest-auth to handle authentication logic. I have created a custom user model and a custom user serializer. Registration, login, and retrieving user details are functioning correctly. However, I'm encountering an issue with PUT and PATCH requests when attempting to update user information, I get error looks like this. UserSerializer.save() missing 1 required positional argument: 'request' Request Method: PATCH Custom User Model Code from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyUserManager(BaseUserManager): def create_user(self, email, password=None): user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email, password): user = self.create_user( email=self.normalize_email(email), password=password, ) user.is_staff = True user.is_admin = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser): username= None is_superuser = models.BooleanField(default=False) email= models.EmailField(max_length=255, unique=True, primary_key=True) name = models.CharField(max_length=255) date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) phone = models.CharField(max_length=20, unique=True) with_facebook = models.BooleanField(default=False, blank=True) with_google = models.BooleanField(default=False, blank=True) latitude = models.DecimalField(max_digits=11, decimal_places=8, blank=True, default=None, null=True) longitude = models.DecimalField(max_digits=11, decimal_places=8, blank=True, default=None, null=True) created_at = models.DateTimeField(auto_now_add=True) notification_token = models.CharField(max_length=255) isSoon = models.BooleanField(default=False) id_image = models.ImageField(upload_to='id_image/', blank=True, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = MyUserManager() def __str__(self): return … -
use of Django-gTTS to say multiple text in one audio
I am building a simple quiz app and I am using Django-gTTS to read out some text on my webpage but the problem that I am having is I cannot join regular text and text from my views in one audio tag. For example, I want my code to be something like this: <audio src="{% say 'en-us' 'Course name' test.course_name 'Total Marks' total_marks %}" controls ></audio> although this exact code will give an error. Is there any way I can implement this? -
Django properly add foreign key from newly created model
I am trying to create a foreign key in my Project Model. The foreign key is from a newly created model. class Status: name = models.CharField(max_length=100) def __str__(self): return self.name class Project(models.Model): projectID = models.IntegerField(primary_key=True) name = models.CharField(max_length=50) projectBrief = models.TextField(default="") status = models.ForeignKey(Status, blank=True, null=True, on_delete=models.SET_NULL) Getting the following error line 939, in __init__ raise TypeError( TypeError: ForeignKey(<class 'projects.models.Status'>) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self' PS: I have been working on JSP from a long (I know pretty bad, where I can just add remove db fields without issue). Recently started learning Django. So please guide accordingly. Thanks. I am using the following commands python manage.py makemigrations python manage.py migrate I am not able to successfully migrate. -
How to remove newline created by { % if %} in django
I am generating email using email template in django. email_template.txt Some random string Some other string ----------------------------------------- {% if 'firstname' in data %}firstname: {{data['firstname']}}{% endif %} {% if 'lastname' in data %}lastname: {{data['lastname']}}{% endif %} {% if 'dob' in data %}dob: {{data['dob']}}{% endif %} {% if 'route' in data %}route: {{data['route']}}{% endif %} {% if 'mobile' in data%}mobile: {{data['mobile']}}{% endif %} {% if 'mail' in data%}mail: {{data['mail']}}{% endif %} I can not use spaceless because it will also remove spaces which i want to keep. In some cases if condition in template is not true then it gives new line. How can I stop the extra new line if condition is not true. -
Why does a button show in virtual environment but not in Django project in VS Code?
I am searching for a button name in VS Code in a Django Project. But the button is not showing in the Django project. Instead it is showing in it's virtual environment. and if i change something like that button's name in the virtual environment then it works fine. I want the button to be found in the Django project and not in it's virtual environment. Kindly help please. -
Print as pdf using python django
Check Image First I need assist in creating the code to create each record from the list to print as pdf using Django or JavaScript as seen from the picture the edit code is properly working but got stuck on pdf feature. assist only with pure django, pure javascript or any other library from both. -
Does csrf protection is required in django api?
Im currently making an app with flutter, and to communicate with mysql server using django for restAPI. Also Im using session for protection. In this case d I also need to use CSRF protection? If I plan to build an website with flutter in the future, does CSRF Protection is required?