Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django allauth with custom redirect Adapter ignoring "?next" parameter
I am using Django 3.2 and django-allauth 0.44 I have a custom adapter that redirects a user to their profile page upon login - however, I also want to be able to use a ?next=/some/url/ so that a user is redirected to that url if there is a next parameter in the GET arguments. This is my custom Adapter: class MyAccountAdapter(DefaultAccountAdapter): def get_login_redirect_url(self, request): print(f"GET request dict is {request.GET}") return reverse('profile', kwargs={'username': request.user.username}) I suspect that I have to modify my custom adapter, so that it checks for a 'next' GET parameter BEFORE going to the profile page. However, I found to my surprise that it seems: I can't set a breakpoint in the adaptor (it is ignored) If I deliberately introduce an error in the adaptor (e.g. print(request.GET['hello']) ) the code runs fines and redirects to the profile page without throwing an exception How can I use ?next=/some/url with django-allauth whilst also using a custom adaptor? -
The google-one-tap does't work on Django latest version
In my project, the google-one-tap does work fine in Django<=3.0 version, but it doesn't work in Django>=3.1. It gives me this error. [GSI_LOGGER]: The given origin is not allowed for the given client ID. I need it does work on Django==3.2.7. I need your help urgently. Thank you. -
Using HTML and Python together
I need some general python/web development help. Me and my friend know some Python and HTML and want to make a simple test website to practice with some text and buttons, but we don't how to make python detect the button press and run code then display text. I don't even know where to start with this? -
Register form in Django
I am noob to django programming.I want to create register form.I get error NoReverseMatch at / Reverse for 'register' with no arguments not found. 1 pattern(s) tried: ['(?P<register_id>[^/]+)/$'].Please help me. views.py def register(request): if request.method == "POST": user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): new_user = user_form.save(commit=False) new_user.set_pasword =(user_form.cleaned_data['Password']) new_user.save() return render(request, 'main/account/register_done.html', {'new_user': new_user}) else: user_form = UserRegistrationForm() return render(request, "main/account/register.html", {'user_form': user_form}) url.py path("<int:register>/",views.register, name='register'), forms.py from django.contrib.auth.models import User from django import forms from django.forms import widgets class UserRegistrationForm(forms.ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Repeat password', widget=forms.PasswordInput) class Meta(): model = User fields = {"Username", "email", "Name", "SurName"} def clean_password2(self): cd =self.cleaned_data if cd['password'] != ["password2"]: raise forms.ValidationError("Password dont match") return cd["password2"] base.html <a class="me-3 py-2 text-dark text-decoration-none" method="POST" href="{% url 'register' %}">Регистрация</a> -
Invalid section header '[Socket]ListenStream=/run/gunicorn.sock'
I am trying to deploy, a Django app on production mode using Nginx and Gunicorn, on an ec2 linux instance. I created a gunicorn.socket file in the path /etc/systemd/system/gunicorn.socket: It's contents are: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target Furthermore I created a service file , in the path /etc/systemd/system/gunicorn.service Its contents are: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=ec2-user Group=www-data WorkingDirectory=/home/ec2-user/buisness ExecStart=/home/ec2-user/.local/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock buisness.wsgi:application [Install] WantedBy=multi-user.target I then tried to start and enable gunicorn socket: sudo systemctl start gunicorn.socket but I got the error, Failed to start gunicorn.socket: Unit is not loaded properly: Bad message. When I checked the error logs, using, systemctl status gunicorn.socket , this is wat I got: ● gunicorn.socket - gunicorn socket Loaded: error (Reason: Bad message) Active: inactive (dead) Sep 06 19:13:52 ip.compute.internal systemd[1]: [/etc/systemd/system/gunicorn.socket:3] Invalid section header '[Socket]ListenStream=/run/gunicorn.sock' Sep 06 19:13:52 ip.compute.internal systemd[1]: [/etc/systemd/system/gunicorn.socket:3] Invalid section header '[Socket]ListenStream=/run/gunicorn.sock' Sep 06 19:14:15 ip.compute.internal systemd[1]: [/etc/systemd/system/gunicorn.socket:3] Invalid section header '[Socket]ListenStream=/run/gunicorn.sock' Sep 06 19:14:27 ip.compute.internal systemd[1]: [/etc/systemd/system/gunicorn.socket:3] Invalid section header '[Socket]ListenStream=/run/gunicorn.sock' Sep 06 19:26:15 ip.compute.internal systemd[1]: [/etc/systemd/system/gunicorn.socket:3] Invalid section header '[Socket]ListenStream=/run/gunicorn.sock' Sep 06 19:26:26 ip.compute.internal systemd[1]: [/etc/systemd/system/gunicorn.socket:3] Invalid section header '[Socket]ListenStream=/run/gunicorn.sock' Sep 06 19:56:22 ip.compute.internal systemd[1]: [/etc/systemd/system/gunicorn.socket:3] Invalid section header '[Socket]ListenStream=/run/gunicorn.sock' … -
Abstract User django create different table but it is not show in db
1st Problem : i have already running django-oscar app ,now i have to convert it into restapi app so i just create User using from oscar.apps.customer.abstract_models import AbstractUser then it was giving me .0001 initial migrations error ,then i deleted all migrations folder from oscar sitepackage and use python ./manage.py makemigrations and the migrate command ,every thing was ok until i found that when i open from my local server it show user table inside the Authentication(my custom app) but when same app use though from server it wad inside authentication and autherization table and work normally,then i search my authentication table in side my db it was not showing ,i am confuse if there is no authentication table then how i get user inside authentication table and if it is created why it is not showing inside db. 2nd : in my case i have already existing and live application based on django-oscar ,now i want to use jwt token for authentication ,what should i do ? thanks in advance and all above things happen on my testing server but if it will success than it will replicate on production server. -
how to use django related_name
I have to models named Meeting and MeetingMembers like this : class Meeting(models.Model): title = models.CharField(max_length=255) description = models.TextField() class MeetingMember(models.Model): CHOICES = ( ("A", "Accepted"), ("R", "Rejected"), ("I", "Invited" ), ("H", "Host")) status = models.CharField(max_length=9, choices=CHOICES, default="I") meeting = models.ForeignKey(Meeting, on_delete=models.CASCADE, related_name="members") email = models.EmailField(blank=True) i need to write a query that first gets all the records in MeetingMeember models which belongs to current logged in user like this : meetingmembers = MeetingMember.objects.filter(email = requets.user.email) then i need to the get all the info from the meetings belongs to the meetingmember(the second queryset should be Meeting object) i have studied about related_name but still can't figure out how can i write this. -
send django logs to graylog
I wrote this configuration in settings.py, but when DEBUG=False some logs are sent to the greylog and some (errors) appear in the console, what is wrong with this variant? I need all logs to be sent to graylog if debug=false LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'formatters': { "json": { '()': 'dynamic_tests.utils.CustomisedJSONFormatter', 'format': '%(asctime)s %(name)s %(levelname)s %(message)s' } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, 'graypy': { 'class': 'graypy.GELFTCPHandler', 'filters': ['require_debug_false'], 'formatter': 'json', 'host': GRAYLOG_HOST, 'port': GRAYLOG_PORT, 'level': 'INFO' }, }, 'loggers': { 'django': { 'handlers': ['console', 'graypy'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), 'propagate': False, }, }, } -
How to limit the user upto only three wrong otp entries
I am making my user enter an otp that he recieves in his email. But somehow I am unable to make the loop that will restrict him to enter the wrong otp only 3 times. If he enters the otp wrong for the third time his username will be deleted. this is the code that I wrote def registerpage(request): if request.method == 'POST': get_otp = request.POST.get('otp') if get_otp: get_user= request.POST.get('user') user = User.objects.get(username=get_user) if int(get_otp) == UserOtp.objects.filter(user= user).last().otp: user.is_active = True user.save() messages.success(request,'Login to complete the registration process.') return redirect('login') else: messages.error(request, f'OTP entered is wrong') return render(request, 'register.html', {'otp': True, 'user': user}) first_name = request.POST['first_name'] username = request.POST['email'] password1= request.POST['password'] password2= request.POST['con_password'] email= request.POST['email'] last_name= request.POST['join_as'] if password1==password2: if User.objects.filter(username=username).exists(): messages.info(request, 'UserID already exists') return redirect('register') elif User.objects.filter(email=email).exists(): messages.info(request, 'Email already exists') return redirect('register') else: user=User.objects.create_user(username= username.lower(), password= password1, email= email.lower(), first_name= first_name.upper(), last_name=last_name) user.is_active = False user.save() user_otp = random.randint(100000, 999999) UserOtp.objects.create(user = user, otp = user_otp) mess = f"Hello, {user.first_name}, \nYour OTP is {user_otp}\n Thanks!" send_mail( "Welcome to Solve Litigation - Verify your Email", #subject mess, #message settings.EMAIL_HOST_USER, # sender [user.email], #reciever fail_silently= False ) return render(request, 'register.html', {'otp': True, 'user': user}) else: messages.info(request, 'Password and Confirm … -
ModuleNotFoundError: No module named 'Prueba3'
Para verificar conexion a una base de datos de Maria DB intento ejecutar en la Terminal de Visual Studio Code el archivo pruebadb.py que se encuentra en la carpeta con nombre Prueba3 (carpeta creada por defecto en la creacion del proyecto y que lleva el mismo nombre de este), pero me sale el error ModuleNotFoundError: No module named 'Prueba3' Codigo del archivo import pymysql from django.conf import settings conexion=pymysql.connect(DATABASES, 'hotelsys_1001') cursor = conexion.cursor() cursor.execute("INSERT INTO ro_rooms(number,id_ad_rooms_type,id_ad_rooms_status) VALUES(1020,1,1)") conexion.commit() print ("Registro almacenado exitosamente") conexion.close() Este es el mensaje de error en consola PS D:\Proyectos\Prueba3\prueba3> py pruebabd.py Traceback (most recent call last): File "D:\Proyectos\Prueba3\prueba3\pruebabd.py", line 1, in from Prueba3.settings import DATABASES ModuleNotFoundError: No module named 'Prueba3' Arbol del proyecto enter image description here -
how to filter field values based on other field values in Django
Let us consider my models.py as class ItemsInvoices(models.Model): RESERVED = 1 NOT_RESERVED = 2 ACCEPTED_BY_CUSTOMER = 3 PO_OR_DEPOSIT_RECEIVED = 4 DELIVERY_SET = 5 NOT_READY = 6 DELIVERED = 7 ORDER_STATUS = ( (RESERVED, 'Reserved'), (NOT_RESERVED, 'NOT Reserved'), (PO_OR_DEPOSIT_RECEIVED, 'Accepted by customer'), (PO_OR_DEPOSIT_RECEIVED, 'PO or deposit received'), (DELIVERY_SET, 'Delivery set'), (NOT_READY, 'Not ready'), (DELIVERED, 'Delivered'), ) invoice_number = models.IntegerField(blank=True, null=True) order_status = models.IntegerField(default=RESERVED, choices=ORDER_STATUS) class ItemsAddedInvoice(models.Model): item_invoice = models.ForeignKey(ItemsInvoices) class StockMovements(models.Model): item_added_invoice = models.ForeignKey(ItemsAddedInvoice, blank=True, null=True) sales_group_id = models.IntegerField(blank=True, null=True) Here based on my sales_group_id i need to filter the ItemsInvoices table items whose order_status is set to RESERVED.(Here we need to filter based on sales_group_id because for each sales_group_id we might have multiple item_added_invoice_id ) For example let us consider my database table for StockMovements as: item_added_invoice_id | sales_group_id 2206 | 1 2207 | 1 2208 | 2 2209 | 3 2210 | 4 2211 | 4 2212 | 4 2213 | 5 for ItemsAddedInvoice id | item_invoice_id 2206 | 1236 2207 | 1236 2208 | 1236 2209 | 1236 2210 | 1236 2211 | 1241 2212 | 1241 2213 | 1242 for ItemsInvoices id | order_status 1236 | 1 1241 | 2 1241 | 1 And finally in a … -
How to perform better filtering in django admin?
I have this filtering applied in my admin. But there are around 200 and much more unique id which is getting displayed on the right. How can I limit them? Is there are a better way to do this? @admin.register(Model) class Model(admin.ModelAdmin): list_filter = ['my_unique_id'] Screenshot of the admin -
Traceback (most recent call last): AttributeError: 'NoneType' object has no attribute 'Command'
When I run the code it shows me this error Traceback (most recent call last): File "E:\DJANGO-CRM-NEW\Django-CRM\manage.py", line 24, in <module> execute_from_command_line(sys.argv) File "C:\Users\iamra\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 400, in execute_from_command_line utility.execute() File "C:\Users\iamra\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\iamra\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 244, in fetch_command klass = load_command_class(app_name, subcommand) File "C:\Users\iamra\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 38, in load_command_class return module.Command() AttributeError: 'NoneType' object has no attribute 'Command' PS E:\DJANGO-CRM-NEW\Django-CRM> py manage.py runserver Traceback (most recent call last): File "E:\DJANGO-CRM-NEW\Django-CRM\manage.py", line 24, in <module> execute_from_command_line(sys.argv) File "C:\Users\iamra\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 400, in execute_from_command_line utility.execute() File "C:\Users\iamra\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\iamra\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 244, in fetch_command klass = load_command_class(app_name, subcommand) File "C:\Users\iamra\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 38, in load_command_class return module.Command() AttributeError: 'NoneType' object has no attribute 'Command' -
Django nested forms
I have trouble figuring out how to create nested forms. I have two models: Poll and Question (foreign key for Poll is inside Question model). I want it to be possible to add several questions for the poll dynamically inside one form. I've already tried making it work with inlineform_factory, but found troubles saving the form. Right now I have overcomplicated code that throws MultiValueDictError after saving the poll for the second time. I thought maybe there is some other way. Here's my code models.py class Question(models.Model): type_choices = ( ('text', 'Текстовый'), ('integer', 'Числовой'), ) type = models.CharField(verbose_name=u'Тип вопроса', choices=type_choices, max_length=70) text = models.CharField(verbose_name=u'Текст вопроса', max_length=255) poll = models.ForeignKey('Poll', on_delete=models.CASCADE, related_name='questions') class Poll(BaseFields): objects = models.Manager() published = PublishedManager() title = models.CharField(verbose_name=u'Заголовок', max_length=70) date_from = models.DateTimeField(u'Дата начала') date_to = models.DateTimeField(u'Дата окончания') status = models.IntegerField(choices=Status.choices, default=0) def status_name(self): return dict(Status.choices).get(self.status) def update_url(self): return reverse('poll_update', args=(self.id, )) forms.py QuestionInlineFormSet = inlineformset_factory(Poll, Question, extra=1, can_delete=False, fields=('type', 'text', 'poll'), widgets={ 'type': w.Select(attrs={'class': 'form-control'}), 'text': w.TextInput(attrs={'class': 'form-control'}), }) class PollForm(CommonForm): class Meta(CommonForm.Meta): model = Poll views.py class Create(BaseCreateView): template_name = 'back/poll/poll.html' page_title = 'Создание опроса' model = Poll form_class = PollForm def form_valid(self, form): result = super(Create, self).form_valid(form) questions_formset = QuestionInlineFormSet(data=form.data, instance=self.object, prefix='questions_formset') if questions_formset.is_valid(): … -
I'm trying to do remember me feature at login page using django built-in auth view
from django.contrib.auth.views import LoginView from django.contrib.auth.forms import AuthenticationForm class MyLoginView(LoginView): def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['request'] = self.request # print(self.get_initial(),'--------1') return kwargs def get_form_class(self): if self.request.POST: if self.request.POST.get('remember'): self.request.session['usernameS'] = self.request.POST['username'] self.request.session['passwordS'] = self.request.POST['password'] self.request.session['remember'] = True self.initial = { 'username':self.request.session.get('usernameS'), 'password':self.request.session.get('passwordS'), 'remember':self.request.session.get('remember') } print(self.initial) return self.authentication_form or self.form_class But whenever I logged out it's not showing initial values### -
Django JWT authentication doesn't work in browser?
I'm trying to do django authentication with JWT in my django+react app. I'm using part 1 of this tutorial: https://hackernoon.com/110percent-complete-jwt-authentication-with-django-and-react-2020-iejq34ta Everything works fine when I use cURL in terminal to get access to my API, but when I run server in my browser I'm still getting What does this behaviour mean? -
Creating annotation based on subquery with parameters
I have two models in my app, Event and Registration, with the most important fields below: class Event(models.Model): ... capacity = models.IntegerField() ... class Registration(models.Model): timestamp = models.DateTimeField(auto_now_add=True) event = models.ForeignKey(Event, on_delete=models.CASCADE) uses_bus = models.BooleanField(default=False) is_vegan = models.BooleanField(default=False) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=None) Now, in either a field or in the admin, I am trying to get the number of registrations where the user has marked uses_bus and the number of registrations where the user has marked is_vegan. This could be something like this: class EventAdmin(admin.ModelAdmin): list_display = ('title', 'date', 'nr_registrations', 'nr_bus') inlines = [RegistrationInline] def get_queryset(self, request): queryset = super(EventAdmin, self).get_queryset(request) return queryset.annotate( nr_registrations = Count('registration'), nr_bus = Count('registration', filter=Q(registration__uses_bus=True)), nr_vegan = Count('registration', filter=Q(registration__is_vegan=True)), ) def nr_registrations(self, obj): return obj.nr_registrations def nr_bus(self, obj): return obj.nr_bus def nr_vegan(self, obj): return obj.nr_vegan but this obviously finds the total number of bus registrations, not the number of bus registrations for the ones that can actually attend the event because of the capacity constraints. In SQL I would solve this like this: SELECT SUM(uses_bus) FROM (SELECT CAST(uses_bus AS INTEGER) FROM events_registration WHERE event_id = *event id* ORDER BY id LIMIT *capacity*) AS a but I can't do this, because even if I … -
how to stop django autoreload without comman line argumer "--noreload"
I have developer a django app with the apscheduler and the scheduler runs twice whenever I don't use the "--noreload" command line argument with it. It was fine until I had it running on my local machine but after running it in the cpanel I don't understand how to stop the autoreloader since I can't enter a command line argument there. Please let me know how i can stop this from happening. -
I can't import JSONfield in Django==3.0
I was using Django==3.2.7 in my project, but I installed 3.0 due to some reason. But I can't import the JSONField from django.db.models. Here is the error message. from django.db.models import JSONField ImportError: cannot import name 'JSONField' from 'django.db.models' (/home/userstar713/workspace/weini/hotel_booking/mobytrip-hotelbeds/hotel_booking_backend/venv/lib/python3.8/site-packages/django/db/models/__init__.py) Please give me a suggestion. Thank you. -
Docker ModuleNotFoundError: No module named 'boto3'
I'm trying to make a web app using django and in views.py file I added imort boto3 . it worked perfectly when i tried it without docker but now i get this error: ModuleNotFoundError: No module named 'boto3' so here is my dockerfile FROM python:3 ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY ./requirements.txt /app/requirements.txt RUN pip install -r requirements.txt RUN pip install boto3 -t . COPY . /app/ ADD . /app ENV PYTHONPATH /app CMD [ "python", "/app/greet/views.py" ] and this is my docker-compose.yml file version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/app ports: - "8000:8000" -
How to send httponly cookie with axios?
I'm using a django backend, and a CRAO frontend. I saved the jwt refresh token as a httponly cookie: document.cookie = `refresh=${refresh_token}; SameSite=Strict; Path=/api/token/refresh; HttpOnly`; Then to refresh the access token, I'm sending an axios request: const response = await axios.post('/api/token/refresh/', { withCredentials: true }); But, in this case, the originally saved cookies don't get sent by axios. However, on removing the httponly attribute, the cookies do get sent, and everything works fine. -
How to connect a payment service to a Django/Flask registration process? [closed]
How do i connect a registration form which uses Django or flask with a payment service like PayPal? And what tools could be used instead to simplify the process in view of performance and security? -
How to use helios-client python module?
Now I want to use Python helios-client module. https://snyk.io/advisor/python/helios-client this is url. I am using Django as a backend. But I am not sure how to use this module. For example, what method should I use if I want to search similar songs. https://heliosmusic.io/api.html#operation/getSongsByReference here is their API document. Please give me your hands. Thanks. -
how to allow web file content update using django supervisor nginx and gunicorn
I am using django inside of ubuntu os and connected it to supervisor, nginx, gunicorn with following config supervisor [program:gunicorn] directory=/home/ubuntu/test_app/backend command=/home/ubuntu/test_app/env/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/test_app/backend/app.sock backend.wsgi:application autostart=true autorestart=true stderr_logfile=/var/log/gunicorn/gunicorn.err.log stdout_logfile=/var/log/gunicorn/gunicorn.out.log [group:guni] programs:gunicorn then i created a sym-link between sites-availabes with site-enabled nginx server { listen 80; server_name EC2Endpoint; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/test_app/backend/app.sock; } location /static { autoindex on; alias /home/ubuntu/test_app/backend/static; } } also, i enabled firewall with firewall sudo ufw allow 80 sudo ufw allow 22 sudo ufw enable now everything work fine except whenever i change a file in the django application, no matter how much i try to reload, restart nginx or supervisor, i cannot see the result of the changes applied. I read in a similar post that i must restart gunicorn but when i do sudo service gunicorn restart i get the error Failed to restart gunicorn.service: Unit gunicorn.service not found. Again from the same post i read that i must go in /etc/systemd/system then create a gunicorn.service file, which i did:` cd /etc/systemd/system sudo touch gunicorn.service then when i do : sudo systemctl enable gunicorn.service i get: Failed to enable unit: Unit file /etc/systemd/system/gunicorn.service is masked. to try to solve it: … -
I'm trying to display a single post in Django but I'm getting: Server Error(500)
I'm using Django to display my post models. When I try to display multiple posts, it works but a single post isn't working for me. I'm not really sure why. Here is what I did: views.py def post(request, pk): post = Post.object.get(id = pk) context = {'post': post} return render(request, 'base/post.html', context) urls.py urlpatterns = [ path('', views.home, name="home"), path('posts/', views.posts, name='posts'), path('post/<str:pk>/', views.post, name='post'),] post.html <h3>{{post.headline}}</h3> <h4>{{post.sub_headline}}</h4> <p>{{post.body|linebreaks}}</p> Edit: Adding my Post model class Post(models.Model): headline = models.CharField(max_length=200) sub_headline = models.CharField(max_length=200, null=True, blank=True) # thumbnail = body = models.TextField(null=True, blank=True) created = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) featured = models.BooleanField(default=False) tags = models.ManyToManyField(Tag, null=True) # slug def __str__(self): return self.headline