Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I load a module in a Django template with a variable for the module name?
I want to build some very similar apps in Django, but I want them to load different tag/filter modules. For this I want the html templates to be generic. For example, I would like to have something like {% load specific_tags %} and then I would like to define the variable specific_tags in a context processor for each app. But Django thinks that it should look for "specific_tags" in the installed apps in settings.py. How can I tell Django/Python to first evaluate the content of the variable from the context processor? Best regards -
Performing layer 7 health check with HAProxy and uWSGI in Django application
I'm using this uwsgi.ini to run a Django application. [uwsgi] http-socket = :8000 enable-proxy-protocol = true chdir = /usr/local/src/api module = api.wsgi uid = root gid = root pidfile = /var/run/api-uwsgi.pid master = true processes = 10 chmod-socket = 664 threaded-logger = true logto = /var/log/api/uwsgi.log log-maxsize = 10000000 logfile-chown = true vacuum = true die-on-term = true I've added an API url to perform database and cache health checks under the /health-check url. This API returns status code 200 if everything is fine. Now I want to be able to health check in layer 7 using this API with HAProxy but using option httpchk the response status code is 301, so the health check fails. Here is the backend part of my HAProxy config. backend http_server mode http balance leastconn option forwardfor http-request set-header X-Forwarded-Port %[dst_port] http-request add-header X-Forwarded-Proto https if { ssl_fc } option httpchk http-check send meth GET uri /health-check ver HTTP/1.1 hdr Accept application\json http-check expect rstatus 200 server app1 192.168.0.11:8000 check inter 500 downinter 5s fall 2 rise 3 server app2 192.168.0.12:8000 check inter 500 downinter 5s fall 2 rise 3 Here is the result of running the Django apps with uWSGI and HAProxy. Note … -
Sorl-thumbnail--> Image height is not equals to the given height
After implementing the below code when i see image on frontend width is 430 but height not equals to th given height(250) instead it is 100 {% load thumbnail %} {% thumbnail recipe.image "430x250" as thumb %} {% endthumbnail %} -
Custom permissions for Simple-JWT in Django Rest Framework
For my current system, I am using Simple-JWT as my user authentication. And also using Django REST Framework API Key. I am satisfied with Simple-JWT for its simplicity. However, I would like to add a permission where it requires my Api-Key to be able to view the token page. As for now, if I want to get a JWT Token, I can simply go to /project/api/token/ (To get access and refresh token) OR /project/api/refresh/ (To refresh the access token) In my settings.py file, I have set the DEFAULT_AUTHENTICATION_CLASSES and DEFAULT_PERMISSION_CLASSES. From my understanding, if I put 'HasAPIKey' as the default permission classes, all pages will require the Api-Key. REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework_api_key.permissions.HasAPIKey', ), } However both /token/ and /refresh/ can still be accessed without an Api-Key. Hence, my goal is to make sure those URLs require my Api-Key. (Note: I am fully satisfied with how 'simple-jwt' provides the token. It was easy to be implemented. I simply want to add the 'HasAPIKey' permission) -
Django modelformset_factory how to save form with request.user?
how to save modelformset_factory with request.user? error: Exception Type: AttributeError Exception Value: 'list' object has no attribute 'user' def pubblica_orari(request): TimeFormSet = modelformset_factory(Time, form=TimeForm) if request.method == "POST": formset = TimeFormSet(request.POST) if formset.is_valid(): instance = formset.save(commit=False) instance.user = request.user instance.save() messages.success(request, 'Salvato con successo!', extra_tags='alert alert-success alert-dismissible fade show') return redirect('pubblica_orari') else: formset = OrariFormSet() return render(request, 'attivita/pubblica_orari.html', {'formset': formset}) -
Best practice: Face Recognition Authentication
I am working on a django project and I build a login system with the face recognition library. I am concerned about security issues the way I build this and I wanted to ask how I could optimize it. In the template, I: capture the image with the webcam and draw it on canvas. save the canvas to image and post the image-data together with the username of somebody who wants to access his account. In the backend, I: serialize the login credentials and save them to the database. encode and compare the uploaded image using the face_recognition library with another image the user has uploaded when registering. login the user But this way anyone who has an image and the username of a person could access his account. Thank you for any suggestions -
Send mail from business email in smtp django
I have a business email and I want to send messages to other users from that email which is different from Gmail. How do I setup that? -
How to associate a username from the User model to another model in Django?
I currently have an index view with several input tags for a name, file and tags. I'm trying to connect the model that handles that view (name: Uploaded) to the User model and associate the logged in users username to the Uploaded model. Here's my view: def index(request): if request.method == 'POST': form = FileUploadForm(request.POST, request.FILES) if form.is_valid(): form.save() else: form = FileUploadForm allTags = Tag.objects.all() context = {'form': form, 'allTags': allTags} return render(request, 'index.html', context) and here's the Uploaded model: class Uploaded(models.Model): objects: models.Manager() user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="users") name = models.CharField(max_length=50) file = models.FileField(upload_to=MEDIA_ROOT) tags = TaggableManager() def __str__(self): return f"{self.name} {self.file}" -
Django | example of usage of Expression in check constraint
Django docs says that sinse version 3.1. it is possible to use Expression in check-constraints. https://docs.djangoproject.com/en/3.1/ref/models/constraints/ CheckConstraint.check¶ A Q object or boolean Expression that specifies the check you want the constraint to enforce. For example, CheckConstraint(check=Q(age__gte=18), name='age_gte_18') ensures the age field is never less than 18. Changed in Django 3.1: Support for boolean Expression was added. Does anyone have any real life or at least decent made up example how to use Expression in check constraints basically, cos i can't get my head around it and there are no any example in documnetation. Thank you. -
How to add constraint for 2 fields not having the same value?
How to write a check that checks if two objects of the same model are not the same object? class Foo(models.Model): first = models.ForeignKey(Bar, on_delete=models.CASCADE, related_name='first') second = models.ForeignKey(Bar, on_delete=models.CASCADE, related_name='second') class Meta: constraints = [ CheckConstraint(name='not_same', check=(first!=second)) ] -
Passing a parameter in url through multiple pages in django
I may not have been descriptive in the title but what I want is that for example When a new user opens a page where login is required --> he is redirected to login page with the login url having a next parameter to the previous page.But as he is a new user he chooses to signup by clicking on a link on the login page which takes him to signup page ,now this is where the problem comes - The signup url gets no parameter and once user signs up he is automatically redirected to login page and after he logs in he is redirected to the index page instead of the page where login was required. This is my login view for my customer user model: def login(request): if request.user.is_authenticated: return redirect('/') else: if request.method == "POST": email=request.POST['email'] password=request.POST['password'] user=auth.authenticate(email=email,password=password) if user is not None: auth.login(request, user) next_page = request.POST['next'] if next_page != '': return redirect(next_page) else: return redirect('/') else: messages.info(request,"Email Password didn't match") next = request.POST['next'] if next != '': login_url = reverse('login') query_string = urlencode({'next': next}) url = '{}?{}'.format(login_url, query_string) # create the url return redirect(url) else: return redirect('login') else: return render(request,"login.html") And signup view: def … -
dependent dropdown error 'tuple' object has no attribute 'get'
**PCR.html** <div class="main-container"> <p>PCR LIVE INDICATOR</p> <form method="POST" id="pcrchart" data-pcr-url="{% url 'ajax_expiry'%}"> <div class="drop1"> <label>Select Symbol</label> <select name="company" id="company" size="1"> <option value="" selected="selected">Nifty</option> {% for i in d %} <option value="{{i.name}}">{{i.name}}</option> {% endfor %} </select> </div> <div class="drop2"> <label>Select Expiry</label> <select name="expiryDate" id="expiryDate" size="1"> </select> </div> <div class="drop3"> <label>Select Strike</label> <br> <select name="price" id="price" size="1"> <option value="" selected="selected">12700</option> {% for Price in Prices %} <option value="{{price.pk}}">{{price.name}}</option> {% endfor %} </select> </div> </form> pcr1.html <option value="" selected="selected">27 Aug 2020</option> {% for expiryDate in expiry %} <option value="{{expiryDate.expiry}}" title="27 Aug 2020">{{expiryDate.expiry}}</option> {% endfor %} views.py def pcr(request): d={} d = stock.objects.all() return render(request,'pcr.html',{"d":d}) def expiry(request): name1 = request.GET.get('company') print(name1) expiry=NFO.objects.all().filter(name=name1) return (request,'pcr1.html',{ 'expiry': expiry, }) i am write to write a dependent dropdown list .the first dropdown value is selected based on that on second dropdown there is an error thAT 'tuple' object has no attribute 'get' Request Method: GET Request URL: http://127.0.0.1:8000/ajax/expiry/?company=NIFTY Django Version: 3.0.7 Exception Type: AttributeError Exception Value: 'tuple' object has no attribute 'get' Exception Location: /usr/local/lib/python3.8/dist-packages/django/middleware/clickjacking.py in process_response, line 26 Python Executable: /usr/bin/python3 Python Version: 3.8.3 Python Path: ['/root/Documents/optionplus', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/usr/local/lib/python3.8/dist-packages', '/usr/lib/python3/dist-packages', '/usr/lib/python3.8/dist-packages'] Server time: Sat, 29 Aug 2020 20:57:06 +0530 -
Can't raise the error in UserCreationForm in Django?
I want to raise the error in my UserCreationForm. I have seen previous questions on this problem but It's not working for me. I gave the existing email and when i submitted there's no error display on the page. Can you spot me the mistakes? How I wrote in forms.py class StudentRegisterForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ['email', ....] def __init__(self, *args, **kwargs): email_attr = {'class': 'form-control', 'id': 'email-register', 'type': 'email'} super(StudentRegisterForm, self).__init__(*args, **kwargs) self.fields['email'].widget.attrs.update(email_attr) # some other fields def clean_email(self): email = self.cleaned_data.get('email') if CustomUser.objects.filter(email=email).exists(): raise forms.ValidationError("Email's already taken!") return email views.py class StudentRegisterView(SuccessMessageMixin, CreateView): template_name = "attendance/login-register/student_register.html" form_class = StudentRegisterForm success_url = "/" -
Can you show me an example of Mixins in Django? What is the usage?
I am new to Django, and I usually used function-based views. But I see that using mixins and class-based views way more powerful. I did a lot of research but I am still confused about how to use Mixins. How come Mixins are an excellent way of reusing code across multiple classes? If you show me an example or better way of explanation than it does in docs, I would be appreciated. -
django LEFT JOIN targets ON FIND_IN_SET
i need to implement a query with django orm like that: http://sqlfiddle.com/#!9/7fcd03/1/0 how can i implement the LEFT JOIN targets ON FIND_IN_SET(targets.id, info.target_ids) with django? is that possible? should i use the .extra() ? my code now it's like that: search = self.model.objects.annotate(services = GroupConcat(Services)).filter(services__icontains=self.request.GET['type'], city__icontains=self.request.GET['city']).order_by('id') Thanks -
Not able to run the command "sudo nginx -t"
I am following this document and this tutorial to deploy a Django website on Microsoft azure. After configuring all the setting upto "Configure Nginx to Proxy Pass to Gunicorn", when i executed "sudo ngnix -t" to test that all is working or not, It is giving this Error nginx: [emerg] open() "/etc/nginx/sites-enabled/myproject" failed (2: No such file or directory) in /etc/nginx/nginx.conf:62 nginx: configuration file /etc/nginx/nginx.conf test failed Please Help me. -
Django-template. How to create list of values for specific key for each element in QuerySet
I am sending all objects to html through context: views.py def books(request): all_books = Book.objects.all() context = {'books': all_books} return render(request, 'books/books.html', context) models.py class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=30) category = models.IntegerField() offset_pages = models.IntegerField() read_pages = models.IntegerField() total_pages = models.IntegerField() book_path = models.CharField(max_length=200, default='') status = models.BooleanField(default=False) def __str__(self): return f'{self.category} | {self.title} | {self.author}' Is this possible to get a list of all values for specific key in django template? I would like to have a list of all read_pages values for each element in QuerySet. I can do this through a context as well I believe, but it seems like there has to be a better way. I need a list because I want to send it do chart.js later on. -
Django Bug with long name in db_column?
When i use a long name in db_columns at a field in Models.py, django does not work correct. It truncates the name, and add random letters/numbers at the end. Like this: db_column='my_loooooooooooooooooong_column_name' And when i try queryset, django returns: 'table name'.'my_looooooooooooooo6E4': invalid identifier. My scenario in detail: I have a legacy database in Oracle. The table name in database: PALAVRA_CHAVE_ENTREGA_VALOR With 3 Fields: PCEV_CD_PALAVRA_CHAVE_ENTREGA_VALOR (Primary Key), PACH_CD_PALAVRA_CHAVE, ENVA_CD_ENTREGA_VALOR In my models.py: class PalavraChaveEntregaValor(models.Model): pcev_cd_palavra_chave_entrega_valor = models.BigIntegerField(primary_key=True, db_column='pcev_cd_palavra_chave_entrega_valor') pach_cd_palavra_chave = models.BigIntegerField() enva_cd_entrega_valor = models.BigIntegerField() class Meta: managed = False db_table = 'palavra_chave_entrega_valor' When i run in shell (python manage.py shell) this command: PalavraChaveEntregaValor.objects.all() I got output: DatabaseError: ORA-00904: "PALAVRA_CHAVE_ENTREGA_VALOR"."PCEV_CD_PALAVRA_CHAVE_ENTRA6E4": invalid identifier I made a test, and changed the long name PCEV_CD_PALAVRA_CHAVE_ENTREGA_VALOR to PCEV_CD, and everthing works fine.. Is there a limitation of characters in db_columns at django? Is there a workaround for this? If not, i will have to create a lot of Views in Oracle Database with shorter names of columns only for django work.. Change the current table column names is not an option. -
How to add integers to primary key field in Django Model at save
In my Django app, I have created a model with the id (primary key) as a CharField of length 6. I am using a custom validator which allows the user to only enter integers only. Is there a way to add zeros before the input if it is less than the "six" character length specified in the field definition. For example, the user enters value 1234 in the primary key field. Now I want that at save the pk field value should be saved as 001234. I tried doing that at save but two records are getting created, one with the input by the user and the other with the zero(s) added. Is this at all possible to achieve what I am trying to do? -
Migrating from django celery tasks to apache airflow
I have a python/django project (running in docker containers). There's a data collection workflow which is implemented via celery tasks, which depend on each other and run in parallel. I want to migrate all this logic to apache airflow, because I assume it suits for my needs and it will be more convenient to start and restart the tasks, build more complex workflow, monitor and debug. I've never used airflow before. Is my plan sane? Where do I start? What executors should I use? -
DRF simple jwt. How to change response from TokenObtainPairView to get an access token EXPIRES time
I wrote in urls: from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, ) urlpatterns = [ ... path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ... ] Then when I request api/token/, I got a json response with only access and refresh tokens. But I need to get also an access token expires time for saving it to localStorage and request to the refresh url, save the new access token in the storage if the time was expired -
How to host number of websites under similer url
I have a site build in site123 (site123 is a WYSIWYG and it dose not support code export). I use it as a nice designed landing page and product's catalog. so I have: https://app.site123.com/?w=my_site this site has no back-end (not supported by site123). and I have another site build in django for payments and other stuff like this I host it on pythonanywhere, So I also have http://my_website_with_backed.pythonanywhere.com/. Now, I buy a domain from GoDaddy and I would like to know if there is a way to connect the 2 websites under the same url??. like: site123 website: www.catalog.my_own_url.com django website: www.payment.my_own_url.com Thank you -
Is there any way to keep on updating Django Database?
I am making a Django API for Movie Ticket Booking System. The model for a ticket has got 5 fields namely Name of the User Phone Number of the User Date Time Status (Discussed in detail below) The operations supported by the API are, GET -> get all the ticket details GET/ID -> get the ticket details for the specified ID POST -> Book a new ticket PUT -> Update date and time of a ticket DELETE/ID -> Delete a ticket with the specified ID I have completed all the above specified functions. But Now I want to do something like, Mark a ticket as expired if there is a diff of 2 hours between the ticket timing and current time. AND Delete expired tickets automatically I cannot find any useful resources to do the above specified tasks and am unable to think of a professional way to do so. Can anyone please explain the best approach to solve the above problems. NOTE: The API will not be going LIVE. It will only run on my local machine. -
Create User in Django through form
I want to have a user sign up form in Django, I know that for the Backend I should have something like this: >>> from django.contrib.auth.models import User >>> user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword') >>> user.last_name = 'Lennon' >>> user.save() However, I don't know how to make the Frontend. I've already looked up in the Django documentation and found the UserCreationForm class and it says it's deprecated. What should I do? Thank you -
Login using Django sessions when using Django REST framework
I have a Django application. Some parts of the applications are using only Django and Django templates and thus session authentication. Some other parts are written using Django REST framework with JWT authentication. I want to login the use in Django when the request for obtaining the JWT tokens arrives to the server. I use Django's login(request, user), but it's not working. What should I do?