Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I can't getting input fields in blog page but i written code for input fields in html page
I can't getting input fields in blog page but i written code for input fields in html page First i added some reactions you may see in my page it is saved in my sql server, i want to input fields to react for my post and those reactions(comments) should be displayed in below for my blog but input fields are hidden i am unable to see it, with my knowledge i written this below code but i can't getting input fields like email and comment box, i'm trying to display those reaction in same page index.html ''' forms.py from django import forms from . models import user_response class userfield(forms.ModelForm): class Meta: model = user_response fields='__all__' models.py from django.db import models # Create your models here. class user_response(models.Model): userName = models.CharField(max_length=15) userEmail = models.EmailField() message = models.TextField() def __str__(self): return self.userName, self.userEmail urls.py from django.urls import path from . import views urlpatterns = [ path('userdata/',views.userdata, name='userdata'), ] views.py from django.http import HttpResponse from django.shortcuts import redirect, render from . models import user_response from . forms import userfield # Create your views here. def userdata(request): if request.method == 'POST': form = userfield(request.POST) if form.is_valid(): form.save() return redirect(request, '../templates/index.html') else: form = … -
Django Snippets/Updating Primary Key
I have a client that requested (after launch) to start their records at a very large number (3,000,000). The model itself has at least 10 relationships/reverse relationships all through FK, established with "on_delete=CASCADE". Originally I was working with this snippet: https://djangosnippets.org/snippets/10619/, which gave quite a few errors. After some formatting (removing %s formatting for easier to read f-string formatting), the script ran but gave the dreaded: Cannot delete or update a parent row: a foreign key constraint fails. I am looking at any sort of way to get the 100 or so records (and their respective relationships) to update accordingly. I have already updated the MYSQL database to start numbering from the last record + 3,000,000 so that any resulting scripts should not result in a collision keeping the PK restraints. I believe there used to be a way to do this via a simple model.objects.all().update(id=F('id')+3000000), but this also has failed in Django 4.2. Any help is appreciated. d -
htmx isn't call in meta widgets
I'm trying to validate a field in a crispy form in Django using htmx: class Foo( forms.ModelForm ): id = forms.CharField( label='Id', disabled="true") # WORKING local_amount = forms.DecimalField( label='Local Amount', required=True, max_digits=10, decimal_places=2, widget=forms.TextInput(attrs={ 'type': 'number', # Use 'number' type for numeric input 'hx-get': reverse_lazy('check_amount'), 'hx-trigger': 'change', # Trigger the request when the value changes }) ) class Meta: model = Cost_schedule_org_unit fields = ['id','cost_schedule', 'local_amount',.....] # NOT WORKING IN THIS WAY widgets = { 'local_amount' : forms.TextInput(attrs={ 'type': 'number', # Use 'number' type for numeric input 'hx-get': reverse_lazy('check_amount'), 'hx-trigger': 'change', }) } The htmx call is working in the first way but not on the second way? -
Authenticating a user's identity using date of birth
I have a question regarding my implementation of an authentication system based on date of birth. I am using Django, but I think this question can be generalized. The use case is that the server already knows two things about the user, without them having made an account: a code uniquely assigned to them, and their date of birth. I want to use the combination of these things to authenticate their identity and display sensitive information that belongs specifically to them. I am trying to understand the best way to do this. Since the user will not be using this website very often, I do not want them to create an account. Currently my thought process is: user opens webpage with the unique token in the url and enters date of birth. Server validates the token and date of birth and informs the client. On subsequent requests to the server, include date of birth as a header or data field, and perform the same validation on the back-end. Would this work? Are there superior implementation patterns? -
Django: Separate Databases for Development, Test, and Production Environments - Migrations Not Applying
In my Django project, I'm trying to configure separate databases for the development, test, and production environments. To achieve this, I've made changes to my settings.py and created separate settings files: settings_development.py, settings_test.py, and settings_production.py. settings.py """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 4.2.5. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ import os from dotenv import load_dotenv from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent load_dotenv() # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.getenv('SECRET') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', ] 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 = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/4.2/ref/settings/#databases # DATABASES = { # 'default': … -
I'm trying to use inline forms and updateView, but is not working
I'm using django inline forms and crispy forms to make a CRUD, but I've changed the structure a little bit and the update i'snt working I created a forms.py to organize the inputs of the regular form and the inline form, using HTML inside it. 'Forms.py' class RegistroForm(forms.ModelForm): cliente = forms.ModelChoiceField(queryset=Cliente.objects.all(), empty_label='Selecione um cliente...') class Meta: model = Registro fields = ['cliente','totalPedido', 'tipo', 'vendedor', 'nome', 'cpf', 'email', 'rg', 'cidade', 'telefone', 'numero', 'rua', 'bairro', 'data'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Personalize o layout dos campos usando Crispy Forms self.helper = FormHelper() self.helper.form_class = 'form' self.helper.layout = Layout( HTML( ''' <div class="container-fluid"> <div class="col-sm-9 col-md-8 m-auto"> {% csrf_token %} <select class="form-select no-focus" id="id_cliente" name="cliente" onchange="update_cliente_data()"> <option value="" data-cliente='{"nome": "", "cpf": "", "email": "", "rg": "", "cidade": "", "telefone": "", "numero": "", "rua": "", "bairro": ""}'>Selecione um cliente...</option> {% for cliente in form.cliente.field.queryset %} <option id="opcao{{cliente.id}}" value="{{ cliente.id }}" data-cliente='{"nome": "{{ cliente.nome | title }}", "cpf": "{{ cliente.cpf }}", "email": "{{ cliente.email }}", "rg": "{{ cliente.rg }}", "cidade": "{{ cliente.cidade | title }}", "telefone": "{{ cliente.telefone }}", "numero": "{{ cliente.numero }}", "rua": "{{ cliente.rua | title }}", "bairro": "{{ cliente.bairro | title }}"}'>{{ cliente.nome | title }}</option> {% endfor %} </select> … -
Oracle "ORA-00942: table or view does not exist" using Django with multiple databases/schemas
I recently had to change up my Django back end to accommodate a "restricted database user". Instead of querying the database using the database admin user that is responsible for making/migrating migrations, a user with SELECT, INSERT, UPDATE, and DELETE on only the necessary tables was created. I set up the databases in settings.py like so: DATABASES = { 'default': {'ENGINE': 'django.db.backends.oracle', 'NAME': 'dbname', 'USER': 'restricted', 'PASSWORD': '*********', 'HOST': '*******************', 'PORT': '****', }, 'migrations': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'dbname', 'USER': 'admin', 'PASSWORD': '*********', 'HOST': '*********************', 'PORT': '****', }, } With the databases set up like this, any queries that are executed from your views go through the "default" restricted user, and the admin user is only there for migrations. To migrate, you would run - python manage.py makemigrations (this command does not change as it does not care about the database user) and then python manage.py migrate --database=migrations After doing this, none of my views worked, and I discovered the reason why. The next step that I had to do was to change all of the db_table values in my models.py to match the schema of the new user. So any db_table values went from this db_table = 'items' to … -
Django Middleware check if page contents was cached
I have a middleware that manages and denies access based on trial info stored in the user model. One aspect of it is that it increments the request count by 1 each time. But also on a lot of endpoints, we have the results returned cached using method_decorator. Is there a way to see if the page they're accessing is cached or not, so that I can avoid incrementing their request count if they would be using a cached result? -
How to add particular css classes to the checkboxes generated by a django MultipleChoiceField?
I have a django form that renders an MultipleChoiceField. In the __init__ part I define the choices for my field as a tuple. class MyForm(forms.ModelForm): my_field = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(attrs={'class': 'flat'})) ... def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) datas = Mymodel.objects.all() datas.sort(key=itemgetter('foo', 'bar')) datas_grouped = groupby(datas, key=itemgetter('foo')) choices = tuple() for foo, items in datas_grouped: items = tuple((i.get('label'), i.get('label')) for i in list(items)) choices += ((foo, items),) self.fields["my_field"].choices = choices The checkboxes are rendered as this: <input type="checkbox" name="my_field" value="Baz" class="flat" id="id_my_field_0_0"> I would like to render some checkboxes with a particular css class. The goal is to be able to target them in javascript to make grouped selections. How can I access each checkbox individually, in python, in order to add a class? -
How to design a dynamic gamification microservice in django
I want to implement a gamification microservice with Django that works alongside other microservices. In this microservice, I want to have points, ranks, coins, badges and credit cards for each user. Points: A number that is earned based on the user’s activity and this activity is not limited to purchase operations and can be earned by performing any kind of activity. Uses of points include increasing rank, buying discount codes and increasing lottery chances. Rank: For example, you can have 5 ranks for users and rank them based on the total points they have earned so far. The ranks can be named from “Newcomer” to “Professional” level. Special benefits are provided for each rank, which may include discounts, various notifications, coefficient in getting rewards, etc. Coins: Only earned for financial transactions. The higher the transaction amount, the more coins the user earns. You can get benefits other than discount codes through coins. Badge: They are awarded to a person for repeating a specific activity. Having badges gives the user special advantages. Credit card: A type of credit for in-app and out-of-app purchases. For example, you can buy a credit card for a specific product with a credit of $100 for … -
Nearest int query inside a json field object
I have a gigantic db with a json field object storing around 30 sub-objects per entry. Looks like that: { "field1": {"someOther": "stuffInside", [...]}, "field2": {"someOther": "stuffInside", [...]}, [...] } All these fields contain one field with a bigint. My objective is to be able to match the closest entry from a given int, for that purpose I made a function that does exactly that: def get_closest_match( field: str, match: int, model: django.db.models.Model, return_all_match: bool = False, sub_filter: dict or None = None, ): log.debug(f"Finding nearest in {model.__name__} with {field} {match}") result = model.objects.annotate(abs_diff=Func(F(field) - match, function='ABS')) if sub_filter: result = result.filter(**sub_filter) result = result.order_by('abs_diff') if not return_all_match: return result.first() return result While this function works great for int fields, I wasn't able to make it compatible with jsonfields, is there a way to make my function work with an int inside a jsonfield ? My first idea was to make a separate table storing only those bigints so I could use my method, which in fact works, but as mentionned above, each entry has around 30 objects and I have millions of entries so performance wise it is not very optimal (It also make data duplication which is not … -
`python manage.py qcluster` doesn't work on Windows 10, but the same project works on Linux
The problem is that I fetched a new part of the project related to qcluster from my colleague. I merged it with my project, but when I tried to use it with PS C:\Users\b2b\Desktop\tech\squirll> python manage.py qcluster I received this error: PS C:\Users\b2b\Desktop\tech\squirll> python manage.py qcluster 19:32:12 [Q] INFO Q Cluster pip-september-tennessee-papa starting. Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\b2b\AppData\Local\Programs\Python\Python310\lib\multiprocessing\spawn.py", line 116, in spawn_main exitcode = _main(fd, parent_sentinel) File "C:\Users\b2b\AppData\Local\Programs\Python\Python310\lib\multiprocessing\spawn.py", line 126, in _main self = reduction.pickle.load(from_parent) File "C:\Users\b2b\.virtualenvs\squalue-9_-wEM9I\lib\site-packages\django_q\cluster.py", line 12, in <module> from django_q.monitor import monitor File "C:\Users\b2b\.virtualenvs\squalue-9_-wEM9I\lib\site-packages\django_q\monitor.py", line 7, in <module> import django_q.tasks File "C:\Users\b2b\.virtualenvs\squalue-9_-wEM9I\lib\site-packages\django_q\tasks.py", line 14, in <module> from django_q.models import Schedule, Task File "C:\Users\b2b\.virtualenvs\squalue-9_-wEM9I\lib\site-packages\django_q\models.py", line 28, in <module> class Task(models.Model): File "C:\Users\b2b\.virtualenvs\squalue-9_-wEM9I\lib\site-packages\django\db\models\base.py", line 129, in __new__ app_config = apps.get_containing_app_config(module) File "C:\Users\b2b\.virtualenvs\squalue-9_-wEM9I\lib\site-packages\django\apps\registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "C:\Users\b2b\.virtualenvs\squalue-9_-wEM9I\lib\site-packages\django\apps\registry.py", line 138, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. What's odd, when my coleague used the same project that I have, via Github, on his Linux, it worked. So, something is not set correctly on my Win 10. I have the same libraries as he: PS C:\Users\b2b\Desktop\tech\squirll> pipenv shell Launching subshell in virtual environment... PowerShell 7.3.6 PS … -
Nginx + Ubuntu + Gunicorn + ORACLE CLOUD Private/Public IP
Im deploying my website into OCI account. In my cloud I have 2 IP adresses: Public and Private and im not sure how to setup my webserver. Here bellow is my code: NGINX setup server { listen 0; server_name **PRIVATE IP**; location /static/ { root /home/ubuntu/static/; } location / { proxy_pass http:**PRIVATE IP**:8000; } } GUNICORN setup command = '/home/ubuntu/py_env/bin/gunicorn' pythonpath = '/home/ubuntu/blog' bind = '**PRIVATE IP**:8000' workers = 3 Please advice how to setup it properly so i can access it from my browser via its IP. Im trying to access my website with is located on cloud by my browser via its IP adress. -
Where is the parameter 'request' used in view.py in django
A newbie in Django web development. I've got a tiny but puzzling question about request / response in views.py. I self-learn Django online and here comes the http request / response section. The code is as follows: #from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("<h1>123</h1>") I understand that the index page is requested and django creates a response which shows 123 in the index page. My questions are: with the request as the parameter of the function, isn't it used in the body of the function, just like def math(x): return x+1? Also, why does render become redundant in this trunk of code, where it should be used to produce output? Thanks for answering. -
Using django select_for_update for not updating but creating new records
I am using Django==2.2 and trying to create some new records for an object in django only if an upper limit is not reached. I was checking with unused_count = Account.objects.filter(field1__isnull=True, field2__isnull=True).count() vacancies = UPPER_LIMIT - unused_count if vacancies > 0: *create (vacancies) new accounts here* however we faced a case where this is not being respected and double the max limit accounts got created, and most probably seems like a concurrency issue. Just wanted to confirm that using unused_count = Account.objects.select_for_update().filter(field1__isnull=True, field2__isnull=True).count() will suffice and prevent this issue or not? The whole method is wrapped in @transaction.atomic -
Django : Get the list of a orderdetail
Hi i want to get the list (in json) first of the list of a Orderdetail. Indeed, I am trying to display all the order data with the details as mentioned below in the json code. Here is my code : models.py # model Driver class Drivers(models.Model): driver_id = models.AutoField(primary_key=True) driver_fullname = models.CharField(max_length=500) class Meta: db_table ="drivers" # model Truck class Trucks(models.Model): truck_id = models.AutoField(primary_key=True) truck_matricule = models.CharField(max_length=500) class Meta: db_table ="trucks" # model Product class Products(models.Model): product_id = models.AutoField(primary_key=True) product_name = models.CharField(max_length=500) class Meta: db_table ="products" # model Order class Orders(models.Model): order_id = models.AutoField(primary_key=True) order_number = models.CharField(max_length=500) statut = models.CharField(max_length=500, default="validé") date_of_order = models.DateField() company = models.ForeignKey(Companies, on_delete = models.CASCADE) products = models.ManyToManyField(Products, through='OrdersDetail') class Meta: db_table ="orders" # model OrdersDetail class OrdersDetail(models.Model): Order = models.ForeignKey(Orders, on_delete=models.CASCADE) product = models.ForeignKey(Products, on_delete=models.CASCADE) driver = models.ForeignKey(Drivers, on_delete = models.CASCADE) truck = models.ForeignKey(Trucks, on_delete = models.CASCADE) product_quantity = models.PositiveIntegerField(default=1) # amount = models.IntegerField(default=1) class Meta: db_table ="ordersdetails" serializers.py class TruckSerializer(serializers.ModelSerializer): class Meta: model=Trucks fields = '_all_' class MeasureSerializer(serializers.ModelSerializer): class Meta: model=Measures fields = '_all_' class ProductSerializer(serializers.ModelSerializer): class Meta: model=Products fields = '_all_' class OrderDetailSerializer(serializers.ModelSerializer): company = CompanySerializer() products = ProductSerializer() truck = TruckSerializer() driver = DriverSerializer() class Meta: model = OrdersDetail fields … -
How to Customize the Error Response in Django
This is what i want! I have a view and i want to send the API JWT Token along with request i want to verify if the token is valid or not if it is Valid it gives the responce Response({"gpcars": gpSerial.data, "featuredCars": featSerial.data, "recentcars": RecentSerial.data}, status=status.HTTP_200_OK) and if its not valid so the user is unauthenticated then this should be the responce Response({"gpcars": gpSerial.data, "featuredCars": featSerial.data, "recentcars": RecentSerial.data}, status=status.HTTP_401_UNAUTHENTICATED) Basically i want to determine if the user is logged in or not along with the request. This is what i have tried permission_classes = [IsAuthenticated] def get(self, request): try: # Fetch the first 5 Car objects GpCars = Car.objects.order_by( '-stockid').filter(gpcar=True, featured=False)[:6] FeaturedCars = Car.objects.order_by( '-stockid').filter(gpcar=False, featured=True)[:6] RecentCars = Car.objects.order_by( '-stockid').filter(gpcar=False, featured=False)[:6] # Serialize the queryset gpSerial = CarSerializer(GpCars, many=True) featSerial = CarSerializer(FeaturedCars, many=True) RecentSerial = CarSerializer(RecentCars, many=True) time.sleep(5) return Response({"gpcars": gpSerial.data, "featuredCars": featSerial.data, "recentcars": RecentSerial.data}, status=status.HTTP_200_OK) except Exception as e: # Handle other exceptions as needed return Response({"gpcars": gpSerial.data, "featuredCars": featSerial.data, "recentcars": RecentSerial.data}, status=status.HTTP_401_UNAUTHENTICATED) -
Online Banking payment solution
I try to plug a BBVA Bank (Spanish) payment solution on my website. I work with Python and Django framework I have an error code SIS0431 which is telling me "Parameter error" without more precisions. The bank doesn't reply to my questions. This is my code : BANK_PAIEMENT_URL = "https://sis-t.redsys.es:25443/sis/realizarPago" # TEST API amount_decimal = payment.amount amount_integer = int(amount_decimal * Decimal("100")) # because bank need 4999 instead of 49.99 context["BANK_PAIEMENT_URL"] = BANK_PAIEMENT_URL url_ok = request.build_absolute_uri(reverse("front:shop_cart_payment_success")) url_ko = request.build_absolute_uri(reverse("front:shop_cart_payment_error")) print(f"amount_integer = {amount_integer}") #Data fo JSON data = { "DS_MERCHANT_AMOUNT": str(amount_integer), "DS_MERCHANT_ORDER": payment.payment_number, "DS_MERCHANT_MERCHANTCODE": "123456789", # HIDE "DS_MERCHANT_CURRENCY": "978", "DS_MERCHANT_TRANSACTIONTYPE": "0", "DS_MERCHANT_TERMINAL": "001", "DS_MERCHANT_URLOK": url_ok, "DS_MERCHANT_URLKO": url_ko, "DS_MERCHANT_MERCHANTNAME": "XXX", # HIDE "DS_MERCHANT_CONSUMERLANGUAGE": "004" } json_data = json.dumps(data) print(f"json_data = {json_data}") encoded_data = base64.b64encode(json_data.encode('utf-8')) context["Ds_MerchantParameters"] = encoded_data # secert key for HMAC cle_secrete = b'XXXXX' # HIDE # HMAC SHA256 signature = hmac.new(cle_secrete, encoded_data, hashlib.sha256).hexdigest() context["Ds_Signature"] = signature return render(request, 'front/shop_payement_proceed.html', context) and the html : <form action="{{ BANK_PAIEMENT_URL }}" method="post" target="_blank"> <input type="hidden" name="Ds_SignatureVersion" value="HMAC_SHA256_V1"/> <input type="hidden" name="Ds_MerchantParameters" value="{{ Ds_MerchantParameters }}"/> <input type="hidden" name="Ds_Signature" value="{{ Ds_Signature }}"/> <input type="submit" value="Procéder au paiement"> </form> Thanks for reading, if you need more information ask me. -
Problem generating dynamic HMTL with python
I have a WebApp that it generated a dynamic html depending on logged user. The problem is sometimes open mes.html page but that is completely empty, and I see white on browser, and the code of this file is completely empty. But many times that work properly. What can to be the problem? def calendario(request): miCalendario = FormularioCalendario(request.POST) aino = 2023 usuario = request.user.id user = User.objects.get(id=usuario) if request.method=='POST' and ('cargar' in request.POST): miCalendario = FormularioCalendario(request.POST) obtener_mes(miCalendario.data['mes'],aino,user) return render(request, "BieleGastosApp/mes.html", {"calendario": miCalendario}) return render(request, "BieleGastosApp/calendario.html", {"calendario": miCalendario}) def obtener_mes(mes, aino,usuario): mem_sem=0 aino= 2023 res_mes = [] BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) mes_file = os.path.join(BASE_DIR, 'BieleGastosApp/templates/BieleGastosApp/mes.html') f = open(mes_file,'w') html=""" {% extends "BieleGastosApp/base.html" %} {% load static %} {% block content %} <div align="center"> <form action="" method="POST" > <table> {{ calendario.mes }} </table> <div> <p> --------------------- </p> </div> <input class="boton" type="submit" value="Cargar" name="cargar"> {% csrf_token %} </form> </div> <div align="center"> <table width="50%" border="0" align="center" id="mes_calendario"> <th> <td align='center'>Lun </td> <td align='center' >Mar </td> <td align='center'>Mie </td> <td align='center'>Jue </td> <td align='center'>Vie </td> <td align='center'>Sab </td> <td align='center'>Dom </td> </th> """ #user = Usuario.objects.get(autor= usuario) for i in range (1,32,+1): horas_viaje = 0 viaje_opacity=0.0 horas_trabajo = 0 trabajo_opacity=0.0 pernocta_opacity=0.0 gastos_opacity = 0.0 fecha = … -
can't login after creating a user in django, login function returns none
after I created a user in Django I then tried to login but can't. i don't if its a setting that needs to be done or the problem is with the code. this is my sign-in views # def signin(request): if request.method == 'POST': email = request.POST.get('email') pass1 = request.POST.get('password1') user = authenticate(email=email, password=pass1) if user is not None: login(request, user) fname = user.first_name return render (request, 'store.html', {'fname':fname}) else: messages.error(request, 'invalid password or email') return render (request, 'signin.html') return render (request, 'signin.html') and sign-up views the pass2 says variable not accessed def signup(request): if request.method == 'POST': username = request.POST['username'] email = request.POST['email'] fname = request.POST['fname'] lname = request.POST['lname'] pass1 = request.POST['password1'] pass2 = request.POST['password2'] myuser = User.objects.create_user(username, email, pass1, ) myuser.first_name = fname myuser.last_name = lname myuser.save() return redirect ('signin' ) return render(request, 'signup.html') this is my signup.html <form method="post" action="signup"> {% csrf_token %} <div class="mb-3"> <label for="" class="form-label">Account name</label> <input type="text" class="form-control" id="username" name="username" placeholder="account name" required> </div> <div class="mb-3"> <label for="" class="form-label">Email address</label> <input type="email" class="form-control" id="email" aria-describedby="emailHelp" name="email" placeholder="Enter email address" required> </div> <div class="mb-3"> <label for="" class="form-label">First name </label> <input type="text" class="form-control" id="fname" name="fname" placeholder="First name " required> </div> <div class="mb-3"> <label for="" class="form-label">Last … -
Django static files not found when I try to specify favicon
I'm developing my first Django website. I have an issue with static files. In my homepage I linked my logo with this code. <img class="d-block mx-auto mb-4" src="{% static 'mysite/images/logo.png' %}" alt="" width="300" height="225"> It was perfectly ok. When I tried to change my favicon and tried to link another .png file from the static folder, it can't find the favicon png image. <link rel="shortcut icon" href="{% static '/mysite/images/logo.png' %}" > I don't know why it doesn't detect the favicon while getting the logo. My settings.py file: STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') If I try to link another pictures It can't find. Only my logo.png is available. -
Django consumer frequently get disconnected and reconnected on different pods on K8S
big brothers! I deployed my Django app on K8S pods. I implemented websocket server with websocket consumer using Django channels package. And the problem is, I found K8S would frequently close and reconnect websocket connection, that's to say K8S would frequently new consumer objects on the same websocket connection URL on different pods. I have cached data inside consumer object, and this situation really bothers. How can I keep websocket connection in K8S? -
Django composite Key
I have a table called "Tickets" and exact copy of this same table called "Logs" .The aim is to copy every data into "Logs" . So to keep the structure same I need to exclude Django default generated field "id" and planned to use a composite key with field name "ticket_no" and "updated_on". is there any way to make these field as primary key without this 'id'. -
Adding a Threaded Comment functionality in my Django blog using FETCH API
Please I am stuck on a problem I've been trying to solve by myself for up to a month now. I am at my wit's end. So I have a Django blog and I am trying to implement a threaded comment functionality using FETCH API to avoid a page refresh each time a comment is submitted. Also, I intend to limit the number of comments shown first to just 10 with a "load more comments" button at the bottom that when clicked would reveal the next 10 comments, and so on until there is no more comment to be shown at which point the "load more comments" button disappears. You see, I successfully implemented this feature with FETCH API for only single parent comments. But I am trying to take my blog further by adding a threaded comment, or rather, to make it possible for parent comments to have child comments. However, I can't seem to successfully implement the above functionalities asynchronously. Only after reloading the page do the parent comments and child comments show on the page, but I want the comments to show immediately after hitting the comment submit button. I believe the problem is with my Javascript … -
How to make text remain on page even after user exits and opens again?
Using js,it is possible to make text remain on screen when user submits the text, but I want that it remains even after user exits or lets say opens the website on a different device. I think databases would be involved. Can we use Django for this purpose? I am trying to make a website like a common notepad type thing. Anyone who opens the site can add text and leave and it stays there until he himself or any other person removes the number. How should I proceed with this idea?