Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I solve this error? : 'WSGIRequest' object has no attribute 'objects'
I am trying to create a web app for managing expenses for a company but I ran into a problem that I quite don't know how to work around it. The error message is 'WGSIRequest' object has no attribute 'objects'. I am new in python that's why it is stressing me out. I have linked the line that spawns the error as well as my views.py file as well as my urls.py. The error: 'WGSIRequest' object has no attribute 'objects' Line associated with error: user = request.objects.filter(email=email) My view.py file: from django.shortcuts import render, redirect from django.views import View import json from django.http import JsonResponse from django.contrib.auth.models import User from validate_email import validate_email from django.contrib import messages from django.core.mail import EmailMessage from django.contrib import auth from django.utils.encoding import force_bytes, force_str, DjangoUnicodeDecodeError from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.contrib.sites.shortcuts import get_current_site from django.urls import reverse from .utils import token_generator from django.contrib.auth.tokens import PasswordResetTokenGenerator # Create your views here. class EmailValidationView(View): def post(self, request): data=json.loads(request.body) email=data['email'] if not validate_email(email): return JsonResponse({'email_error': 'Email is invalid'}, status=400) if User.objects.filter(email=email).exists(): return JsonResponse({'email_error': 'Sorry email in use, choose another one'}, status=409) return JsonResponse({'email_valid': True}) class UsernameValidationView(View): def post(self, request): data=json.loads(request.body) username=data['username'] if not str(username).isalnum(): return JsonResponse({'username_error': … -
OperationalError at at /users/login/ no such table: auth_user when trying to login on my website
I've deployed my website using Railway. I'm pretty sure the error is because I'm switching from sqllite to postgres. settings.py import dj_database_url DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, } if 'DATABASE_URL' in os.environ: DATABASES['default'] = dj_database_url.config( conn_max_age=500, conn_health_checks=True, ) I've run makemigrations and migrate, but it doesn't fix the error. -
django foreignkey sort per user
Help me implement it. Let's say I have 3 models one user another branches and depart of branches. I need everyone to see only the depart of their branches - Create a record @login_required(login_url='my-login') def create_record(request): form = CreateRecordForm() if request.method == "POST": form = CreateRecordForm(request.POST) if form.is_valid(): form.instance.cr_user = request.user form.save() messages.success(request, "Запись созданно успешно") return redirect("dashboard") context = {'form': form} return render(request, 'tik/create-record.html', context=context) -
Django apps.get_models(): how to load models from other folders
I have the following folder structure: All models from apps/<some_app_name>/models.py are loaded OK when using apps.get_models(), but unfortunately the folders client/brand/reseller/company on the image also have a models.py file on each of them, which are not being loaded on apps.get_models() (code below): import pytest from django.apps import apps # Set managed=True for unmanaged models. !! Without this, tests will fail because tables won't be created in test db !! @pytest.fixture(autouse=True, scope="session") def __django_test_environment(django_test_environment): unmanaged_models = [m for m in apps.get_models() if not m._meta.managed] for m in unmanaged_models: m._meta.managed = True Can someone explain me how/where should I set pytest/Django to lookup for models? Using Python 3.9.18, and Django 3.2.21 Not sure if it helps on something: these 4 models inherit from Account, and that model inherit from PolymorphicMPTTModel (which allows for some pretty crazy/confusing parent-child relations). -
onnect() failed (111: Connection refused while connecting to upstream, client: 172.31.45.233, upstream: "http://127.0.0.1:8000/", host: "172.31.45.81" [closed]
My error: 2023/10/04 17:17:19 [error] 39625#39625: *19 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.45.233, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "172.31.45.81" 2023/10/04 17:17:30 [error] 39625#39625: *21 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.10.148, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "172.31.45.81" I am running a Django Project through AWS EB using websockets and am encountering this error. Please help! I've tried adding environment variables setting PORT and SERVER_PORT both to 8000. -
My script works properly on Chrome, but not on Safari
The following script is the code for a dark mode toggle on my website. I don't really know Javascript (I only know Python), so writing this code was a challenge and it might be poorly written. But what it does is it checks for a session variable "is_dark_mode" using Django Templating Language, to check if the current user has previously set his view to light or dark mode, and then it proceeds to switch the Boolean for that variable and adds or removes a "dark-mode" class to the body of my HTML (which is how I'm switching styles when in dark mode). It works fine in Chrome, but it doesn't work at all in Safari, and I don't know why. When using the JavaScript console, it throws an error: SyntaxError: Unexpected token ';' This SyntaxError is pointing to this line of code: var darkMode = ; Could someone give me a hand in figuring this out? I'm learning backend only, so I got no idea of how to solve this, and I've already tried googling it, with no success. <script> document.addEventListener("DOMContentLoaded", function () { var modeToggle = document.getElementById("modeToggle"); function setInitialDarkMode() { var darkMode = {{ request.session.is_dark_mode|default_if_none:"false"|lower }}; modeToggle.checked = darkMode; … -
Django- change password failed for a tester user. I cannot find the error
Hello user Tester cannot change the password. I used chat gpt for help, but it fails What ought I to change/correct? User logs into the My_account website and tries to change the password, but nothing happens. "With this change, the user is always returned to the "my_account" page after saving the password, regardless of whether the password was changed or not. If the password has been changed, the success message is displayed, otherwise the error message. The new password is only saved if it has been successfully changed"- this doesn't happen views.py from django.contrib import messages from django.http import HttpResponseRedirect from django.urls import reverse from django.shortcuts import render, redirect from django.views import View from django.contrib.auth.forms import PasswordChangeForm from .models import Note class MyAccountView(View): template_name = "my_account.html" def get(self, request): password_form = PasswordChangeForm(request.user) notes = Note.objects.filter(user=request.user) context = {"password_form": password_form, "notes": notes} return render(request, self.template_name, context) def post(self, request): password_form = PasswordChangeForm(request.user, request.POST) if 'change_password' in request.POST: if password_form.is_valid(): user = password_form.save() update_session_auth_hash(request, user) messages.success(request, "Successfully changed.") return redirect("my_account") else: messages.error(request, "Error changing the password. Please check your entries.") return HttpResponseRedirect(reverse("my_account")) # If the password has not been changed or the password form is invalid, # redirect the user back to … -
Setting {{ user.email }} as input value does not save Django form?
I am trying to set the default value of an input as {{ user.email }} so that the user does not have to type their email again when they are submitting a POST request. When a user signs up for an account, they use their email and I store it in a model. However, when I was testing this, I get a field error saying that the email field is required. I am printing the error in my views.py file like this: form = UserDataForm(request.POST) for field in form: print("field_error: ", field.name, field.errors) field_error: email <ul class="errorlist"><li>This field is required.</li></ul> I am setting the input value through JavaScript like so, and I am also hiding the input by setting the display to none: document.querySelector("#id_email").setAttribute("value", "{{user.email}}") document.querySelector("#id_email").value = "{{user.email}}" document.querySelector("#id_email").style.display = "none" I used inspect element and i see that the input tag shows the email in the value attribute: <input type="email" name="email" maxlength="320" required id="id_email" value="test@gmail.com" style="display: none;"> forms.py: class UserDataForm(forms.Form): email = forms.EmailField(required=True, label="Email address") # other fields models.py: class UserDataModel(models.Model): email = models.EmailField(default="", max_length=100) # other fields views.py: from .models import UserDataModel from .forms import UserDataForm def profile(request): if request.method == "POST": form = UserDataForm(request.POST) if form.is_valid(): cd … -
How to solve the Runtime.ImportModuleError: Unable to import module 'vc__handler__python': No module named 'django' error on Vercel?
I'm trying to deploy a Django Project on Vercel but I'm facing this error bellow: Runtime.ImportModuleError: Unable to import module 'vc__handler__python': No module named 'django' I've preapered my settings.py allowing vercel deployment as bellow: ALLOWED_HOSTS = ['127.0.0.1', '.vercel.app', '.now.sh'] And edit my JSON file too as bellow: { "builds": [{ "src": "ang/wsgi.py", "use": "@vercel/python", "config": { "maxLambdaSize": "15mb", "runtime": "python3.9" } }, { "src": "build.sh", "use": "@vercel/static-build", "config": { "distDir": "staticfiles" } } ], "routes": [ { "src": "/static/(.*)", "dest": "/static/$1" }, { "src": "/(.*)", "dest": "ang/wsgi.py" } ], "outputDirectory": "staticfiles" } My requirments also shows that I've Django installed asgiref==3.7.2 dj-static==0.0.6 Django==4.2.6 django-stdimage==6.0.1 Pillow==10.0.1 sqlparse==0.4.4 static3==0.7.0 typing_extensions==4.8.0 tzdata==2023.3 whitenoise==6.5.0 So does anyone knows what is causing the problem?? I've try to install whitenoise already, change folder roots and install different django modules I was expecting to fix this Runtime.ImportModuleErro -
How to retrieve all customers bookings by either their username or id. Django
I am trying to retrive all bookings made by the logged in user. I am getting the following error: Cannot assign "'leonie'": "Customer.user" must be a "User" instance. What i don't understand is how this is not an instance of the user model. Views.py from django.shortcuts import render, get_object_or_404 from .forms import CustomerForm, BookingForm from django.contrib.auth.models import User from .models import Booking, Customer # Create your views here. # https://stackoverflow.com/questions/77218397/how-to-access-instances-of-models-in-view-in-order-to-save-both-forms-at-once?noredirect=1&lq=1 def customer_booking(request): if request.method == 'POST': customer_form = CustomerForm(request.POST, prefix='customer') booking_form = BookingForm(request.POST, prefix='booking') if customer_form.is_valid() and booking_form.is_valid(): customer = customer_form.save(commit=False) customer.user = request.user.username customer.save() booking = booking_form.save(commit=False) booking.customer = customer booking.save() customer_form = CustomerForm() booking_form = BookingForm() else: customer_form = CustomerForm(prefix='customer') booking_form = BookingForm(prefix='booking') context = { 'customer_form': customer_form, 'booking_form': booking_form, } return render(request, 'booking.html', context) def display_booking(request): bookings = Booking.objects.filter(customer=request.user) context = { 'bookings': bookings, } return render(request, 'booking.html', context) models.py from django.db import models from django.contrib.auth.models import User # Create your models here. BOOKING_STATUS = ((0, 'To be confirmed'), (1, 'Confirmed'), (2, 'Declined')) class Customer(models.Model): first_name = models.CharField(max_length=80) last_name = models.CharField(max_length=80) email = models.EmailField() phone_number = models.CharField(max_length=20) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f"{self.user}" class Booking(models.Model): booking_date = models.DateField() booking_time = models.TimeField() number_attending = models.IntegerField(default=2) booking_status … -
Cookies between nginx and gunicorn with ssl and without it
Now in my django project everything is configured without Nginx. I've never used it before and I want to use it now. My cookies (sessionid) are protected and httponly. I have one self-written SSL certificate for 127.0.0.1:8000. I'm interested in how cookies will be transmitted if the connection between Nginx and the frontend is HTTPS, and between Nginx and Gunicorn is HTTP. Will Nginx decrypt them and pass them on to Django, who in turn will receive them? Is it possible to somehow use the same SSL certificate for Nginx and Gunicorn? -
Group Symbols Together during order_by
When using order_by in the Django ORM it seems that it is ignoring symbol characters in the text when sorting. For example with the folowing query set. +--------+ | name | +--------+ | 'A' | | '@B' | | 'C' | | 'D' | | '@E' | | 'F' | | '$G' | | '$H' | +--------+ When using Item.objects.all().order_by("name"), the list is returned exactly as you see above. How do i order that list where the symbols are sorted together like so: A,C,D,F,@B,@E,$G,$H -
How to add google analytics 4
I am trying to add Google Tag code in head block of Django-CMS but it ruins the django-cms admin css and tag does not work. {% load cms_tags menu_tags sekizai_tags %} {% load static %} <!DOCTYPE html> <html dir="ltr" lang="{{ LANGUAGE_CODE }}"> <head> <!-- Google tag (gtag.js) --> <script async src="https://www.googletagmanager.com/gtag/js?id=G-P1JCM2KX92"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-P1JCM2KX92'); </script> .... How can we add Google Tag to Django-CMS? Thanks -
Anchor tags not working in DJANGO project do to Javascript file
I have a project with many anchor tags and urls that connect many apps and pages. I also have a javascript file with some functions and DOM events to make somethings in my project. If I add a the script element to my project base.html (thats extended to all my html files) at the head of my base document like this it doesnt load the javascript file and it lets me use the anchor tags normal. But if I add <script **defer ** src="{% static '/js/script.js' %}"> to the element it loads the javascript file but it doesnt let me use the anchor elements. I have tried adding the javascript tag at the end of the base.html before the and it loads the javascript file but it doenst -
How to create popover survey like Hotjar using javascript on client website?
I have been using Django to create post purchase form, much like Google Form, using iframe to embed the form to the clients website. But then I saw Hotjar and how they implement their form as a popover survey. In Hotjar, after the form is created, Hotjar gives a javascript trigger that can be pasted into the clients website. I can create those stuff on my own website, but I am a bit lost on how those can be implemented on another website using javascript trigger. Does anyone have any tips on how to go on about implementing it myself? P.S. I am not interested in tracking features of Hotjar, just survey. So far I thought of creating Django templates and views to create questions and answers, and based on the inputs, then convert it into javascript and save it to Google Cloud Storage. I thought maybe I can load it on clients website using Javascript. But not sure how or whether it is even a good idea. Basically, I just want the client to paste some javascript code. And in doing so the forms (Questions, answers, and buttons) I created would appear at the bottom right corner of their … -
django.http.request.RawPostDataException on file upload
When I try to upload a file to my Django application and try to get the body of the request, I get this error. File "/docs/geon/tenv/lib/python3.10/site-packages/django/http/request.py", line 330, in body raise RawPostDataException("You cannot access body after reading from request's data stream") django.http.request.RawPostDataException: You cannot access body after reading from request's data stream Then I tried using the debugger to inspect the middleware by creating a simple middleware that does nothing and adding it to the topmost place in the list of middleware, then adding a breakpoint just after entering the process_request function. Then I inspected the 'body' attribute of the request and it is RawPostDataException("You cannot access body after reading from request's data stream") Apparently, something is modifying the request before it gets to middleware at all, and if the body is empty, it should be an empty string and not raise an error. I don't know which stack before middleware to look. I have restframework installed in app if it means something -
Asgi:Daphne Django issue in production
Hey i have error in my project its kind of wired error because the code works totally fine locally but its not working when i deploy it on Railway i installed channels[Daphne] and created web-socket and it works great but on deploy it gives this error 2023-10-04 19:10:30,487 INFO /app/.env not found - if you're not configuring your environment separately, check this. Traceback (most recent call last): File "/opt/venv/bin/daphne", line 8, in <module> sys.exit(CommandLineInterface.entrypoint()) File "/opt/venv/lib/python3.10/site-packages/daphne/cli.py", line 171, in entrypoint cls().run(sys.argv[1:]) File "/opt/venv/lib/python3.10/site-packages/daphne/cli.py", line 233, in run application = import_by_path(args.application) File "/opt/venv/lib/python3.10/site-packages/daphne/utils.py", line 12, in import_by_path target = importlib.import_module(module_path) File "/root/.nix-profile/lib/python3.10/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>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/app/./project/asgi.py", line 1, in <module> import notification.routing File "/app/notification/routing.py", line 2, in <module> from notification.consumer import NotificationConsumer File "/app/notification/consumer.py", line 7, in <module> from notification.models import Notification File "/app/notification/models.py", line 3, in <module> from posts.models import PublishedPost File "/app/posts/models.py", line 2, in <module> from django.contrib.auth.models import User File … -
Disable Shortcut:Conflicts of boilerplate with Django extension in VS Code
Tell me why we are unable to use boilerplate (!) shortcut in vs code to add html while having Django extension installed its creating conflict it disables shortcut to add html. I have to add html code manually why its happening tell me the reason and solution that I can use both on same time without any conflict and disabling. As I am a beginner in Django please do guide me. I tried to change extensions settings but unable to fix it. -
Static Files not being found
I'm having issues with serving static files to my production server. I keep getting "WARNING:django.request:Not Found: /static/admin/css/base.css" along with the other static files within my terminal upon loading the page at my domain. Here's some of my code in my settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django_extensions', 'sslserver', 'allauth', 'allauth.account', 'allauth.socialaccount', 'axes', 'rest_framework', ] ... STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') And here's my code within my httpd.conf and httpd-ssl.conf in my Apache files. Alias /static/ "C:/Users/MyUser/Desktop/MyProject/static/" <Directory "C:/Users/MyUser/Desktop/MyProject/static"> Require all granted </Directory> and in my httpd-ssl.conf: Alias /static/ "C:/Users/MyUser/Desktop/MyProject/static/" <Directory "C:/Users/MyUser/Desktop/MyProject/static"> Require all granted </Directory> <Directory "C:/Users/MyUser/Desktop/MyProject/"> Options Indexes FollowSymLinks Require all granted </Directory> I have my DEBUG = False I am also using Apache and Waitress on a Windows VM. Im running my server via: waitress-serve --listen=127.0.0.1:8000 MyProject.wsgi:application Here's my project directory: MyProject/ ├── manage.py ├── db.sqlite3 ├── static/ │ └── ... (my static files) ├── staticfiles/ │ └── ... (collected static files) └── MyProject2/ ├── settings.py ├── urls.py ├── wsgi.py └── __init__.py also heres my wsgi.py: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'HaltScanner.settings') if settings.DEBUG: application = StaticFilesHandler(get_wsgi_application()) else: application = get_wsgi_application() # Add the HaltProject directory to PYTHONPATH sys.path.append(r'C:\Users\MyUser\Desktop\MyProject') # Debugging prints print("PYTHONPATH:", sys.path) print("sys.path:", … -
React styling with variable classname
I am making a chat app and the message has a classname of the current user's username. And I want if a user send a message to appear in blue while if the other one send one to appear in red. So I wanna do something like this: {currentUser.username} { background:red } -
the notification mark shows only if i am inside notification page
this code is for navigation bar in my website. when a new notification comes the var has_new_notification will be true then the notification-mark should show in notification element in the navbar. also there is class called active that makes the element color in navbar change when i click on the element. the problem: i can only see the notification-mark on notification element when i am inside notification page. `{% load static %} .header__menuItem.active a{ background-color: #51546e; color: #fff; padding: 10px 20px; margin: -10px -20px; border-radius: 10px; } .header__menuItem.notification { position: relative; } .notification-mark { position: absolute; top: 0; right: 0; width: 10px; height: 10px; background-color: red; border-radius: 50%; } DevSearch Logo Menu <li class="header__menuItem {% if request.path == '/accounts/notofications/' %}active{% endif %} notification"> <a href="{% url 'notofications' %}">Notifications</a> {% if has_new_notification %} <span class="notification-mark"></span> {% endif %} </li> <li class="header__menuItem {% if request.user.is_authenticated and request.path == '/accounts/logout/' %}active{% endif %}"><a href="{% url 'logout' %}" >Logout</a></li> {% else %} <li class="header__menuItem {% if request.path == '/accounts/login/' %}active{% endif %}"><a href="{% url 'login' %}" >Login/Sign Up</a></li> {% endif %} </ul> var lis = document.querySelectorAll('.header__menu li'); for (var i = 0; i ` i tried removing class: notification and only having class: notification-mark … -
Django Q sends many emails instead of once a day
I wrote a code that sends a letter once a day def send_statistics_email(): statistics = StatisticsNewletter.objects.all() message = "Статистика отправленных сообщений:\n\n" for stat in statistics: message += str(stat) + "\n" subject = "Статистика отправленных сообщений" print('Letter sent') send_mail(subject, message, settings.EMAIL_HOST_USER, [settings.RECIPIENT_ADDRESS]) schedule('notifications.views.send_statistics_email',schedule_type=Schedule.DAILY) Here's the loggi 20:35:16 [Q] INFO Process-1 created a task from schedule [52] 20:35:16 [Q] INFO Enqueued 59 20:35:16 [Q] INFO Process-1 created a task from schedule [53] 20:35:16 [Q] INFO Enqueued 60 20:35:16 [Q] INFO Process-1 created a task from schedule [54] 20:35:16 [Q] INFO Enqueued 61 20:35:16 [Q] INFO Process-1 created a task from schedule [55] 20:35:17 [Q] INFO Process-1:1 processing [snake-rugby-fish-salami] Letter sent 20:35:18 [Q] INFO Process-1:1 processing [eleven-blossom-south-fish] Letter sent 20:35:18 [Q] INFO Processed [snake-rugby-fish-salami] 20:35:20 [Q] INFO Process-1:1 processing [sodium-item-quiet-blossom] Letter sent 20:35:20 [Q] INFO Processed [eleven-blossom-south-fish] 20:35:21 [Q] INFO Process-1:1 processing [mobile-quiet-early-eleven] Letter sent 20:35:21 [Q] INFO Processed [sodium-item-quiet-blossom] 20:35:22 [Q] INFO Process-1:1 processing [robin-spring-fanta-utah] Letter sent 20:35:22 [Q] INFO Processed [mobile-quiet-early-eleven] 20:35:23 [Q] INFO Process-1:1 processing [artist-mexico-india-muppet] Letter sent 20:35:24 [Q] INFO Processed [robin-spring-fanta-utah] 20:35:25 [Q] INFO Process-1:1 processing [bulldog-angel-aspen-hot] Letter sent 20:35:25 [Q] INFO Processed [artist-mexico-india-muppet] I thought it was a matter of workers, although it costs 1 Q_CLUSTER = … -
Doctor Appointment Booking Using Django Forms
I am new to Django. I was trying to built a basic Dentist website which can be used by Patients for booking appointment, as a practice project. The problem I am facing is that I am unable to show available time slots dynamically, to prevent duplicate bookings. The time slot field comes up blank. I tried building logic in the constructor of the Django form itself, so that only available time slots are shown when a user selects a date. The Django form is: `from django import forms from django.forms.widgets import DateInput from .models import Appointment class DatePickerInput(DateInput): def __init__(self, *args, **kwargs): attrs = kwargs.get('attrs', {}) attrs.update({'data-provide': 'datepicker','data-date-start-date': '0d'}) kwargs['attrs'] = attrs super().__init__(*args, **kwargs) class AppointmentForm(forms.Form): first_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control ', 'placeholder': 'First Name'})) last_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control ', 'placeholder': 'Last Name'})) age = forms.IntegerField(widget=forms.NumberInput(attrs={'class': 'form-control ', 'placeholder': 'Age'})) date = forms.DateField( widget=DatePickerInput( attrs={'class': 'form-control datepicker px-2', 'placeholder': 'Date of visit'} ) ) time_slot = forms.ChoiceField(choices=[('', 'Select Time Slot')] + [(option, option) for option in [ '09:00 AM', '10:00 AM', '11:00 AM', '12:00 PM', '02:00 PM', '03:00 PM', '04:00 PM', '05:00 PM', '06:00 PM', '07:00 PM', ]], widget=forms.Select(attrs={'class': 'form-control'})) contact_number = forms.CharField(max_length=15, widget=forms.TextInput(attrs={'class': 'form-control ', 'placeholder': 'Contact Number'})) … -
Bokeh YearsTicker and still month on the ticker sometimes
I am using Bokeh for some charts in a Django project. For instance: [![This one is fine, showing YYYY on the x axis.][1] However, when I restrict the period of time to display (thanks to a DateRangeSlider), years are then displayed as "1/YYYY" [![This one is bad][2]][2] Axis are defined as follows: plot.yaxis.formatter = NumeralTickFormatter(format="€0,0") plot.xaxis[0].formatter = DatetimeTickFormatter(years="%Y") plot.xaxis[0].ticker = YearsTicker() Has anyone a clue of how to always have tickers as YYYY? Thanks in advance Richard [1]: https://i.stack.imgur.com/u9vq4.png [2]: https://i.stack.imgur.com/K9CBp.png -
python-redsys Redirect the user-agent with post method
i use python-redsys : https://pypi.org/project/python-redsys/ I'm stuck at the step 4. Communication step This is my view : @login_required def redsys_start(request): secret_key = DS_SECRET_KEY client = RedirectClient(secret_key) parameters = { "merchant_code": DS_MERCHANT_MERCHANTCODE, "terminal": DS_MERCHANT_TERMINAL, "transaction_type": STANDARD_PAYMENT, "currency": EUR, "order": "000000001", "amount": D("10.56489").quantize(D(".01"), ROUND_HALF_UP), "merchant_data": "test merchant data", "merchant_name": "Example Commerce", "titular": "Example Ltd.", "product_description": "Products of Example Commerce", "merchant_url": reverse('front:shop_cart_payment_callback'), } args = client.prepare_request(parameters) print(f"args = {args}") context = {'args': args, 'BANK_PAIEMENT_URL': BANK_PAIEMENT_URL} # STEP 3 args = client.prepare_request(parameters) What i have to do after that fo redirect my customer to the red sys payement system ? If i try to redirect it with parameters redsys refuse because it is with get method If i try to make a form with args redsys give me an error SIS0431 (json Ds_MerchantParameters issue) That is wahat the doc say : 4. Communication step Redirect the user-agent to the corresponding Redsys' endpoint using the post parameters given in the previous step. After the payment process is finished, Redsys will respond making a request to the merchant_url defined in step 2. 5. Create and check the response Create the response object using the received parameters from Redsys. The method create_response() throws a ValueError in …