Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Authorization button not appearing in Django Ninja API docs
I am using Django Ninja to build an API, and I am having trouble getting the authorization button to appear in the API docs. I have already added the rest_auth app to my INSTALLED_APPS and add this REST_AUTH_DEFAULT_AUTHENTICATION_CLASS = 'rest_auth.authentication.TokenAuthentication' to my Django settings file, but the button is still not appearing.and this is my api docs and as you see the authorization button don't appear I expected the authorization button to appear in the API docs, so that I could use it to authenticate with my API. However, the button is not appearing. -
Django Allauth - ModuleNotFoundError: No module named 'allauth.account.middleware' even when django-allauth is properly installed
"ModuleNotFoundError: No module named 'allauth.account.middleware'" I keep getting this error in my django project even when django-allauth is all installed and setup??? I tried even reinstalling and changing my python to python3 but didn't change anything, can't figure out why all other imports are working but the MIDDLEWARE one... Help pls? settings.py: """ Django settings for youtube2blog2 project. Generated by 'django-admin startproject' using Django 4.2.4. For more information on this file, see For the full list of settings and their values, see """ from pathlib import Path import django import os import logging import pyfiglet import allauth # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-l_pc%*s54c__=3ub&@d)s&@zp*46*=@)y*uv@v&(b6+hwq1&u5' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # CUSTOM CODE # os.environ['FFMPEG_PATH'] = '/third-party/ffmpeg.exe' # os.environ['FFPROBE_PATH'] = '/third-party/ffplay.exe' OFFLINE_VERSION = False def offline_version_setup(databases): if (OFFLINE_VERSION): # WRITE CODE TO REPLACE DATABASES DICT DATA FOR OFFLINE SETUP HERE return True return banner_ascii_art = pyfiglet.figlet_format("CHRIST IS KING ENTERPRISES") logger = logging.getLogger() logger.setLevel(logging.DEBUG) print("\n - CURRENT DJANGO VERSION: " + … -
How to update django user profile information from a form?
I'm creating a web application to track my friends personal bets amongst eachother.. I have added a UserBalance value to the user model, but now I want superuser/admins to be able to update that upon submitting a form. List of all bets Leaderboard with user balances How would I go about making it so the form in last column of first screenshot will update both bettor's balances? accounts models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class UserBalance(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) balance = models.IntegerField(default=0) @receiver(post_save, sender=User) def create_user_balance(sender, instance, created, **kwargs): if created: UserBalance.objects.create(user=instance) I assume I need to add a method somewhere to take the winner/loser form info and then change the corresponding user's balances but I'm not sure where to do that or how -
not being able to access a variable in python flask
Let me briefly explain to you what I want to do: I want to get the username of the commenter to comment on an article. for this I perform a query from the articles table (sorgu2). Finally, I find the username of the person who made the comment, but I get an error. mistake:UnboundLocalError: cannot access local variable 'cevaplanan' where it is not associated with a value how do i solve this please help `@app.route('/yorum/string:article_title/', methods=["GET","POST"]) def yorum_ekle(article_title): cevap = CevapVer(request.form) form = ArticleForm(request.form) if request.method=="POST" and cevap.validate(): icerik = cevap.icerik.data cursor2 = mysql.connection.cursor() cnt = form.content.data tit = form.title.data sorgu2 = "SELECT author FROM articles WHERE title = %s AND content = %s " cursor2.execute(sorgu2,(cnt,tit)) sonuclar = cursor2.fetchall() cevaplanan = None cursor = mysql.connection.cursor() sorgu = "insert into yorum(icerik,cevaplayan,cevaplanan) values(%s,%s,%s)" cursor.execute(sorgu,(icerik,session["username"],cevaplanan)) mysql.connection.commit() cursor.close() flash("Yorum eklendi","success") return render_template('cevapla.html', article_title=article_title, cevap=cevap) ` I was trying to get a username with sql but couldn't get it -
Order tracking in django
I am a beginner in django and I want to create a web app where a user can enter an order ID and the status of that order will be displayed(eg pending) , and If I change the status it will also change for the user(Ie from pending to processed) how do I go about it Just started out haven’t tried anything yet -
Getting csrf token and sessionid from response headers in react app
We are creating some site. We have react + django rest framework.We use SessionAuthentication in django. So, we have issues with authentication. When frontend is trying to login, he get's status 200, but he can't get csrf token and sessionid from response headers, that backend hash sent. We can see them(csrf token and sessionid) in browser Network as Set-cookie values, also we see them in Postman, but not in js. Why? How can we get them? There is part of my settings.py: MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', 'django.contrib.messages.middleware.MessageMiddleware' ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', ] } CORS_ALLOWED_ORIGINS = [ 'http://localhost:5173', ] CORS_ALLOW_CREDENTIALS = True CSRF_TRUSTED_ORIGINS = [ 'http://localhost:5173', ] SESSION_COOKIE_HTTPONLY = False CSRF_COOKIE_HTTPONLY = False CSRF_COOKIE_SECURE = False SESSION_COOKIE_SECURE = False CSRF_COOKIE_SAMESITE = 'None' SESSION_COOKIE_SAMESITE = 'None' I've tried many of settings, have tried to combine them in separate ways, but it didn't help There is react code: import axios from "axios"; axios.defaults.withCredentials = true; export default async function login(data){ axios.post( 'http://127.0.0.1:8000/user/session/', data ) .then( (response) => { console.log(response) // const headerKeys = Object.keys(response.headers); // console.log(headerKeys); // console.log('Set-Cookie:', response.headers['set-cookie']) }) } This is screenshot of what we get in jsresponse js This is what … -
How to create a copy to clickboard for dynamic buttons
Hi guys I'm working currently on a little project with django and Js, I want to add a button to copy information to clickboard, the buttons are dynamic and the site where I'm working is not https so i can't use "navigator.clipboard.writeText" at this point i can get the information trough the attributes specified in my button, but I'm a litle bit stuck since i don't really know how to copy the information from the variables to the clickboard, I'm newbie so if someone can help me with this it would be really nice :) This is basically the main piece of code {% for item in object_list %} <tr> <td class="th-width">{{ item.user.company.name }}</td> <td class="th-width">{{ item.user.user_name }}</td> <td class="th-width">{{ item.user.full_name }}</td> <td class="th-width email-column">{{ item.user.email }}</td> <td class="th-width">{{ item.expire_date }}</td> <td class="th-width">{{ item.avt_version}}</td> <td class="th-width">{{ item.license_avt }}</td> <td class="th-width">{{ item.generated_user.username }}</td> <td class="th-width"> <button class="control button copy-btn btn" company-name="{{item.user.company.name}}" user-name="{{item.user.user_name}}" full-name="{{item.user.full_name}}" email="{{item.user.email}}" expire-date="{{item.expire_date}}">Copy information</button> </td> </tr> {% endfor %} </tbody> </table> <script> const copyBtns = [...document.getElementsByClassName("copy-btn")] copyBtns.forEach(btn => btn.addEventListener('click', () => { const companyName = btn.getAttribute("company-name") const userName = btn.getAttribute("user-name") const fullName = btn.getAttribute("full-name") const email = btn.getAttribute("email") const expireDate = btn.getAttribute("expire-date") console.log(companyName) console.log(userName) console.log(fullName) console.log(email) console.log(expireDate) btn.textContent = … -
How do I conditionally exclude/ include field in fomset on Django admin site TabularInline?
Point System QA model with Point System QA details model rendered as tabular inline form. How can I conditionally exclude/include a field from the Point System QA details formset? Any help would be much appreciated. Model class PointSystemQADetails(models.Model): point_name = models.ForeignKey('PointSystemQA', blank=True, null=True, on_delete=models.SET_NULL) brand = models.IntegerField(blank=True, null=True) model = models.IntegerField(blank=True, null=True) amount = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) ... more filed Admin page: # Point System QA Details Formset # class PointSystemQADetailsFormSet(BaseInlineFormSet): def get_form_kwargs(self, index): kwargs = super().get_form_kwargs(index) kwargs['parent_object'] = self.instance return kwargs class PointSystemQADetailsForm(forms.ModelForm): brand = forms.ChoiceField(choices = []) model = forms.ChoiceField(choices = []) def __init__(self, *args, parent_object, **kwargs): self.parent_object = parent_object super(PointSystemQADetailsForm, self).__init__(*args, **kwargs) if self.parent_object.device_type.id == 19: del self.fields['model'] # not working.. self.fields['brand'].choices = [('', '------'),] + [(x.pk, x.manufacturer_name) for x in Manufacturer.objects.all()] else: self.fields['brand'].choices = [('', '------'),] + [(x.pk, x.manufacturer_name) for x in Manufacturer.objects.all()] self.fields['model'].choices = [('', '------'),] + [(x.pk, x.series) for x in WatchSeries.objects.all()] class PointSystemQADetailsAdmin(admin.TabularInline): model = PointSystemQADetails formset = PointSystemQADetailsFormSet form = PointSystemQADetailsForm extra = 1 # End Point System # class PointSystemQAAdminForm(forms.ModelForm): class Meta: model = PointSystemQA exclude = ['created_at', 'updated_at', 'created_by', 'updated_by'] class PointSystemQAAdmin(admin.ModelAdmin): model = PointSystemQA inlines = [PointSystemQADetailsAdmin] form = PointSystemQAAdminForm save_on_top = True list_display_links = ('point_name', ) search_fields … -
why django page not found/ URL patterns didn't match?
why page not found what is incrorrect on my code ? and there the dealerships code if there any mistake let me know dealships-home- ` <body> <nav class="navbar navbar-light bg-light"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="#">Dealership Review</a> </div> <ul class="nav navbar-nav navbar-right"> {% if user.is_authenticated %} <div class="rightalign"> <div class="dropdown"> <button class="dropbtn">{{user.first_name}}</button> <div class="dropdown-content"> <a href="{% url 'djangoapp:logout' %}">Logout</a> </div> </div> </div> {% else %} <div class="rightalign"> <div class="dropdown"> <form action="{% url 'djangoapp:registration' %}" method="get"> <input class="dropbtn" type="submit" value="Visitor" /> <div class="dropdown-content"> <a href="{% url 'djangoapp:registration' %}">Signup</a> <a href="{% url 'djangoapp:login' %}">Login</a> </div> </form> </div> </div> {% endif %} </ul> </div> </nav>` and there the url code if there any mistake let me know url: `app_name = 'djangoapp' urlpatterns = [ # path for dealerships/index path(route='dealerships/', view=views.get_dealerships, name='dealerships'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ` and there the views code if there any mistake let me know Views: ` def get_dealerships(request): context = {} if request.method == "GET": return render(request, 'djangoapp/dealerships.html', context)` Any suggestions -
Unable to use MySql with Django
I am trying to get Django running with MySql, I am following this guide: https://docs.djangoproject.com/en/4.2/intro/tutorial02/ Everything works up until this command: python manage.py migrate I will include the entire error, the punchline is: Traceback (most recent call last): File "/Users/timo/opt/anaconda3/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database File "/Users/timo/opt/anaconda3/lib/python3.9/site-packages/MySQLdb/__init__.py", line 17, in <module> from . import _mysql ImportError: dlopen(/Users/timo/opt/anaconda3/lib/python3.9/site-packages/MySQLdb/_mysql.cpython-39-darwin.so, 0x0002): symbol not found in flat namespace '_mysql_affected_rows' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/timo/Documents/coding/plegeus/musicians/backend/manage.py", line 22, in <module> main() File "/Users/timo/Documents/coding/plegeus/musicians/backend/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/timo/opt/anaconda3/lib/python3.9/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/Users/timo/opt/anaconda3/lib/python3.9/site-packages/django/core/management/__init__.py", line 416, in execute django.setup() File "/Users/timo/opt/anaconda3/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/timo/opt/anaconda3/lib/python3.9/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/Users/timo/opt/anaconda3/lib/python3.9/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "/Users/timo/opt/anaconda3/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/timo/opt/anaconda3/lib/python3.9/site-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/timo/opt/anaconda3/lib/python3.9/site-packages/django/contrib/auth/base_user.py", … -
How to redirect the login to an app, model specific
I need that when I log in, it shows me directly an admin model.. Example, I have the app nameapp, and within the models nodel_one, model_two that are different tables, I need it to show me the records of one of those tables when entering after login. How do I set the urls? I have: # file: intrados/intrados/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('daytona/', include("daytona.urls")), path('', admin.site.urls), # home also goes to admin ] And I need to go to # file: intrados/daytona/admin.py is in URL http://localhost:8000/admin/daytona/domain/ class DomainAdmin(SetReadOnlyModel, admin.ModelAdmin): #xxxxxxxxx te redirect specific table to see records -
changing the project name and environment doesn't work
After my project name was changed, when I activate my environment in my project, it shows activated but doesn't work in wsl2 -
How do I change my whole form based on a user selection? Using Django/Python
I need to build a registration form for industrial equipments. But I want that form to change based on a user selection. For example, some type of equipments require a different types of values and what I need is when the user select a type of equipment the form adapting automatically to what the user needs and later on, save that data in a database. I already tried the Dynamically Change Form Action Based on Selection using jquery, but (as far as I know) this only works for dropdowns menus changing data for another dropdown menu, like when you are on a site that asks for your country in a dropdown menu and in another dropdown right under is a dropdown to select the cities from the country that you selected. Unfortunelly this doesn't help me. What I need is to change the whole form. I'm picturing like a button or checkbox, or even a dropdown menu above the form that asks for the user to choose what type of equipment they want to register and then the form changes. -
Can you tell why here create two objects instead of one object of Notification?
Here I would like to create a notification after creating a blog. It's working fine, but the issue is here creating two objects of Notification instead of one object. Can you tell me where is the problem in my code? models.py: class blog(models.Model): title = models.CharField(max_length=250) img = models.ImageField(upload_to="img_file/", blank=True, null=True) def __str__(self): return f"{self.pk}.{self.title}" class Notification(models.Model): title = models.CharField(max_length=250) details = models.TextField() is_seen = models.BooleanField(default=False) def __str__(self): return f"{self.pk}.{self.title}" signal.py: from django.db.models.signals import post_save from django.dispatch import receiver from .models import blog, Notification @receiver(post_save, sender=blog) def call_notification(sender, instance, **kwargs): Notification.objects.create( title="New Blog Post uploaded", details=f"{instance.id} number Blog" ) -
Django-Rest MultiPartParser vs JsonParser
Imagin in javscript have a object like below : {is_active:false,date:null} it is the data that i get from a form and then i POST this data to the django server when i send data with header: 'Content-Type': 'application/json' , in server i receive this: is_active:False date:None but when i send data with header: 'Content-Type': 'multipart/form-data' , in server i receive this: is_active:'false' date:'null' is there any way to when sending data with 'multipart/form-data' header , and geting python object insted of get an strings -
I am working on a django project and for payment integration we need SSLCOMMERZ python . While installing this problem arises
I am working on a Django project and attempting to install the sslcommerz-python\ package for payment integration. However, I encountered an error during the installation process. Here's the error message: pip install sslcommerz-python Collecting sslcommerz-python ... Building wheels for collected packages: typed-ast Building wheel for typed-ast (setup.py) ... error ... Failed to build typed-ast ERROR: Could not build wheels for typed-ast, which is required to install pyproject.toml-based projects This is the error I get while installing sslcommerz python Thanks in advance for your help. -
Django TextField (CharField) in OuterRef to list with filter _in
I tried filter queryset in Subquery, but can not use filter _in with OuterRef. UserAccount.objects.filter(groups__name__contains=group).annotate( spend=Cast(Subquery(FacebookStatistic.objects.filter( ad_account__id_ad__in=[el.strip() for el in str(OuterRef('facebook_ad_accounts')).split(',')], ).annotate(spd=Coalesce(Func('spend', function='Sum'), 0, output_field=FloatField()) ).values('spd') ), output_field=FloatField()), ) This filter don't work. Text Field not converting to string str(OuterRef('facebook_ad_accounts')) Plese tell me, how can I do it? -
Trouble access django models with celery for background tasks
I'm utilizing Celery within my Django project to execute tasks in the background. However, I've encountered an issue when try to access models using apps "from django.apps import apps". The problem arises when I use this method to access a model, as it raises an "object does not exist" error. Even when I try to resolve it by using relative imports, I still got the same problem. I would greatly appreciate any insights or solutions . If anyone has encountered a similar issue or has knowledge about integrating Celery with Django . ps: Im use Supervisor in order to run celery execution process. here is the celery task from celery import shared_task from django.apps import apps from campaigns.api import send_campaign from campaigns.constants import CampaignStatus from django.core.mail import mail_managers @shared_task def send_campaign_task(campaign_id): Campaign = apps.get_model('campaigns', 'Campaign') try: campaign = Campaign.objects.get(pk=campaign_id) if campaign.campaign_status == CampaignStatus.QUEUED: send_campaign(campaign) mail_managers( f'Mailing campaign has been sent', 'Your campaign "{campaign.email.subject}" is on its way to your subscribers!' ) else: logger.warning( 'Campaign "%s" was placed in a queue with status "%s".' % (campaign_id, campaign.get_campaign_status_display()) ) except Campaign.DoesNotExist: logger.exception( 'Campaign "%s" was placed in a queue but it does not exist.' % campaign_id) and this is the log of … -
Overriding LOGIN_REDIRECT_URL = "page-name" for a specific function in Django
I have a base.py file that states a default redirection page when the user registers and gets logged in. base.py LOGIN_REDIRECT_URL = "index" I want to create to possibility for a user that connects from a specific page page_1 to signup/login directly from this page. When they sign up/login they will be redirected to the same page1 which will show a different content based on whether the user is authenticated or not. (if authenticated they get content, if not they get the signup/login prompt) The problem I am running into (I think) is that when a user register from page_1, this user is redirected to index page as defined in my base.py. Is there a way to override the base.py for a specific function? I left my latest attempt request.session['LOGIN_REDIRECT_URL'] = url. Which didnt work. def show_venue(request, page_id): #REGISTER USER FROM VENUE url = request.META.get('HTTP_REFERER') print(f'url ={url}') if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active=True user.save() user = authenticate(username = form.cleaned_data['username'], password = form.cleaned_data['password1'],) login(request,user) request.session['LOGIN_REDIRECT_URL'] = url else: for error in list(form.errors.values()): messages.error(request, error) else: form = RegisterForm() -
login with django in a microservices architecture
I'm trying to login and authenticate my user in a microservices architecture def form_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') api_url = 'http://127.0.0.1:8000/login/' data = { 'username': username, 'password': password, } try: response = requests.post(api_url, data) if response.status_code == 200: print("Usuário autenticado com sucesso.") return redirect('home') elif response.status_code == 400: messages.error(request, 'Credenciais inválidas', extra_tags='login_error') except requests.exceptions.RequestException: messages.error(request, 'Credenciais inválidas', extra_tags='login_error') return render(request, 'login.html') This view takes the username and password from the form and sends it to my API endpoint in the microservice and if the authentication is successful and returns status 200 it redirects to the main page if it returns status 400, it gives an error message class UserLogin(APIView): def post(self, request): username = request.data.get('username') password = request.data.get('password') user = authenticate(request, username=username, password=password) print(user) if user is not None: login(request, user) return Response({'detail': 'Autenticação bem sucedida'}, status=status.HTTP_200_OK) else: return Response({'detail': 'Credenciais inválidas'}, status=status.HTTP_400_BAD_REQUEST) This view takes the username and password from the other view, authenticates using django's 'authenticate' if the user exists, logs in with django's 'login' and returns status 200 and if it does not exist, returns status 400 My problem is that: the view sends the username and password, the API gets … -
Django AJAX Form submission is always invalid
I have a Django Project with a view that contains two forms that I want to be submitted with two separate ajax requests. The first ajax request is actually supposed to fill in one value of the second form which this does successfully. Also, the second form has a few initial values that I later plan on making hidden so the user only sees the necessary fields to fill in after submitting the first form. I am passing in an "ajax_type" keyword after checking for "request.is_ajax()" and "request.method == 'POST' within my view to determine if the ajax type is the first ajax request or the second one. My second ajax request makes use of a model form that is supposed to create a new instance of my model upon validation. My View: def canadaTaxEntries(request): newest_record = LAWCHG.objects.aggregate(Max('control_number')) newest_control_number = newest_record["control_number__max"] print(newest_control_number) today = date.today().strftime("1%y%m%d") current_time = time.strftime("%H%M%S") #print(today) #print(current_time) initial_data = { 'control_number': (newest_control_number + 1), 'item_number': None, 'vendor_tax_code': None, 'expiration_flag': 1, 'charge_category': None, 'charge_desc_code': None, 'country': 'US', 'state': None, 'city': None, 'county': None, 'charge_amount': None, 'charge_uom': 'CA', 'charge_percentage': 0.0, 'apply_flag': 1, 'beg_del_date': None, 'end_del_date': None, 'rev_date': today, 'rev_time': current_time, 'est_date': today, 'est_time': current_time, 'program_id': 'BI008', 'operator_id': 'FKRUGER', } … -
Session is not working and showng keyError at task
Hello i was trying to fix my session but it did not work. it shows KeyError at /task/ 'tasK'. I tried many things . I changed the setting but it didnt work too: SESSION_COOKIE_SECURE = True SESSION_COOKIE_SECURE != DEBUG my code is: from django.shortcuts import render from django import forms class TaskForm(forms.Form): input = forms.CharField(label="New Task", max_length=255) # Verwende CharField für Texteingabe def show_task(request): if "tasK" != request.session: request.session["tasK"] = [] return render(request, "hi/j.html", {"tasK": request.session["tasK"]}) def show(request): if request.method == "POST": form = TaskForm(request.POST) if form.is_valid(): task = form.cleaned_data["input"] request.session["tasK"].append(task) # Verwende .append() statt += request.session.modified = True # Speichere die Änderungen in der Session request.session.save() else: return render(request, "hi/j.html", {"form": form}) return render(request, "hi/k.html", {"forms": TaskForm()}) -
Serving image uploads with apache and django
I am programming a ticket system, where users can upload their favorite thing: screenshots with red circles! Each ticket gets an ID and has an upload field. I use one django project with one app that uses this upload function. What I've done I followed the official steps on How to use Django with Apache and mod_wsgi and that works. My website is available under http://localhost. Where I am stuck I am stuck at the next step of the documentation How to authenticate against Django’s user database from Apache When I come to the part where they suggest to add the following code, the whole website gets an 500 Internal Server Error Code to be added to wsgi.py: import os os.environ["DJANGO_SETTINGS_MODULE"] = "mysite.settings" from django.contrib.auth.handlers.modwsgi import check_password from django.core.handlers.wsgi import WSGIHandler application = WSGIHandler() I didn't touch nor change the wsgi.py code. I replaced it with the code above from the documentation. And then the 500 Error shows up. Previous code, that I didn't change in wsgi.py that works: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_wsgi_application() Below is my project.conf file <VirtualHost *:80> ServerName localhost DocumentRoot /var/www/project/mysite ServerAdmin webmaster@localhost Alias /favicon.ico /var/www/project/mysite/static/tickets/img/ibe.ico Alias /media/ /var/www/mysite/media/ Alias … -
Custom Authentication in Django with Email
i have to do this task For the current project, create the ability to log in with email or username, under these conditions, you should expand the input elements of the registration form and add the ability to log in by email, and then during the review if one of the two matches. The user name or email status should be checked and the user will be allowed to enter and i search a lot about this but i cant find them useful #viws.py from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from django.contrib.auth.forms import AuthenticationForm, UserCreationForm from django.contrib.auth.decorators import login_required def login_view(request): if not request.user.is_authenticated: if request.method == 'POST': form = AuthenticationForm(request=request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('/') form = AuthenticationForm() context = {'form': form} return render(request, 'accounts/login.html', context) else: return redirect('/') @login_required def logout_view(request): logout(request) return redirect('/') def register_view(request): if not request.user.is_authenticated: if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('/') form = UserCreationForm() return render(request, 'accounts/register.html', {"form":form}) else: return redirect('/') i dont hace a forms.py and i dont much code in models -
Tailwind/Flowbite modal hidden behind backdrop
I'm going through the same issue as this 'https://stackoverflow.com/questions/72080009/tailwindflowbite-pop-up-showing-black-screen/77008795?noredirect=1#comment135756693_77008795' developing in django: even with aria-hidden set to true it doesn't work. I'm also really confused because i'm using the same exact modal for the signup and it works perfectly with two cta buttons, the structure is the same, basically copied changing only the ids. Inspecting on the browser the backdrop that appears after i click on it is the same for both modals, i don't understand why the backdrop with z-40 is making it impossible to interact with the login that has z-50. <div id="login_modal" data-modal-backdrop="static" tabindex="-1" aria-hidden="true" class="fixed top-0 left-0 right-0 z-50 hidden w-full p-4 overflow-x-hidden overflow-y-auto md:inset-0 h-[calc(100%-1rem)] max-h-full"> <div class="relative w-full max-w-md max-h-full"> <!-- Modal content --> <div class="relative bg-darkred rounded-lg shadow"> <button id="close-login_modal" type="button" class="absolute top-3 right-2.5 text-palettewhite hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm w-8 h-8 ml-auto inline-flex justify-center items-center dark:hover:bg-gray-600 dark:hover:text-white" data-modal-hide="login_modal"> <svg class="w-3 h-3" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 14 14"> <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m1 1 6 6m0 0 6 6M7 7l6-6M7 7l-6 6"/> </svg> <span class="sr-only">Close modal</span> </button> <div class="px-6 py-6 lg:px-8"> <h3 class="mb-4 text-xl font-medium text-palettewhite">Login to our platform</h3> <form class="space-y-6" action="{% url 'home' %}" method="POST"> {% csrf_token %} <div> <label for="username" …