Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
deploying Django project on AWS lambda without using Zappa [closed]
I have created my complete django app and I want to deploy it on lambda . I am not willing to deploy via zappa . I will have my zip generated of the project using zappa and I want to put this in another bucket in AWS but this time I dont want to use zappa as it will not give me control to certain properties if any i want in future. -
Is there anyone can help me with a task of Django [closed]
Now I need to implement a project of Django (add a new tab in company website). Can anyone help me to look into it together, to help me with outline the step? Since I am totally new beginner and I feel a little confused about this. I can share the screen to express the problem. Thank you so much. -
Template Tag - Get class variables
I need to get information in template tag from a custom class This is the class class EmpleadoSiradig: def __init__(self, cuit, nro_presentacion, fecha, deducciones={}, cargasFamilia={}, ganLiqOtrosEmpEnt={}, retPerPagos={}): self.cuit = cuit self.nro_presentacion = nro_presentacion self.fecha = fecha self.deducciones = deducciones self.cargasFamilia = cargasFamilia self.ganLiqOtrosEmpEnt = ganLiqOtrosEmpEnt self.retPerPagos = retPerPagos def get_cuit(self): return self.cuit Views @login_required def archivo_solo_view(request, slug): dd = os.path.join(get_carpeta(), slug) siradig_empleado = formulas.leeXML3(dd) context = { 'siradigEmpleado': siradig_empleado, } return render(request, 'reader/soloxml2.html', context) HTML {% block title %} Siradig Individual - CUIT: {{ siradigEmpleado.cuit }}{% endblock title%} "siradig_empleado" is an EmpleadoSiradig object type, but I'm not getting a result in {{ siradigEmpleado.cuit }}. Thanks in advance. -
How to set is_staff field to False when user is created by logging in from google using alluth package
I am building a django website and I wanted to know how can I set is_staff of my custom user model to false when some user logs in from their google account. When someone logs in from their email and password their is_staff is set to false(implemented by me), but I can't find nor figure out a way to do so when someone logs in from their google account. I am using allauth package for google login. Here is my models.py for accounts app models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager # Custom User Manager class CustomUserManager(BaseUserManager): def _create_user(self, email, password, first_name, last_name=None, **extra_fields): if (not email): raise ValueError("Email Must Be Provided") if (not password): raise ValueError("Password is not Provided") user = self.model( email=self.normalize_email(email), first_name=first_name, last_name=last_name, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, first_name, last_name=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_active', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, first_name, last_name, **extra_fields) def create_superuser(self, email, password, first_name, last_name=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_active', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, first_name, last_name, **extra_fields) # Custom user Model class User(AbstractBaseUser, … -
Container commands for Elastic Beanstalk
I'm upgrading to Linux 2 on Elastic Beanstalk and I'm having trouble with command 02. commands 01 and 03 are confirmed to be working. when 02 is introduced, the deployment fails. container_commands: 01_migrate: command: "source /var/app/venv/*/bin/activate && python3 myapp/manage.py migrate --noinput" leader_only: true 02_makesuper: command: "python3 myapp/manage.py makesuper" leader_only: true 03_collectstatic: command: "source /var/app/venv/*/bin/activate && python3 myapp/manage.py collectstatic --noinput" leader_only: true the makesuper.py file exists within the following path myapp/useraccounts/management/commands/makesuper.py Under linux 1, the following command worked 02_makesuper: command: "python3.6 myapp/manage.py makesuper" leader_only: true Thanks! -
How to apply filter on django ManyToManyField so that multiple value of the field follow the condition?
class Publication(models.Model): title = models.CharField(max_length=30) class Article(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField(Publication) p1 = Publication.objects.create(title='The Python Journal') p2 = Publication.objects.create(title='Science News') p3 = Publication.objects.create(title='Science Weekly') I want to filter articles, published in both p1 and p3. They might or might not publish in other publications but they must have to publish in p1 and p3. -
Django- HTTP status code must be an integer
I have error for pagination view.py def ShowAll(request): s = request.GET.get('s') products = Domains.objects.all() paginator=Paginator(products,2) # page_num=request.GET.get('page',1) # products=paginator.page(page_num) if s: products = products.filter(Q(name__icontains=s) | Q(description__icontains=s)) serializer = DomainsSerializers(products, many=True) return Response(serializer.data,{'paginator':paginator}) what i do? -
Django does not display errors from the custom validator, and instead resets the form
I recently started learning django and can't solve one problem. I created my validator for the form, but instead of showing an error window, it just resets the form. Here is the code models.py: from django.db import models from django.urls import reverse_lazy from django.core.exceptions import ValidationError class News(models.Model): title = models.CharField(max_length=150, verbose_name='Title') content = models.TextField(blank=True, verbose_name='Content') created_at = models.DateTimeField(auto_now_add=True, verbose_name='Date of publication') updated_at = models.DateTimeField(auto_now=True, verbose_name='Update') photo = models.ImageField(upload_to='photos/%Y%m/%d/', verbose_name='Photo', blank=True) is_published = models.BooleanField(default=True, verbose_name='Is_published ') category = models.ForeignKey('Category', on_delete=models.PROTECT, null=True, verbose_name='Category') def get_absolute_url(self): return reverse_lazy('read', kwargs={'news_id' : self.pk}) def __str__(self): return self.title class Meta: verbose_name = 'new' verbose_name_plural = 'news' ordering = ['-created_at', 'title'] class Category(models.Model): title = models.CharField(max_length=150, db_index=True, verbose_name='Title of category') def get_absolute_url(self): return reverse_lazy('category', kwargs={'pk' : self.pk}) def __str__(self): return self.title class Meta: verbose_name = 'category' verbose_name_plural = 'categories' ordering = ['-title'] This is the code forms.py: from django import forms from .models import News, Category from django.core.exceptions import ValidationError import re class NewsForm(forms.Form): title = forms.CharField(max_length=150, min_length=1, label='Title', widget=forms.TextInput(attrs={'class' : 'form-control'})) content = forms.CharField(label='Text', required=False, widget=forms.Textarea(attrs={'class' : 'form-control', 'rows' : 15})) # photo = forms.ImageField(upload_to='photos/%Y%m/%d/') is_published = forms.BooleanField(label="To publish", initial=True) category = forms.ModelChoiceField(label='Category', queryset=Category.objects.all(), empty_label='Select a category', widget=forms.Select(attrs={'class' : 'form-control'})) def clean_title(self): raise ValidationError('Error!') # … -
User can't login into my application hosted in heroku
I hosted my application on Heroku for almost two weeks. For the first time everything is working fine but yesterday at morning, i have try to login but it does not redirected me to the user dashboard, and I don't know why as you can see in code below nothings is wrongs with it: def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return redirect('index') else: messages.info(request, 'Invalid Credential') return redirect('login') else: return render(request, 'login.html') my form: <form method="POST"> {% csrf_token %} <div class="form-group"> <label class="text-primary">Enter Username</label> <input type="text" class="form-control" name="username"> </div> <br> <div class="form-group"> <label class="text-primary ">Enter Password</label> <input type="password" class="form-control" name="password"> </div> <br> <a href="{% url 'register' %}" style="text-decoration: none;" class="text-primary text-center"> SignUp Now <br> <br> <a href="{% url 'reset_password' %}" style="text-decoration: none;" class="text-primary text-center"> Forgot Password </a> </a> <br> <br> <button type="submit" class="btn btn-primary">Login</button> </form> -
django data table filters with filter-checkbox
HOW CAN I CONVERT THIS DYNAMIC FILTER JAVASCRIPT INTO CHECKBOX FILTER JS AND THE DATA WHICH IS EXPOSED IN THE FOR LOOP IS COMING DIRECTLY FROM SQL CONNECTION. PLEASE HELP """ function myFunction() { var input, filter, table, tr, td, i, txtValue; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); table = document.getElementById("myTable"); tr = table.getElementsByTagName("tr"); for (i = 0; i < tr.length; i++) { td = tr[i].getElementsByTagName("td")[1]; if (td) { txtValue = td.textContent || td.innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { tr[i].style.display = ""; } else { tr[i].style.display = "none"; } } } } </script> """ """ <div class="sub-filter filter-hide" aria-labelledby="static-filter-company" data-toggle="checkboxgroup"> <ul role="listbox"> <li role="option"> <div class="filter-item pad-responsive-lr"> <div class="checkbox"> <input id="static-check-company" type="checkbox" data-indeterminate checked/> <label for="static-check-company">Select All</label> </div> </div> <ul class="filter-checklist"> {% for i in res %} <li class="pad-responsive-lr filter-item" role="option"> <div class="checkbox"> <input class ="filter-checkbox" data-filter="cols" id="static-check-mendez" type="checkbox" value="{{i.0}}"/> <label for="static-check-mendez">ID</label> </div> </li> {% endfor %} </ul> </div> """ HOW CAN I CONVERT THIS DYNAMIC FILTER JAVASCRIPT INTO CHECKBOX FILTER JS AND THE DATA WHICH IS EXPOSED IN THE FOR LOOP IS COMING DIRECTLY FROM SQL CONNECTION. PLEASE HELP -
Django Develop Live Streaming Application
We are building Live Streaming Application and I found there is very few resources to achieve this kind of thing. I decided to integrate third-party tools with Django to implement live streaming! Does anyone know any third-party service or tutorial to develop live video streaming? so that my user can go love using my webpage anytime. -
django.core.exceptions.SuspiciousFileOperation: The joined path is located outside of the base path comp
raise SuspiciousFileOperation( [20/Jun/2022 15:21:10] "GET /static/assets/img/logos/facebook.svg HTTP/1.1" 404 1846 django.core.exceptions.SuspiciousFileOperation: The joined path (S:\cdn.startbootstrap.com\sb-forms-latest.js) is located outside of the base path component (C:\Users\Nishant\Envs\work\lib\site-packages\django\contrib\admin\static) [20/Jun/2022 15:21:10] "GET /static/assets/img/about/2.jpg HTTP/1.1" 404 1825 [20/Jun/2022 15:21:10] "GET /static/assets/img/logos/google.svg HTTP/1.1" 404 1840 [20/Jun/2022 15:21:10] "GET /static/assets/img/about/3.jpg HTTP/1.1" 404 1825 [20/Jun/2022 15:21:10] "GET /static/https%3A/cdn.startbootstrap.com/sb-forms-latest.js HTTP/1.1" 500 59 [20/Jun/2022 15:21:10] "GET /static/assets/img/team/1.jpg HTTP/1.1" 404 1822 [20/Jun/2022 15:21:10] "GET /static/assets/img/about/4.jpg HTTP/1.1" 404 1825* [ [ i am having this error that path is located outside of the base path and i also uploaded all my file in github link is given ][github link for files] ][screenshort of the error] * -
Django apps ,Ajax post is not working over HTTPS in Azure, returns 403
I'm new to Azure. when I host the same website in Heroku it works fine in both(Http and Https). But in Azure the ajax POST Method is only working over Http but return 403 in Https and showing error when login to Django admin pannel Django admin login error I tried many things but still I cannot figure it out Its not the problem in code because it works fine in Heroku. I think missed something in Azure Network configuration You can visit the websites Problem in https://glide.azurewebsites.net Works in http://glide.azurewebsites.net Works in https://estatemanagements.herokuapp.com When page Loades it sends a ID that saved in browser via post request if ID is not available a Sign in button will appear if ID is there it will return the Name and email You can notice that over http connection sign in button is visible in Login and Register(https://glide.azurewebsites.net/auth) also not responding -
best way to rename django app without getting errors
am in need of renaming my django app but i know that comes with alot of problems and headaches if done wrong. Anyone got any ideas on how to do it as smooth as possible? I looked around and is this metod the best one to do? or any other suggestions? https://pypi.org/project/django-rename-app/ https://odwyer.software/blog/how-to-rename-an-existing-django-application -
getting this error : how can i solve it using django?
hello im try to add google recaptcha t my website so when i add the recaptcha i had this error : ?: (captcha.recaptcha_test_key_error) RECAPTCHA_PRIVATE_KEY or RECAPTCHA_PUBLIC_KEY is making use of the Google test keys and will not behave as expected in a production environment HINT: Update settings.RECAPTCHA_PRIVATE_KEY and/or settings.RECAPTCHA_PUBLIC_KEY. Alternatively this check can be ignored by adding SILENCED_SYSTEM_CHECKS = ['captcha.recaptcha_test_key_error'] to your settings file. how can i solve it ? -
Django - update query doesn't work in pre_delete signal
I tried to update a Transaction model queryset in the below pre_delete signal that connected to the Wallet model, but it didn't work. The signal triggers, and all lines work correctly, except the last line :( @receiver(pre_delete, sender=Wallet) def delete_wallet(sender, instance, **kwargs): if instance.is_default: raise ValidationError({"is_default": "You can't delete the default wallet"}) q = {"company": instance.company} if instance.company else {"user": instance.user} try: default_wallet = Wallet.objects.get(**q, is_default=True) except Wallet.DoesNotExist: default_wallet = Wallet.objects.filter(**q).first() if not default_wallet: raise ValidationError({"is_default": "You can't delete the last wallet"}) instance.transactions.all().update(wallet=default_wallet) -
How could I keep the variable constant in looping when the variable is reused in python
I'm trying to loop through the JSON where I have sid which is initially zero when it is passed through the Stored Procedure it will return some value 8463 and I want to keep this value as sid and again I want to pass the same value which is 8463 through the SP again. I have tried keeping it constant but once it loop through the one dictionary it automatically increasing the value of `sid. Views.py @api_view(['POST']) def SaveUserResponse(request): if request.method == 'POST': for ran in request.data: print(type(ran),'QId--',ran.get('QId'), ran) print(type(request.data)) auditorid =ran.get('AuditorId') print('SaveUserResponse auditorid---', auditorid) ticketid = ran.get('TicketId') qid = ran.get('QId') answer = ran.get('Answer') sid = '0' cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_SaveAuditResponse] @auditorid=%s,@ticketid=%s,@qid=%s,@answer=%s,@sid=%s', (auditorid,ticketid,qid,answer, sid)) result_st = cursor.fetchall() print('sp_SaveAuditResponse', result_st) # # if qid != 1 or qid != 42: for row in result_st: print('sp_SaveAuditResponse', row) sid = row[0] return Response(row[0]) Payload: [{"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":42,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":43,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":44,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":45,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":46,"Answer":"3","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":47,"Answer":"5","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":48,"Answer":"5","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":49,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":50,"Answer":"5","SID":"0","Comments":""}] -
Directory indexes are not allowed here. I`m trying to solve this error but nothing any solution
Here Is My Code for trying to view pdf file by pressing button.How to solve this problem please add some reply for solving this problem thank you advance.. here is my views.py code : def show(request): a=student.objects.all() return render(request,'show.html',{'a':a}) def ppts(request, id): b=student.objects.get(id=id) return render(request,'ppts.html',{'b':b}) And Here is my html file <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <td><embed src="{% static ' ' %}{{a.resume}} " height="700px" width="1500px"></td> <!-- <td> <a href="" download></a> </td> --> </body> </html> And Here is my show.html code : <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=>, initial-scale=1.0"> <title>student table</title> </head> <body> <table> <thead> <tr> <th>NAME</th> <th>ADDRESS</th> <th>AGE</th> <th>EDUCATION</th> <th>EMAIL</th> <th>RESUME</th> </tr> </thead> <tbody> {% for val in a %} <tr> <td>{{val.NAME}}</td> <td>{{val.ADDRESS}}</td> <td>{{val.AGE}}</td> <td>{{val.EDUCATION}}</td> <td>{{val.EMAIL}}</td> <td><button><a href="/ppts/{{val.id}}/">{{val.resume}}</a></button></td> </tr> {% endfor %} </tbody> </table> </body> </html> here is output showing while run this program.. -
Django: How to create superuser with custom fields?
I have a custom User model in my models.py and custom UserManager as well. My custom User model has username field with changed name to login and same is updated in UserManageras well. Everything goes fine, but when I try to create superuser using commandpython manage.py createsuperuser, it asks for loginbut it does not ask foremail` which at the end gives me this error: TypeError: UserManager.create_superuser() missing 1 required positional argument: 'email' My custom User model is: class User(AbstractBaseUser, PermissionsMixin): login = models.CharField(max_length=254, unique=True) email = models.EmailField(max_length=254, unique=True) first_name = models.CharField(max_length=254, null=True, blank=True) last_name = models.CharField(max_length=254, null=True, blank=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'login' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) My custom UserManager is: class UserManager(BaseUserManager): def _create_user(self, login, email, password, is_staff, is_admin, **extra_fields): if not email: raise ValueError('Users must have an email address') now = timezone.now() email = self.normalize_email(email) user = self.model( login=login, email=email, is_staff=is_staff, is_active=True, is_admin=is_admin, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, login, email, password, **extra_fields): user = self._create_user(login, email, password, False, False, **extra_fields) user.save(using=self._db) return user def create_superuser(self, login, email, password, … -
How to implement Buy Now functionality using Django in eCommerce
I am creating an e-commerce website. almost done!! But I want to add extra feature which is Buy Now I found the same question Here -
django quill editor how to make validation on quill text area
i have django form in which a text area is made up using quill editor know if i submit form with data it work correctly but when i submit it text area empty it gives me key error . how to make validation on quill field that it required form.py def clean(self): data = super(NewQuestion, self).clean() if len(data['title']) < 15: self.add_error('title', "Title must be at least 15 characters.") if len(data['body']) < 30: self.add_error( 'body', f"Body must be at least 30 characters; you entered {len(data['body'])}.") if len(data['tags']) < 1: self.add_error( 'tags', f"Please enter at least one tag; .") models.py class Questions(models.Model): title = models.CharField(max_length=150, blank=False,) body = QuillField(blank=False) views.py if request.method == 'POST': newQuestionForm = NewQuestion(request.POST or None) if newQuestionForm.is_valid(): -
psycopg2.errors.CannotCoerce: cannot cast type integer to interval
Error when running migrations.AlterField in a conversion from IntegerField to DurationField using PosgreSQL with Django 2.2. Any workaround? -
How to store list of foreign keys in a model
Hii Everyone here is the case in which i am facing this same issue please have a look over this: ClassificationGroup.py class DeviceClassificationGroup: vendor_id = models.ForeignKey(Vendor, on_delete=models.CASCADE, default=None, null=True) id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) description = models.CharField(max_length=1000) classification = ?? Classification.py class DeviceClassification(models.Model): vendor_id = models.ForeignKey(Vendor, on_delete=models.CASCADE, default=None, null=True) id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) description = models.CharField(max_length=1000) device_type = models.IntegerField() device_name_regex = models.CharField(max_length=100) vid_pid = models.CharField(max_length=50) device_instance_id = models.CharField(max_length=100) serial_number = models.CharField(max_length=100) brand = models.CharField(max_length=25) def __str__(self): return self.name So i would have set of classifications that i can put in the one classification group. How can i store an unknown amount of foreign keys in a django model?? Kindly help me out in this. -
Detect if Django API query is from own-site or external site
I have Django running on a server which has a public facing API. I want to do different django-rest-framework throttling based on where the request is coming from. For example, if the request is coming from an Angular client on the same domain (e.g. my-angular-client.mydomain.com) I'd like it to be rate limited differently to, say, a curl request from someone's command line. What is the best practice for this? I know there is data in HttpRequest.META such as REMOTE_ADDR, but that field is empty when I use my test server rather than running locally. There's also HTTP_REFERER, but that seems to populate only if the page is a django template page, rather than say, a client built using a different tech stack, such as Angular. What should I be using for this use case? -
Display my Django project on my server domain
I have a Django project on a CentOS server. I run the following command - python3 manage.py runserver 0.0.0.0:8080 Django version 3.2.13, using settings 'djangonautic.settings' Starting development server at http://0:8080/ But when I visit http://myDomainName:8080 I get the error ERR_CONNECTION_REFUSED. I also tried running - python3 manage.py runserver myIP:8080 but when I visit http://myIP:8080 I receive Bad Request (400). This time I can see the GET request on my server - "GET / HTTP/1.1" 400 143 [20/Jun/2022 09:16:39] "GET /favicon.ico HTTP/1.1" 400 143 [20/Jun/2022 09:16:41] "GET / HTTP/1.1" 400 143 [20/Jun/2022 09:16:41] "GET /favicon.ico HTTP/1.1" 400 143 The allowed_hosts in setting.py containing my domain name. Thanks!