Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
LOGIN FORM: I need Login for from the blow User Mode
user_type=[(1, "manager"), (2, "registeror"), (3, "Engineer"),] class Users(AbstractBaseUser): user_id=models.CharField(max_length=50,primary_key=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) user_name = models.EmailField(max_length=50,unique=1) pass_word= models.CharField(max_length=15) user_type = models.IntegerField(choices=user_type,default=3) is_active=models.BooleanField(auto_created=True,default=True) is_staff = models.BooleanField(default=False,null=True,auto_created=True,blank=True) is_superuser = models.BooleanField(default=False,auto_created=True,null=True,blank=True) USERNAME_FIELD = "user_name" def __str__(self) -> str: return f"{self.first_name.upper()} {self.last_name.upper()}" user_type=[(1, "manager"), (2, "registeror"), (3, "Engineer"),] class Users(AbstractBaseUser): user_id=models.CharField(max_length=50,primary_key=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) user_name = models.EmailField(max_length=50,unique=1) pass_word= models.CharField(max_length=15) user_type = models.IntegerField(choices=user_type,default=3) is_active=models.BooleanField(auto_created=True,default=True) is_staff = models.BooleanField(default=False,null=True,auto_created=True,blank=True) is_superuser = models.BooleanField(default=False,auto_created=True,null=True,blank=True) USERNAME_FIELD = "user_name" def __str__(self) -> str: return f"{self.first_name.upper()} {self.last_name.upper()}" LOGIN FORM: I need Login for from the blow User Mode Login Functionality Is not work .I need some guide to Implement Login and Authantication LOGIN FORM: I need Login for from the blow User Mode LOGIN FORM: I need Login for from the blow User Mode LOGIN FORM: I need Login for from the blow User Mode LOGIN FORM: I need Login for from the blow User Mode -
How to use celery with django duration field
I have model Banner with duration field. I wanna update value of status field of banner after end of duration. For example, I'm creating object with hour duration, and I need to create task which will change value of status field after hour. How can I do this celery? # models.py class AdvertisementModelMixin(models.Model): class Statuses(models.TextChoices): ACTIVE = "active", _("Active") HIDDEN = "hidden", _("Hidden") DELETED = "deleted", _("Deleted") TEST = "test", _("Test") link = models.URLField() view_count = models.PositiveIntegerField(default=0) age_from = models.PositiveSmallIntegerField( blank=True, null=True, validators=[MaxValueValidator(80)]) age_to = models.PositiveSmallIntegerField( blank=True, null=True, validators=[MaxValueValidator(80)]) devices = models.ManyToManyField(Device, verbose_name="platforms",) duration = models.DurationField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) status = models.CharField(max_length=30, choices=Statuses.choices, default=Statuses.ACTIVE) -
Life Cycle of Daemon thread and Non Daemon Thread in Django
I'm trying to execute a long-running process (sending mail to around 600 people) using threading module. My Django view and email processing function goes like this: def daily_wap(request): context = { } if request.method == 'POST': file = request.FILES.get('dailywap', None) if file: try: wap = pd.read_excel(file, header = [0,1], engine='openpyxl').dropna(how = 'all') t = threading.Thread(target= daily_wap_automailer, kwargs={'wap': wap}, daemon = True) t.start() messages.success(request , "Task Scheduled") return HttpResponseRedirect(reverse('usermanagement:daily_wap_automailer')) except Exception as e: messages.error(request, 'Error occured: {0}'.format(e)) return HttpResponseRedirect(reverse('usermanagement:daily_wap_automailer')) else: messages.error(request, 'File not provided') return HttpResponseRedirect(reverse('usermanagement:daily_wap_automailer')) return render(request, "wap_automailer.html", context) def daily_wap_automailer(wap): ### In send_mail, im iterating over each mail ids and sending the mail, ### which then returns total mail successfully sent(count) and total no users (total) count , total = send_mail(wap=wap) return (count , total) I'm executing the function daily_wap_automailer using the daemon thread. As per the online documenation and resources, daemon thread gets terminated as soon as the main/parent thread gets terminated provided it does not have any non-daemon thread to execute. The main thread (HTTP request response cycle) typically takes less than a sec to complete(sending the message "Task Scheduled" to Client), does it mean that the daemon thread which executes func daily_wap_automailer won't have sufficient time … -
How can I add a telegram bot in Django application
I have a Django application (store) and I want to receive notifications about new users who have registered in the store. I also want to receive messages via telegram bot if any user has logged in. I've never written telegram bots before. I will be glad of any information and support. The most important thing I want to know is how to connect bot and django. Does the bot need private server? Any links or tutorials will be helpful. -
I don't understand this TemplateDoesNotExist error
I am very new to Django. Currently following the book django for beginners (https://djangoforbeginners.com/) and all was fine and dandy until chapter 4. I get the following error: TemplateDoesNotExist at / home.html, posts/post_list.html I don't know where this comes from. Why is Django looking for the posts/post_list.html file? I am not referring to that file anywhere afaik. I get this error message: Request Method: GET Request URL: serverurl Django Version: 2.1 Exception Type: TemplateDoesNotExist Exception Value: home.html, posts/post_list.html Exception Location: /home/tang/.local/share/virtualenvs/message_board_django-jJcCRH2C/lib/python3.10/site-packages/django/template/loader.py in select_template, line 47 Python Executable: /home/tang/.local/share/virtualenvs/message_board_django-jJcCRH2C/bin/python3 Python Version: 3.10.12 Python Path: ['/home/tang/LinuxServ/message_board_django', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/home/tang/.local/share/virtualenvs/message_board_django-jJcCRH2C/lib/python3.10/site-packages'] Server time: Fri, 13 Oct 2023 10:31:52 +0000 Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /home/tang/LinuxServ/message_board_django/templates/home.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/tang/.local/share/virtualenvs/message_board_django-jJcCRH2C/lib/python3.10/site-packages/django/contrib/admin/templates/home.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/tang/.local/share/virtualenvs/message_board_django-jJcCRH2C/lib/python3.10/site-packages/django/contrib/auth/templates/home.html (Source does not exist) Using engine django: django.template.loaders.filesystem.Loader: /home/tang/LinuxServ/message_board_django/templates/posts/post_list.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/tang/.local/share/virtualenvs/message_board_django-jJcCRH2C/lib/python3.10/site-packages/django/contrib/admin/templates/posts/post_list.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/tang/.local/share/virtualenvs/message_board_django-jJcCRH2C/lib/python3.10/site-packages/django/contrib/auth/templates/posts/post_list.html (Source does not exist) Does it come from my file structure? #posts/view.py from django.views.generic import ListView from .models import Post class HomePageView(ListView): model = Post template_name = 'home.html' <!-- templates/home.html --> <h1>Message board homepage</h1> <ul> {% for post in object_list %} <li>{{ post }}</li> {% endfor %} </ul> … -
Django breaking css after using if statement
I'm trying to add a dropdown list into my navbar that i created using bootstrap but whenever i put the dropdown menu into the if statement to loop categories into a list, the css breaks. without if statement(only for loop) <nav class="navbar navbar-expand-lg navbar-dark nav-color fixed-top"> <a class="navbar-brand" href="{% url 'home' %}" ><b>Lorem Ipsum</b></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item dropdown"> <a class="nav-link active dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="true"> Categories </a> <ul class="dropdown-menu"> {% for item in cat_menu %} <li><a class="dropdown-item" href="{% url 'category' item|slugify %}">{{ item }}</a></li> {% endfor %} </ul> </li> {% if user.is_authenticated %} <li class="nav-item active"> <a href="{% url 'blogposts'%}" class="nav-link" id="hover-change">Blog Posts <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a href="{% url 'personalinfo'%}" class="nav-link">About Me <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="{% url 'create-post'%}">Create Post <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="{% url 'create-category'%}">Create Category <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="{% url 'logout'%}">Logout <span class="sr-only">(current)</span></a> </li> {% else %} <li class="nav-item active"> <a href="{% url 'blogposts'%}" class="nav-link" id="hover-change">Blog Posts <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a href="{% url 'personalinfo'%}" class="nav-link">About Me <span class="sr-only">(current)</span></a> </li> … -
How can i solve the error ("storages.backends.s3boto3" does not define a "S3StaticStorage")?
when i putted the configurations: # Amazon S3 Configuration AWS_ACCESS_KEY_ID = "*******************" # AWS_SECRET_ACCESS_KEY = "****************" # AWS_STORAGE_BUCKET_NAME = 'karafeta-bucket' # # Django > 4.2 STORAGES = {"staticfiles": {"BACKEND": "storages.backends.s3boto3.S3StaticStorage"}} # Django < 4.2 #STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_FILE_OVERWRITE = False in settings.py in my django project i got an error sayes : django.core.files.storage.handler.InvalidStorageError: Could not find backend 'storages.backends.s3boto3.S3StaticStorage': Module "storages.backends.s3boto3" does not define a "S3StaticStorage" attribute/class the whole error : python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). October 13, 2023 - 13:16:16 Django version 4.2.3, using settings 'karafeta.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Internal Server Error: / Traceback (most recent call last): File "C:\Python3-10-2\lib\site-packages\django\core\files\storage\handler.py", line 35, in __getitem__ return self._storages[alias] KeyError: 'staticfiles' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Python3-10-2\lib\site-packages\django\utils\module_loading.py", line 30, in import_string return cached_import(module_path, class_name) File "C:\Python3-10-2\lib\site-packages\django\utils\module_loading.py", line 15, in cached_import module = import_module(module_path) File "C:\Python3-10-2\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", … -
Handling "No color selected" and "No size selected" Messages in Django Form Submission
I'm working on a Django project where I have a form that allows users to select a color and size before adding a product to their cart. However, I'm encountering an issue when users submit the form without making selections. I receive the following messages: "No color selected" and "No size selected in terminal." look at add_to_cart function home.html <form method="POST" action="{% url 'add_to_cart' products.id %}"> <div> <select name="colors" class="border border-gray-200 focus:outline-none "> {% for color in Colors.all %} <option value="{{color.color}}">{{color.color|capfirst}}</option> {% endfor %} </select> <select name="sizes" class="border border-gray-200 focus:outline-none "> {% for size in Sizes.all %} <option value="{{ size.size }}">{{ size.size }}</option> {% endfor %} </select> </div> </form> views.py from django.shortcuts import render,redirect from .models import * def home(request): product = Product.objects.all() sizes = Sizes.objects.all() colors = Colors.objects.all() return render(request , 'home.html' , {'Product':product , 'Sizes':sizes , 'Colors':colors}) def add_to_cart(request, product_id): product = Product.objects.get(id=product_id) cart = request.session.get('cart', []) if request.method == 'POST': selected_color = request.POST.get('colors') selected_size = request.POST.get('sizes') cart_item = { 'product_id': product.id, 'color': selected_color, 'size': selected_size, } print(cart_item['product_id']) if selected_color is not None: print(cart_item['color']) else: print("No color selected") if selected_size is not None: print(cart_item['size']) else: print("No size selected") cart.append(product.id) request.session['cart'] = cart return redirect('home') def view_cart(request): # Retrieve … -
Connexion python pywin32 au Sage100c cloud Object Model
Qui peux m'aider car je ne sais plus : J'ai toujour cette erreur : Erreur de connexion au sage 100c: (-2147221008, 'CoInitialize n’a pas été appelé.', None, None) ``import logging import os import pythoncom import win32com from win32com.client import Dispatch from utils.logs import write_log Initialise COM au début du script pythoncom.CoInitialize() def connect_to_sage_100c(name_gcm, username_sage, password_sage, types): try: # Obtenir le chemin du fichier associé à l'objet FieldFile file_path = os.path.join('data', f'{name_gcm}') # Vérifier si le fichier existe if file_path == '': write_log("Le fichier Sage 100c n'existe pas.", logging.ERROR) print("Le fichier Sage 100c n'existe pas.") return conn = win32com.client.Dispatch("Objets100c.Cial.Stream") if types == 'gcm' else win32com.client.Dispatch( "Objets100c.Cpta.Stream") print('Conn ', conn) conn.Name = name_gcm conn.loggable.userName = username_sage conn.loggable.userPwd = password_sage conn.Open() if conn.IsOpen: write_log("Connexion à Sage 100c réussie.", logging.INFO) print("Connexion à Sage 100c réussie.") return conn else: write_log("Échec de la connexion à Sage 100c.", logging.ERROR) print("Échec de la connexion à Sage 100c.") return None except Exception as ex: write_log(f"Erreur de connexion au sage 100c: {str(ex)}") print(f"Erreur de connexion au sage 100c: {str(ex)}") return None finally: # Assurez-vous d'appeler CoUninitialize à la fin pythoncom.CoUninitialize() pass `` -
how to get output in python after click button in html
how to create a button and after clicking the button get the output show the same page input and output show same page and it's also getting some pop message show on title bar and some action on click on button. in html page divide two-part one part is button and second part is use for output and backend using django -
Cannot access admin if setting is set and cannot acces website if setting is not set
I have a Django website in production so DEBUG = False There is a setting: SESSION_COOKIE_SECURE = True If it is set to True then I can access the admin and log in, but then I cannot access the website itself and I get a bad gateway error. If the setting is missing or set to False then I can access the website fine but I cannot log into admin. A bit confusing Here are the settings related to domains and CSRF: ALLOWED_HOSTS = ["localhost","102.219.85.91","founderslooking.com","app.founderslooking.com"] CORS_ALLOWED_ORIGINS = [ "http://localhost", "http://127.0.0.1", "http://localhost:file", "http://app.founderslooking.com", ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True SESSION_COOKIE_SAMESITE = None SESSION_COOKIE_DOMAIN = "founderslooking.com" SESSION_COOKIE_SECURE = True CSRF_TRUSTED_ORIGINS = ["http://localhost", "http://*.127.0.0.1", "http://app.founderslooking.com",] INTERNAL_IPS = [ "127.0.0.1", ] First time I deploy a Django site so not sure what the settings should be for production. Thanks -
How to run python script running when django server starts
How to run python script running when django server starts. For example, I have a python kafka script , this script should be running continously when django server starts. when i give two commands in Dockerfile like CMD ["python", "manage.py","runserver","0.0.0.0:8443"] CMD [ "python", "./consumer.py"] only the latest cmd it is picking up. Any idea how to start python script and django server using single cmd. how to start python script and django server using single cmd. -
Confused about details of oauth2 authorization and authentication after reading Django-salesforce documentation
I am trying to integrate Salesforce with a Django application, so users can login into my site and push data themselves into the salesforce database. I have read the django-salesforce github page, and I confirmed that I can make postman calls to the database with oauth2 tokens, but I have some questions which probably stems from my ignorance of this subject. If I hardcode my username and password-concat-token into the django salesforce database settings, then won't all new database entries be authorized under my account? Ideally, shouldn't users authenticate into my application with their salesforce account, and then make API calls under the authorization of their own account? Or does this not matter at all? Also, if I hardcode my username and password-concat-token like above, then do I need a separate authentication and authorization system? If I hardcode my token into the django database information like that, then theoretically any backend call would inject my account's oauth2 information to make API calls. I was hoping users could click on a "Sign in with Salesforce" button and be authenticated on my site that way, going 100% for the social login system and not make my own. Any clarifications on my misunderstandings … -
Is there a way to pass django value to python script?
The python script that I have written fetches ticker data and historical data for the stock. Currently the stock value is hardcoded as you can see below. if __name__ == "__main__": stock = 'TSLA' data = GetData() data.tickerData(stock = stock) data.getHistData(stock = stock, startDate = startDate, endDate = endDate) I would like to know whether it's possible to send the user inputted value [via django forms] to this main function and have this script executed. If someone has come across this scenario, please advise. -
How to use TimeZone in Django
In my django project use: TIME_ZONE = 'Asia/Ho_Chi_Minh' USE_I18N = True USE_L10N = True USE_TZ = True But when I add this field: dateOrder = models.DateTimeField(auto_now_add=True) into my Order object, when initializing and printing it using def getDateOrder(self) method: weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] return weekdays[self.dateOrder.weekday()] + ', ' + self.dateOrder.strftime("%d/%m/%Y, %H:%M") is still UTC format Looking forward to receiving feedback from everyone -
Django not loading static from nginx in docker container
I django server cannot load static files, however they are accessible directly through a URL. I have a django server that is served by gunicorn inside a docker container. My Django static sttings.py: STATICFILES_DIRS = [ (os.path.join(BASE_DIR, "static")), ] STATIC_URL = "/static/" STATIC_ROOT = os.path.abspath(os.path.join(BASE_DIR, "../static")) My Nginx conf: http { sendfile on; server { listen 80; server_name localhost; location / { proxy_pass http://gunicorn:8000; } location /static/ { autoindex on; alias /static/; } } } My nginx docker-compose configuration: nginx: image: nginx:1.19.6-alpine depends_on: - gunicorn ports: - "80:80" expose: - "80" - "443" volumes: - ./nginx.conf:/etc/nginx/nginx.conf - ./certs:/etc/nginx/certs - nginx_static:/static When i start the django server with debug mode on, the files load at localhost:8000 where the gunicorn container is, but they are not avaliable at localhost:80 where my nginx container is. When I start it with debug off, static files arent loaded at all. When I try to access a static file through nginx, e.g. localhost:80/static/my_static.css the file loads I think this may be an issue with my django settings as calling the static in a html template like: {% static 'img/logo.png' %} will load that image, however none of my other css files will load even though {% … -
Django Form Field Filtering Issue: Unable to Filter Foreign Keys to Show Only User-Created Content
I'm having some issues working with filters on the forms of my Django project. This the the form that i am using, and the field "Company client" was sopposed to be showing only the companies that have been created by the user logged in, but once i filter using: self.fields['company_client'].queryset = ClientCompany.objects.filter(user=self.user) It does not show any company at all. And when i do not use the filter, it shows the companies that any user have created. forms.py class ClientContractForm(ModelForm): clausules = forms.CheckboxSelectMultiple() work_order = forms.CharField(required=True, label='Ordem de serviço', widget=forms.TextInput(attrs={'class': 'form-control'})) contract_name = forms.CharField(required=True, label='Nome do contrato', widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Insira o nome do seu contrato'})) address = forms.CharField(required=True, label='Endereço do contrato', widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Insira o endereço do contrato'})) installments = forms.CharField(required=True, label='Parcelas', widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Insira o número de parcelas do contrato'})) items = forms.CharField(required=True, label='Itens do contrato', widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Insira o número de parcelas do contrato'})) class Meta: model = ClientContract fields = ['work_order', 'contract_name', 'address', 'installments', 'items', 'clausules', 'company_client'] def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(ClientContractForm, self).__init__(*args, **kwargs) self.fields['clausules'].queryset = Clausule.objects.filter(user=self.user) self.fields['items'].queryset = Item.objects.filter(user=self.user) self.fields['work_order'].queryset = Contract.objects.filter(user=self.user) self.fields['company_client'].queryset = ClientCompany.objects.filter(user=self.user) models.py class ClientContract(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) work_order = … -
Trouble with Django View and URL Configuration for Google AdMob app-ads.txt
I'm currently facing an issue with configuring my Django application published in linode server using Nginx. My issue is in the app-ads.txt file for Google AdMob. I have set up a view in my views.py and added the corresponding URL pattern in urls.py as follows: views.py @require_GET def ads_txt(request): content = 'google.com, pub-*****************, DIRECT, ************' return HttpResponse(content, content_type="text/plain") urls.py from django.urls import path from .views import ads_txt urlpatterns = [ path('app-ads.txt', ads_txt), ] Problem: The view works when I access the URL without a trailing slash (https://www.example.com/app-ads.txt), but I encounter a 404 Not Found error when I include the trailing slash (https://www.example.com/app-ads.txt/). Question: Which is the best configuration to my Django application to handle both cases the app-ads.txt URL? is it with or without the backslash as per the documentation without Additionally, is there anything specific I need to do to ensure that Google's crawler can correctly detect changes to the domain URL? Any insights or suggestions would be greatly appreciated. Thank you! -
How to overcome: Uncaught SyntaxError: Unexpected token ':'
I am receiving this error: script.js:21 Uncaught SyntaxError: Unexpected token ':' My JSON is returning as this: ["2023-10-16", "2023-10-22"] which is valid JSON. The error is pointing to json_script: {{ unavailable_dates|json_script:'unavailable' }} const dates = JSON.parse(document.getElementById('unavailable').textContent); console.log(dates) $('#datepicker').datepicker ({ beforeShowDay: function (date) { var string = jQuery.datepicker.formatDate('yy-mm-dd', date); if ($.inArray(string, dates) != -1) { return [true, 'highlighted-date']; } else { return [true, '']; } }, }); -
ENOENT error : spawn on packaging ElectronJS + ReactJs + Django although it works on development mode, and paths are correct
I am developing a not very common type of desktop applications, it was a web app built by ReactJS and Django, and now I want to convert it into a desktop app, I used ElectronJS for wrapping this web app so it would be a desktop app. First I integrated ElectronJS and ReactJS together, and it worked very smoothly, then on adding the backend (Django), all I wanted was packaging Django (using PyInstaller), adding the Django dist to my electron app dist, and automatically launching the Django server using electron, the rest will all happen through ReactJS and Django, Electron is only to : 1- wrap this as a desktop app. 2- automatically launch the Django server. This worked on the development mode, the django server was launched, and the app worked perfectly, but on the setup of the electron app exe I got this error: error on setup Although the paths are correct, and the same exact way I handled this works on development. **This is my electron.js : ** const { app, BrowserWindow } = require('electron'); const { spawn } = require('child_process'); const path = require('path'); const isDev = require('electron-is-dev'); let mainWindow; function createWindow() { mainWindow = new … -
How to pass value from views.py to display on sendmail
I'm new in sendmail and I want to know if it is possible to pass a context value from views to Forms.py in django sendmail. In the image attached, the context value "getlogincode" is not displaying after I receive an email using sendmail. forms.py: class MyCustomLoginForm(LoginForm): def login(self, *args, **kwargs): html_content = render_to_string('getlogincode_sendmail.html') send_mail(subject="Reliance Assurance Worth", message=html_content, from_email=settings.EMAIL_HOST_USER, recipient_list=[self.user.email], html_message=html_content) # You must return the original result. return super(MyCustomLoginForm, self).login(*args, **kwargs) views.py: def GetLoginCodeView(request): #Get User LOGIN CODE user = Profile.objects.filter(user=request.user) for code in user: getlogincode = code.login_code #print(getlogincode) context = { 'getlogincode': getlogincode, } return render(request, 'getlogincode_sendmail.html', context) Template" getlogincode_sendmail.html <p style="padding-bottom: 16px">Please use the login code below to complete your request.</p> <p style="padding-bottom: 16px"><strong style="font-size: 150%;">{{ getlogincode }}</strong></p> -
Django Quiz- fetching data from database onto specific website
I am having troubles fetching data from my data base. The quiz questions are unpopulated. Chat GPT considers the code for correct. Check if there is anything that interferes with them downloading the questions from the database and displaying them at questionmanager.html. Please take a look and provide me with feedback: views.py # Questions' deletion and edition in separate htmls & urls class QuestionManagerView(LoginRequiredMixin, TemplateView): template_name = "questionmanager.html" context_object_name = "questions" # Fetching data from database: def get_queryset(self): multi_questions = MultiQuesModel.objects.all() single_choice_questions = SingleChoiceQuestion.objects.all() text_questions = SingleQuestion.objects.all() # Debugging: Add print statements to check data print("Multi Questions:", multi_questions) print("Single Choice Questions:", single_choice_questions) print("Text Questions:", text_questions) return {"multi_questions": multi_questions, "single_choice_questions": single_choice_questions, "text_questions": text_questions} # Add this method to handle form submissions def post(self, request, *args, **kwargs): # Process form data here # Debugging: Print form data answers_data = request.POST print("Form Data:", answers_data) # Validate the form form = YourFormHere(request.POST) print("Form is Valid:", form.is_valid()) print("Form Errors:", form.errors) if form.is_valid(): pass # Process the form data return super().get(request, *args, **kwargs) # Or redirect to another page class DeleteMultiQuestionView(DeleteView): model = MultiQuesModel def get_success_url(self): return reverse("question_manager") class DeleteSingleQuestionView(DeleteView): model = SingleChoiceQuestion def get_success_url(self): return reverse("question_manager") class DeleteTextQuestionView(DeleteView): model = SingleQuestion def get_success_url(self): return reverse("question_manager") … -
Django Ignoring TestCases
There are loads of questions with this issue, but whatever I try, it just doesn't want to work. This is the file structure of my project. As you can see, all directories have an init file. Here is the code within that tests.py from django.test import TestCase from django.contrib.auth import get_user_model class UserManagerTestCase(TestCase): def setUp(self): self.data = { "user": { "email": "normal@user.com", "password": "foo", "first_name": "Joe", "last_name": "Doe" } } def test_create_user(self): User = get_user_model() user = User.objects.create_user(**self.data['user']) self.assertEquals(user.email, self.data['user']['email']) self.assertEquals(user.first_name, self.data['user']['first_name']) self.assertEquals(user.last_name, self.data['user']['last_name']) self.assertTrue(user.is_active) Indentation here is a bit messed up. Not sure what causing the tests to be ignored. If I run the test by app namespace (python project/manage.py test project) it works fine, but If I try to run all the tests (python project/manage.py test) it says no tests are found. Thanks. -
error while saving database file foreignkey constrained failed realese restore point
from django.db import models from django.contrib import auth class Publisher(models.Model): name = models.CharField( max_length=50, help_text="The name of the publisher") website = models.URLField(help_text="The website of the publisher") email = models.EmailField(help_text="The email of the publisher") def str(self): return self.name class Book(models.Model): title = models.CharField(max_length=70, help_text="The title of the book") publication_date = models.DateField( verbose_name="Publication date") isbn = models.CharField( max_length=20, verbose_name="ISBN number of the book") publisher = models.ForeignKey( Publisher, on_delete=models.CASCADE) contributores = models.ManyToManyField( 'Contributor', through='BookContributor') def str(self): return self.title class Contributor(models.Model): first_names = models.CharField( max_length=50, help_text="The first names of the contributor") last_names = models.CharField( max_length=50, help_text="The last names of the contributor") email = models.EmailField(help_text="The email of the contributor") def str(self): return self.first_names class BookContributor(models.Model): class ContributionRole(models.TextChoices): AUTHOR = 'AUTHOR', 'Author' CO_AUTHOR = 'CO_AUTHOR', 'Co-author' EDITOR = 'EDITOR', 'Editor' CO_EDITOR = 'CO_EDITOR', 'Co-editor' book = models.ForeignKey(Book, on_delete=models.CASCADE) contributor = models.ForeignKey(Contributor, on_delete=models.CASCADE) role = models.CharField(verbose_name="Contribution role", choices=ContributionRole.choices, max_length=20) class Review(models.Model): content = models.TextField(help_text="The review text") rating = models.IntegerField(help_text="The rating the reviewer has given") date_created = models.DateTimeField( auto_now_add=True, help_text="The date and time the review was created") date_edited = models.DateTimeField( null=True, help_text="The date and time the review was edited") creator = models.ForeignKey( auth.get_user_model(), on_delete=models.CASCADE) book = models.ForeignKey( Book, on_delete=models.CASCADE, help_text="The book that this review is for") in my … -
how to detect vpn in django?
I want to find out if a user is using a VPN when a user sends a request to the API (to warn the user that he is using a VPN and to use the API he must turn off the VPN) I get the user's IP using the following code: def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip_list = x_forwarded_for.split(',') return ip_list[0].strip() return request.META.get('REMOTE_ADDR') But there are different ways to detect the use of VPN by the user, which are limited and also not free Is there a way to solve this problem?