Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issue with @login_required function in Django
I'm receiving an error when trying to use the login_required function. I'm receiving a TemplateDoesNotExist at /accounts/login/ registration/login.html Error. While I have no directory Registration, I have my templates in a folder, templates. I have a login.html template which works fine for the login page. This is the view`I'm using the login_required function on @login_required(login_url='signin') def buy_crypto(request): if request.method == 'POST': currency = request.POST.get('currency') amount = Decimal(request.POST.get('amount')) price_per_unit = Decimal(request.POST.get('price_per_unit')) purchase = CryptoPurchase(user=request.user, currency=currency, amount=amount, price_per_unit=price_per_unit) purchase.save() return redirect('index') else: return render(request, 'buy_crypto.html') My url patterns for User Authentication are in a seperate app in the same project. This app is called accounts. Here's the accounts/urls.py file from django.urls import path from cryptoapp import views from .views import signupView, signinView, signoutView urlpatterns = [ path('create/', signupView, name='signup'), path('login/', signinView, name='signin'), path('signout/', signoutView, name='signout'), ] If you need any further code please let me know ! Any help would be greatly appreciated ! -
best realtime Web framework
Which backend framework is best suited for sending location data from mobile app to website in realtime. I am a beginner in web development and trying to build a real time system, I was told that django is good for learning curve , but node js is good for realtime system, please help me in suggesting the correct framework, -
Django QR code send inline via email is not showing in body
I am trying to send a QR Code to email and have it display inline within the email body. The email is sent successfully, The attachment currently works and displays as expected but the png within the body is showing as a ? and looks like this: In my view I have the following function defined. def send_qr_code_email(to_email, qr_code_data): # Generate QR code image qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4, ) qr.add_data(qr_code_data) qr.make(fit=True) img = qr.make_image(fill_color="black", back_color="white") # Convert image to bytes and attach it to the email message buffer = BytesIO() img.save(buffer, 'PNG') image_data = buffer.getvalue() image_filename = 'qr_code.png' data_uri = 'data:image/png;base64,' + base64.b64encode(buffer.getvalue()).decode('ascii') src = 'data:image/png;base64,{0}'.format(data_uri) email = EmailMessage( 'QR Code', render_to_string('Templates/email.html', {'qr_code_data': qr_code_data, 'src': src}), settings.DEFAULT_FROM_EMAIL, [to_email], reply_to=[settings.DEFAULT_FROM_EMAIL], ) email.content_subtype = "html" email.attach(image_filename, image_data, 'image/png') # Send the email email.send(fail_silently=False) and this is my email.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>QR Code</title> <style> .qr-code-container { display: inline-block; border: 1px solid #ccc; padding: 10px; background-color: #fff; box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.1); } .qr-code-container img { display: block; margin: 0 auto; max-width: 100%; } .qr-code-container p { margin: 10px 0; font-size: 14px; line-height: 1.5; } </style> </head> <body> <div class="qr-code-container"> <p>Here is your QR code:</p> … -
How can i use function from another function in Django views.py?
there is global parameter sentence, ascii_sentence, cearsar_sentence, caesar_shift here is my views.py def random_string(request): global sentence sentence = " ".join(random.sample(words.words(),random.randint(7,10))) cearsar_sentence = caesar_encryp(sentence) return render(request, 'caesar.html',{'sentence':sentence},{'cearsar_sentence':cearsar_sentence}) def caesar_encryp(sentence): (blah blah) return ceasar_sentence while i call caesar_encryp in random_string. somthing unknown problem occurred. when i click ramdom_string button. there's no error message. just my code script showed in web page. but when i delete all the 'cearsar' codes. i does work well. so i'm pretty sure function in function use is wrong. how can i use function caesar_encryp in random_string? i saw similar question in stackoverflow. and the answer said Django view have to need request so i've tried the bottom code def random_string(request): cearsar_sentence = caesar_encryp(request) return render(request, 'caesar.html',{'sentence':sentence},{'cearsar_sentence':cearsar_sentence}) def caesar_encryp(request): (blah blah) return ceasar_sentence but also doesn't work. please help me. -
Adding to the Django registration form confirmation of registration by mail and phone number
Good afternoon, please tell me how to add registration confirmation points to my Django registration by phone number and by mail. Code and sequence below: The essence should be as follows: Filling out the registration form => Sending the code to the mail and sending the code to the phone number => Redirecting from the registration page to the page for entering the code from the mail => If the code does not fit, redirecting to the same page for entering the code from the mail , but with an error that the code is not suitable, if the code is suitable, then redirect to the page for entering the phone number => If the code is suitable, then redirect to the main page, if not, then redirect to the page to enter the code from the phone number only with a warning that the code is not suitable views.py: from django.shortcuts import render, redirect from .forms import CustomUserCreationForm from django.contrib.auth import login, authenticate def register(request): if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect('home') else: form = CustomUserCreationForm() return render(request, 'account/registration.html', {'form': form}) models.py: from django.db import models from django.contrib.auth.models import AbstractUser … -
Django - k8s - django.db.utils.OperationalError - redis.exceptions.ConnectionError - requests.exceptions.ConnectionError
I'm running a django + postgrsq/pgbouncer + redis project on Kuerbenetes (OVH public cloud) Each on their own pod and I sometimes encounter this kind of error django.db.utils.OperationalError: could not translate host name "pgbouncer" to address: Try again redis.exceptions.ConnectionError: Error -3 connecting to redis:6379. Try again. requests.exceptions.ConnectionError: HTTPConnectionPool As if Django pod sometimes lost connection with the other pods (redis / pgbouncer or other services we use) I mainly happens if I send concurrency requests (not a lot) and it is very random Pods are declared as type: ClusterIP on the default namespace and I access them from Django using their service name I put below the config for Redis/Django-rq as an example but not sure it will help as it happens for any other services used by Django. Django settings.py RQ_QUEUES = { 'default': { 'HOST': 'redis', 'PORT': 6379, 'DB': 0, }, } redis yaml file apiVersion: v1 kind: Service metadata: name: redis labels: app: redis spec: type: ClusterIP ports: - port: 6379 targetPort: 6379 protocol: TCP name: http selector: app: redis --- apiVersion: apps/v1 kind: Deployment metadata: name: redis labels: app: redis spec: selector: matchLabels: app: redis template: metadata: labels: app: redis spec: restartPolicy: Always containers: - name: … -
Python/Django - Stream operation responses as received in one StreamingHttpResponse
I am making a number of calls to boto3 head_object operation in a for loop, after getting the list of keys from a list_objects_v2 call. I am wondering, is there anyway to return the json chunk from each head_object call as soon as I get it, as part of a single overall StreamingHttpResponse object? streamed_response = StreamingHttpResponse([]) keys = s3.list_objects_v2(Bucket=bucket) for key in keys['Contents']: metadata = s3.head_object(Bucket=bucket, Key=key['Key'])['Metadata'] # Add to streamed_response and return Is there a way to add the each metadata response to streamed_response and immediately return that chunk of json? -
using One databse in two different projects
I have create a custom admin panel in Django, where admin is able to register a new user, now I want that i should use that same database in user panel and login user by checking that user table in the database user cannot register himself from the user panel he has to send his detail to the admin and then admin will provide him login credentials i was mention that same database in my user pane setting.py I tried to makemigrations for the same but i got some error's over there -
How to set an advanced one time sms code in Django app
I have sms autentication in my Django app. I works right. But I want to use a recomendations from https://github.com/WICG/sms-one-time-codes So, instead of 4 digits code I want user to get smth like this: https://example.com, 747723, 747723 is your ExampleCo authentication code ** "https://example.com" is the origin the code is associated with, "747723" is the code, and "747723 is your ExampleCo authentication code.\n\n" is human-readable explanatory text. services.py from pyotp import HOTP from django.db.models import F from types import SimpleNamespace fake_response = SimpleNamespace(status_code=200, code=0) def send_sms(phone: int, totp_code: str) -> int: data = { "api_id": settings.SMS_API_KEY, "to": phone, "text": totp_code, "from": "my_django_app.ru", } if not settings.AUTH_CODE_TO_SMS: response = fake_response else: response = requests.post("https://sms-sender.com", data) return response.status_code def make_totp(user: User) -> str: totp = HOTP(user.otp_secret, digits=4) totp_code = totp.at(user.otp_counter) return totp_code def totp_verify(user: User, totp_code: str, verify=None) -> bool: if user: totp = HOTP(user.otp_secret, digits=4) verify = totp.verify(otp=totp_code, counter=user.otp_counter) if verify: user.otp_counter = F("otp_counter") + 1 user.save() return verify Any suggestions how to solve this problem? -
Django Ajax updated Table loosing sortable function
I'm using this plugin to make my HTML table sortable and it works great. <script src="https://www.kryogenix.org/code/browser/sorttable/sorttable.js"></script> You can call it by adding sortable in the table class <table id='myTable' class="table table-striped table-hover table-bordered fixed_header sortable"> But when I'm updating the table with AJAX after filtering, the table looses the sortable functionality. Do I have to re-import the script somewhere ? I have tried to place it in my home.html page and of course in my filter.html page which is rendered after the Ajax call. Thanks -
Django form.is_valid() False
I'm trying to create custom user authentication using any of email/phone to login. When I use email it goes fine, but when I'm trying to enter with phone number nothing happens. Error appears in views.py (form is not valid): def login_request(request): user = request.user if user.is_authenticated: return redirect("account:home") if request.method == "POST": form = AccountAuthenticationForm(request.POST) print('line 28 views', request.POST) **print('line 29 views', form.is_valid()) ** if form.is_valid(): email = request.POST['email'] print('line 31 email:', email) password = request.POST['password'] user = authenticate(username=email, password=password) #or authenticate(phone=email, password=password) if user: login(request, user) print('fine') return redirect("account:home") else: print(user, 'line38') form = AccountAuthenticationForm() return render(request, "account/login.html", {"login_form": form}) models.py class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_("email address"), unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) first_name = models.CharField(max_length=20, null=True, blank=True) last_name = models.CharField(max_length=20, null=True, blank=True) phone = PhoneNumberField(unique=True, null=True, blank=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email forms.py class AccountAuthenticationForm(forms.ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput) email = forms.CharField(label='Email or phone number') class Meta: model = CustomUser fields = ('email', 'password',) def clean(self): if self.is_valid(): email = self.cleaned_data['email'] password = self.cleaned_data['password'] print('line 48', email, password) if not authenticate(username=email, password=password): raise forms.ValidationError("Invalid login") backends.py class EmailBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): try: … -
How to cancel validation check in standard Django registration view?
Good afternoon, please tell me how to cancel the standard form validation in the Django registration view, the is_valid method is responsible for this. ` from django.shortcuts import render, redirect from .forms import CustomUserCreationForm from django.contrib.auth import login, authenticate def register(request): if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect('home') else: form = CustomUserCreationForm() return render(request, 'account/registration.html', {'form': form})` I tried to remove the condition with it, so that in any case the data would be saved, but it gives an error:Exception Type: ValueError at /account/registration/ Exception Value: The CustomUser could not be created because the data didn't validate. -
docker-compose Django to access postgresql from localhost
I've a django app running with docker-compose and want it to access postgres installed on localhost here's the steps I followed: 1- added host all all 172.17.0.1/16 md5 to pg_hba.conf 2- changed listen_addresses to * in postgresql.conf 3- changed db_host to host.docker.internal 4- in docker-compose.yml added extra_hosts to the service so it looks like this services: web: extra_hosts: - "host.docker.internal:host-gateway" 5- restarted postgresql sudo systemctl restart postgresql still getting this error could not connect to server: Connection timed out Is the server running on host "host.docker.internal" (172.17.0.1) and accepting TCP/IP connections on port 5432? what am I doing wrong? -
Django project: Spam bots spam all over my Sentry.io Account (Invalid HTTP_HOST header)
I have a django project running in production with gunicorn. It is connected to sentry.io for comfortable error logging. There are a lot of spambots causing Invalid HTTP_HOST header, because they try to access it by ip, which is not allowed by django`s ALLOWED_HOSTS setting. Those Spam Bots fill up my sentry plan limits, and after a while other errors are not logged anymore. What would be a simple and elegant solution to this? I already thought about some, but they all have caveats: Filter out requests with wrong hosts in an earlier stage, e.g. the nginx - Good idea, but I would like to be able to configure allowed hosts in django settings Catch Invalid HTTP_HOST header error in django and not send to sentry: Good idea, but then I do not have invalid http host header error handling at all in sentry I would like to log one error per host and url per day or something like that - But then I have to code a custom ratelimiter, which persists infos. Seems like a complex solution What are your thought on this. Do you have other ideas? What would be the most elegant and less comlicated solution? -
django-extensions graph_models -a -I options doesn’t work
I’m using django3 and django-extensions to do a DB schema following this instructions https://medium.com/@yathomasi1/1-using-django-extensions-to-visualize-the-database-diagram-in-django-application-c5fa7e710e16. The thing is, it works when I use all the database and specifics apps but it doesn’t when I use specific modules. How can I solve this? I’m working ond django 3.2, pygraphviz 1.10 and django_extensions 3.2.1 -
Django production sever extremely slow upload images
i have created an application in python Django where users can upload some images. MY application as localhost development work perfect and very faster. Now i want to to run as production using Nginx and gunicorn server and port forward for education reasons. My problem is if i run as productions my site has extremely slow in upload images. I don't know why is wrong and i have such a big difference on time upload,is my first time as production . is the some application development and production and i think the problem is some setting in NGINX server or GUNICORN server. I use Ubuntu jammy and not some linux server. here the settings : /etc/nginx/sites-available/myproject server { listen 0.0.0.0:80; server_name _; keepalive_timeout 65; client_max_body_size 1000M; gzip on; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_buffers 16 8k; gzip_proxied expired no-cache no-store private auth; gzip_min_length 10240; gzip_http_version 1.1; gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; gzip_disable "MSIE [1-6]\."; location /static/ { alias /home/username/PycharmProjects/myproject/static/; expires 30d; add_header Cache-Control "public"; } location /media/ { alias /home/username/PycharmProjects/myproject/myproject_app/media/; } location / { include proxy_params; proxy_pass http://unix:/home/username/PycharmProjects/myproject/myproject.sock; proxy_buffer_size 128k; proxy_buffers 4 256k; proxy_busy_buffers_size 256k; } } nginx.conf: user www-data; worker_processes auto; pid /run/nginx.pid; include … -
Django Dynamic form
Im making Django web application and i dont know how to resolve this problem. I will be very gratefull for help. I have my forms.py CHOICES =( ("1", "sys_1"), ("2", "sys_2"), ("3", "sys_3"), ("4", "sys_4"), ) #and so on, lots of elements Class ExampleForm(forms.Form): text = forms.CharField() list = forms.MultipleChoiceField(choices=CHOICES,widget=forms.CheckboxSelectMultiple) I want to achieve that if user will write something in text charfield the list should change choices content dynamically based on what was typed. Also the list must remember marked checkboxes. checkboxes(user input something in charfield -> list is changing -> user marks some checkboxes -> user delete content in the charfield -> list is changing and displaying all elements but remember marked checkboxes) -
Not able to send the data from django to html
I am developing a Django project where I have two drop downs one is for Category to select from and other is date range. Logic: If user selects the category the ,user should be able to get all relevant data where start_date and end_date is None If the user selects start date and end_date then the user should have all relevant data between the date range. I am able to create these filters and send the data for Django server and get correct results for both logic however I can render only 1st logic results for HTML and unable to send the results after date selection. Views.py def HOME(request): # Project Dropdown to webpage projects_dropdown = ['All'] + list(Project.objects.values_list('Project', flat=True)) selected_project = 'All' #fetching the value of selected dropdown from the webpage ##Start_date and end_date start_date = request.POST.get('start_date') end_date = request.POST.get('end_date') # # converting the dates to datetime objects tz = pytz.UTC if start_date: start_date = datetime.strptime(start_date, "%Y-%m-%d").replace(tzinfo=tz) if end_date: end_date = datetime.strptime(end_date, "%Y-%m-%d").replace(hour=23, minute=59, second=59, tzinfo=tz) ## getting the project selected from filter try: if request.method == "POST": selected_project = request.POST.get('projectslicer') except: pass if start_date and end_date: if selected_project == 'All': re_leads = Lead.objects.filter(lead_created_date__gte=start_date, lead_created_date__lte=end_date,Lead_Status__in=['Open', 'Qualified', 'Lost']).values('Lead_Status').annotate(total=Count('Lead_Status')) else: re_leads … -
Access unique field names
I want to access the field names when declared in Meta class : class Book(models.Model): name = CharField(...) author = CharField(...) class Meta: constraints = [ UniqueConstraint( # fields=['name', 'author'], # solution 1 Lower("name"), Lower("author"), # solution 2 name="unique__book_author", ), ] With solution 1, I access with Book._meta.constraints[0].fields => ('name', 'author'). With solution 2, Book._meta.constraints[0].fields is empty :'( Any idea ? See https://docs.djangoproject.com/en/4.1/ref/models/constraints/ -
How to pass object id to django view when handling multiple different models objects in the same view
I am trying to make web app which has dashboard on main page where user can add saved links, notes reminders and etc. I figured out how to use several forms in same view to create different model objects, but I'm not able to update those objects. What I am specificaly trying to do is to have one button form and when user click on that button (checkbox) reminder object status changes to closed. But I can't find a way to get that object ID or anything to query it in my view. I am very new to Django framework it might be something obvious, but I coudn't find any information that would help me and I tried a lot of variations to achieve this, but nothing worked so far. #models.py class Reminders(models.Model): person_id = models.ForeignKey(Person, related_name="reminder_about", null=True, blank=True, on_delete=models.CASCADE) date = models.DateTimeField(null=True) status = models.CharField(max_length=150, null=True, blank=True) note = models.CharField(max_length=150, null=True, blank=True) user_id = models.ForeignKey(Person, related_name="reminder_for", null=True, blank=True, on_delete=models.CASCADE) class Meta: verbose_name = 'Reminder' verbose_name_plural = 'Reminders' def __str__(self): return f"{self.status} {self.note}" #views.py @login_required def index(request): current_user = request.user person = Person.objects.get(user=current_user) scheduled_calls = ScheduledCalls.objects.filter(user_id=person.id).order_by("-date") reminders = Reminders.objects.filter(user_id=person.id).order_by("-date") notes = Notes.objects.filter(user_id=person.id).order_by("-date") links = SavedLinks.objects.filter(user_id = person.id) if request.method == … -
Devappserver: Attempted RPC call without active security ticket
We're in the migration process from webapp2 to the latest version of Django. We want to keep using legacy services like Appengine NDB for now before we move to the latest technologies. For running the development environment locally I am using devappserver inside a docker environment because devappserver doesn't work with python3 according to Google. My Google Cloud SDK version is: 424.0.0 The server runs, but I keep getting this error whenever I try to access a View that uses some sort of legacy service: google.appengine.runtime.apiproxy_errors.RPCFailedError: Attempted RPC call without active security ticket Complete log: The app.yaml (for deployment looks like this): runtime: python38 instance_class: F2 app_engine_apis: 'True' entrypoint: bash -c 'python3 manage.py migrate --settings=conf.settings.dev --noinput && gunicorn -b :$PORT main:app' handlers: - url: /static static_dir: static/ - url: /.* script: auto secure: always redirect_http_response_code: 301 builtins: - deferred: on env_variables: DEBUG: 'False' DB_HOST: '/cloudsql/arrivy-sandbox:us-central1:arrivy-db' DB_PORT: 5432 DB_NAME: arrivy DB_USER: postgres DB_PASSWORD: FcnJLx3tjfQM4RZVqvC9BSAUerTpsbz2aKwN8kPHdGWY7uhmDX DJANGO_SETTINGS_MODULE: conf.settings.dev main.py: from conf.wsgi import application from google.appengine.api import wrap_wsgi_app app = wrap_wsgi_app(application, use_legacy_context_mode=True, use_deferred=False) The django app works as expected when deployed to AppEngine Standard Environment. There is no error when running services inside the docker containers locally. I have tried these approaches and failed … -
How could I get metadata from my Python-Django project to implement the SSO?
I have a Python-Django project and I'm trying to integrate with a C#/.NET existing website SAML authentication, using their idp. About I absolutely need to generate a metadata file to give to whoever manages the IdP (C#/.NET website). I've been around the Internet for days but can't find anything; I tried with all libraries (pysaml2, djangosaml2, python3-saml, django-saml2-auth, etc.) but it didn't work! How can I implement it? -
django-allatuh login automatic on "/"
I have a program in DJango. I have a second program called "users". Inside I have implemented login and login with microsoft authentication. I have done this using the "allauth" library. Now I want you when accessing the page, (without having to access the "/login" page) check if you have a microsoft account. That is, when I enter the main page: "/", it takes me to the page to choose a microsoft account in the event that it has one. Without having to press any buttons. That's possible? That it automatically connects if I am connected to a Microsoft account. This is my view: def home(request): if not request.user.is_authenticated: user = authenticate(request, auth_entry='microsoft') if user is not None: login(request, user) return redirect('main_page') else: microsoft_account = SocialAccount.objects.filter(user=request.user, provider='microsoft') if microsoft_account.exists(): return redirect('main_page') return render(request, 'home.html') As you can see, the problem is that I firt see if the user is authenticated. But if it the first time the user enters, it is imposible to be autheticated. I don't know if I explained myself correctly, I want the Microsoft authentication to be automatic -
django.db.migrations.exceptions.InconsistentMigrationHistory:
I am getting this error when trying to make migrations. Migration test_1.0001_initial is applied before its dependency test_2.0016_boolean on database 'default'. I've tried python manage.py makemigrations --merge I have also tried. python manage.py migrate --fake -
Getting this error when tried to install using pip install anymail
ERROR: Could not find a version that satisfies the requirement anymail (from versions: none) ERROR: No matching distribution found for anymail Can anyone help me with this