Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Django's "truncatechars" to get last n characters of a word
While I was learning Django Templates, I came to know that we can use Django's built in template's truncatechars function to get first n characters of a world like this; Here, data = Stackoverflow.com {{ data|truncatechars:9 }} # It would print "Stackover.." But what should I do If I need last 9 characters of a word like '..rflow.com' Is there built in function in django template which can give me the inverse of truncatechars:9 ? -
getCookie(name) in django for paypal integration
`I am trying to integrate paypal payment in one website. I need paypal payment id and status response. I have a paypal button integrated already using paypal.Buttons function. The problem I face is if I use csrf token, the paypal button disappears from the page. If I am not using the csrf then the function will work, but with errors "Forbidden (CSRF token missing.):". If I remove " 'X-CSRFToken': 'csrftoken' " from function sendData() and "var csrftoken = getCookie('csrftoken');" then the paypal button will appear again. var csrftoken = getCookie('csrftoken'); var url = "{% url 'payments' %}" // payments is a custom name var orderID = "{{ order.order_number }}" var payment_method = " PayPal" function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = docodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } function sendData() { fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': 'csrftoken', }, body: JSON.stringify({ orderID: orderID, transID: details.id, // from paypal response payment_method: payment_method, status: details.status, // from paypal response … -
How do I record data FK'd to two other models?
Using the 'Pizza' example, I have a Toppings Model, I have a PizzaTemplate Model and a 'Pizza', and now I need to record an amount of topping for each pizza. For Example I have a 'Pepperoni Pizza', I need to record 1 scoop of cheese, 1 scoop of pepperoni. Then I might have a 'Pepperoni Pizza - Extra Pepperoni' which would be 1 scoop of cheese and 2 scoop of peperoni, it uses the same selection of toppings, which have already been defined, I just need to record how much of each. My Current models.py looks like this: class Topping(models.Model): name = models.CharField(max_length=100) unit = models.CharField(max_length=100) class PizzaTemplate(models.Model): name = models.CharField(max_length=100) toppings = models.ManyToManyField(Topping) class Pizza(models.Model): name = models.CharField(max_length=100) Im guessing I need another model like so: class Ingredients(models.Model): pizza = models.ForeignKey(Pizza) topping = models.ForeignKey(Topping) amount = models.IntegerField() I'm not sure if this is the correct way to achieve this or there's a smarter way? The idea is to be able to create a new pizza, choose a topping template, and then specify varying amounts of each topping for this particular Pizza Option. My idea was to dynamically create the form for each input on page load, eg, get the … -
Solution to filter by Cumulative sum and error: Window is disallowed in the filter clause
This is follow-up to a question to: Filter Queries which sum of their amount field are greater or lesser than a number which is supposed to be solved. Answer suggests using Window function with filter but this results in a error: django.db.utils.NotSupportedError: Window is disallowed in the filter clause. Comment from @atabak hooshangi suggests removing the Window function, but query doesn't work in intended way after that. Any ideas to solve this problem? -
how to get a column value of foreign key in the form of object?
There is 2 models Registration and RegistrationCompletedByUser, I want Registration queryset from RegistrationCompletedByUser with filters(user=request.user, registration__in=some_value, is_completed=True) over RegistrationCompletedByUser. Hence result should be like <QuerySet [<Registration: No name>, <Registration: p2>, <Registration: p-1>]>. Now what I tried is Registration.objects.prefetch_related('registrationcompletedbyuser_set') but filters() not working. Another way I tried is model Managers but don't pass parameters for custom filtering. models.py class Registration(models.Model): name=models.CharField(max_length=255) number=models.SmallIntegerField(null=True, blank=True) class RegistrationCompletedByUser(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) registration= models.ForeignKey(Registration, on_delete=models.CASCADE) points = models.SmallIntegerField(default=100) is_completed = models.BooleanField(default=False) -
Django Channels do not send message within except block in Celery task
I am currently facing an issue with the Django Channels and Websockets. I have an application that somehow works with files and Sharepoint. Issued code sample where defect occurs: @shared_task(bind=True) def upload_to_sharepoint_task(self, user_id: str, document_type: str, upload_file: str, filename: str) -> None: """Uploads a file to SharePoint.""" task_id = self.request.id try: upload_to_sharepoint(user_id, document_type, upload_file, filename) print(f"Task {task_id} completed successfully.") async_to_sync(get_channel_layer().group_send)(task_id, { "type": "send_task_status", "message": {'task_id': task_id, 'status': "SUCCESS", } }) except BackendError as e: print(f"Task {task_id} failed with error: {str(e)}") async_to_sync(get_channel_layer().group_send)(task_id, { "type": "send_task_status", "message": {'task_id': task_id, 'status': "FAILURE", 'error': str(e)} }) If everything the method upload_to_sharepoint does not throw an exception, everything works just fine - the message is sent to the group and, via WebSocket, propagated to the Client. However, if I try to simulate a situation when the exception is thrown (for instance, by throwing the BackendException explicitly), the error message gets printed in the console, but WebSocket does not receive any message nor the Client. My TaskConsumer: class TaskConsumer(WebsocketConsumer): def connect(self): self.task_id = self.scope['url_route']['kwargs']['task_id'] # Join the task_id group async_to_sync(self.channel_layer.group_add)(self.task_id, self.channel_name) self.accept() def disconnect(self, close_code): # Leave the task_id group async_to_sync(self.channel_layer.group_discard)( self.task_id, self.channel_name ) def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json["message"] print(f"Task {self.task_id} received … -
ModuleNotFoundError: No module named '_sqlite3' Error when try to import sqlite3 and Django
I tried to Create Django Project. I'm able to create project but not able to run the runserver command. I got below error. I also tried to import sqlite3 got same error >>> import sqlite3 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.11/sqlite3/__init__.py", line 57, in <module> from sqlite3.dbapi2 import * File "/usr/local/lib/python3.11/sqlite3/dbapi2.py", line 27, in <module> from _sqlite3 import * ModuleNotFoundError: No module named '_sqlite3' >>> Python version: Python 3.11.0 -
File from django model not uploading
These are my models class Post(models.Model): title = models.TextField(default="no title") body = models.TextField(default="no body") creation_date = models.DateTimeField(default=timezone.now) creator = models.ForeignKey(User, on_delete=models.CASCADE) document = models.FileField(upload_to="uploads/", null=True, blank=True) the one that isn't working is document, i have set up a form and when i "post" the form the other stuff like title ,body, creation date and creator are being saved but the document isn't, cant even find it in any folder this is my view class Post_List(LoginRequiredMixin, View): def get(self, request, *args, **kwargs): posts = Post.objects.order_by("-creation_date") form = PostForm() context = { "post_list" : posts, "form" : form, } return render(request, 'social/post_list.html', context) def post(self, request, *args, **kwargs): posts = Post.objects.order_by('-creation_date') form = PostForm(request.POST, request.FILES) if form.is_valid(): new_post = form.save(commit=False) new_post.creator = request.user new_post.save() context = { 'post_list': posts, 'form': form, } return redirect('/feed') I tried migrating again but nothing changed -
Add 1 month above today's date with django python
I want to add 1 month to today's date and keep this date in database enter image description here i tried this but it gave error -
Media folder not working properly & Images not being saved - Django
I am trying to add images to a post. (Using Django v3.2.5) root_directory/settings.py: BASE_DIR = Path(__file__).resolve().parent.parent ... MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') root_directory/urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('index.urls')), path('app2/', include('app2.urls')), path('app3/', include('app3.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) app3/models.py: from django.db import models from ckeditor.fields import RichTextField class Post_Picture(models.Model): title = models.CharField('Title', max_length=120) image = models.ImageField(blank=True, null=True, upload_to="images/") caption = RichTextField(blank=True, null=True) def __str__(self): return self.title app3/forms.py: from django import forms from django.forms import ModelForm from .models import Post_Picture class PostPicForm(ModelForm): class Meta: model = Post_Picture fields = ('title', 'image', 'caption') labels = { 'Title': '', 'Caption': '', } widgets = { 'title': forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Title your post'}), 'caption': forms.Textarea(attrs={'class':'form-control', 'placeholder': 'Anything extra you want to add?'}), } app3/views.py: from django.shortcuts import render, redirect from .models import Post_Picture from .forms import PostPicForm from django.http import HttpResponseRedirect from django.contrib import messages def your_home(request): friend_posts = Post_Picture.objects.all() return render(request, "app3/your_home.html", { 'friend_posts': friend_posts, }) def post_pic(request): submitted = False if request.method == "POST": form = PostPicForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('post_pic?submitted=True') else: form = PostPicForm() if 'submitted' in request.GET: submitted = True return … -
Django does not add attribute to the custom ModelForm widget
I'm trying to add another attribute in HTML (placeholder) using Django Widgets, when I do it, they don't appear in the HTML. models.py class InvitadosIngreso(forms.ModelForm): class Meta: model = InvitadosIngreso fields = ['oficina_pro' ,'documento' widgets = { 'oficina_pro' : forms.Select(attrs={'class':'form-control'},choices=ch_pro) ,'documento ': forms.TextInput(attrs={'class':'form-control', 'placeholder':'prueba',}) } forms.py class InvitadosIngreso(models.Model): oficina_pro = models.CharField(max_length=100, default='') documento = models.CharField(max_length=100, default='') nombre = models.CharField(max_length=100, default='') class Meta: db_table = 'InvitadosIngreso' -
Django -> post/get work but loading a fixture gets a "no such column error'
I've created a new model, and can post and get, and I receive all the fields. this indicates the underlying table is correct. I also manually checked my migrations and all the fields are there. And manually check the serializer (which is observably working via post/get). However, when I try the dumpdata or loaddata command, I get the error: "no such column: creator". Why would these two command think the field doesn't exist when the other aspects of the app can use it? -
How to update only a part of a json which is stored in a database with a "json path" list?
Let´s say we have a database and there is a json stored as a string which contains configurations. In the application we want to update only a specific value and write then back the json as a string to the database. The HTTP request provides a "jsonPath" which reflects a path in the json file to navigate to the object we want to update. This parameter is supplied as a list. An example for the path could be something like ['input', 'keyboard', 'language'] and the value we want to set is 'en' Here we load the configuration from the database which works so far: if request.data['jsonPath']: config = json.loads(models.Config.objects.get(name__startswith='general').value Then config is just a normal object now, which I can access with the dot notation like config.input.keyboard.language and it contains then the according part in json syntax. I am able to read out the value of the field with the following syntax: config[request.data['jsonPath'][0]][request.data['jsonPath'][1]][request.data['jsonPath'[3]] But the number of parameters can vary and I want also to write it back into the config object, convert it back to a string and write it into the database. I know it is not a nice thing but I would be interessted how it can … -
Is it possible to join two unrelated models based on a string column using Django-ORM
Currently, in a project that I'm working on, we are using the library called drf-api-tracking for logging each request that related data like an audit. The library is providing a mixin called LoggingMixin and by using that we are logging the API-related URL, status codes, requests, responses and etc. To save these data, the mixing is using a model called, APIRequestLog which is provided by the library. Let's assume the APIRequestLog model is like the below, class APIRequesLog(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) url = models.CharField(null=True, blank=True) ... In our system there we have a model called Dashboard and this model has an attribute called URL. Let's assume the Dashboard model is like below, class Dashboard(models.Model): shortname = models.CharField(null=True, blank=True) url = models.CharField(null=True, blank=True) ... My requirement is when I query the dashboard model, I need to get all the APIRequestLog records that are similar to the dashboard URL. I know that we can achieve this by iterating the dashboard records and filtering the APIRequestLog which has a similar URL to an iterating dashboard URL. But that would be time-consuming. Is there any method that we can join these two models based on the URL column and fetch the data at once? … -
How to add Tags to a model with django-taggits? (django)
I basically have a template which shows all the Tags you can click one. Then I get the Value of the checkbox (it is the Id of the Taggit Items, because I load the Tags from the Database in my Template) and send it to the database. But how can I give a model in my case a Post the Tag? In Pseudocode that would be: Create object Post Get tags from frontend >>> 1, 2 create taggit_taggeditem give item: object id: 22 tag ids: 1, 2 Thank you for answers. I don't have any ideas how to do that : ) . -
Compare values with each other and color the difference red
I have a django application. And I try to mark the difference of both the values red. So I have this to functions: pdf data: from django.utils.safestring import mark_safe from tabulate import tabulate class FilterText: def show_extracted_data_from_file(self): def show_extracted_data_from_file(self): verdi_cost = [3588.20, 5018.75,3488.16] regexes = [verdi_cost] matches = [(regex) for regex in regexes] columns = ["kosten fruit"] return mark_safe( tabulate( zip_longest(*matches), # type: ignore headers=columns, tablefmt="html", stralign="center", ) ) excel data: from django.utils.safestring import mark_safe from tabulate import tabulate class ExtractingTextFromExcel: def init(self): pass def extract_data_excel_combined(self): dict_fruit = {"Watermeloen": 3588.20, "Appel": 5018.75, "Sinaasappel": 3488.16} columns = ["naam fruit", "totaal kosten fruit"] return mark_safe( tabulate( dict_fruit.items(), headers=columns, tablefmt="html", stralign="center" ) ) So I want to compare the values from the excel data and the values from the pdf data. and the views.py: def test(request): filter_excel = ExtractingTextFromExcel() filter_text = FilterText() content_excel = "" content_pdf = "" content_pdf = filter_text.show_extracted_data_from_file() # type:ignore content_excel = filter_excel.extract_data_excel_combined() context = {"content_pdf": content_pdf, "content_excel": content_excel} for ((fruit, a), b) in zip(content_excel, content_pdf): if (a, b): return fruit return render(request, "main/test.html", context) and the template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Create a Profile</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="{% … -
View admin page if the log in user is admin in Django
I am doing a Django project. If the user is admin, then the admin will view the admin-profile page after logging in. But if the user is researcher, then the researcher can view the researcher-profile page after logging in. django_project/settings.py LOGIN_REDIRECT_URL = 'researcher-profile' blog/views.py from django.shortcuts import render from .models import Post, Category from django.views.generic import ListView from django.contrib.auth.mixins import LoginRequiredMixin from .forms import PostForm # get all posts of the logged in user class UserPostListView(LoginRequiredMixin, ListView): model = Post # query the post model to create the list of articles template_name = 'blog/researcher-profile.html' context_object_name = 'posts' ordering = ['-created'] def get_queryset(self): return Post.objects.filter(author = self.request.user) researcher-profile.html {% extends 'users/base.html' %} {% block content %} {% for post in posts %} {% if post.approved %} <div class="card mb-3"> <img class="card-img-top" src="{{ post.image.url }}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{ post.title|truncatechars:70 }}</h5> <p class="card-text">{{ post.content|truncatechars:200|safe }}</p> <a href="{% url 'post-detail' post.aid %}" class="btn btn-primary"> See Details </a> </div> <div class="card-footer text-secondary"> <a class="mr-2" href="{% url 'researcher-profile' %}">{{ post.author }}</a>|| {{ post.created|date:"F d, Y" }} </div> </div> {% endif %} {% endfor %} {% endblock content %} admin-profile.html {% extends 'users/base.html' %} {% block content %} <h1> Admin Post Apporval Portal</h1> … -
I want to add flag field to users in User model(inbuilt) to manage account as active and deactivate in django
J want to change users flag field to disable,how to manage user profiles by flag field. Adding flag field by Boolean and manage accounts as active state and de activated state. -
Django, Nginx, and Docker. DEPLOYMENT
I want to deploy my app which is made by django and flutter and i have used docker to dockerize the django and the nginx. Here what i has so far and what should i add or change: docker-compose.yaml: version: '3.8' services: api: build: context: ./api command: gunicorn myproject.wsgi:application --bind 0.0.0.0:8000 volumes: - ./api:/app/ - static:/app/static/ expose: - 8000 depends_on: - db db: image: postgres:latest volumes: - data:/var/lib/postgresql/data/ server: build: context: ./server volumes: - static:/app/static/ - media:/app/media/ - certs:/etc/nginx/certs ports: - 443:443 - 80:80 certbot: image: certbot/certbot depends_on: - api volumes: data: static: media: certs: dockerfile (django): FROM python:latest ENV SECRET_KEY 123 ENV DATABASE_PASSWORD postgres ENV DEBUG 0 RUN mkdir /app WORKDIR /app COPY . . RUN pip install --upgrade pip RUN pip install -r requirements.txt RUN python manage.py collectstatic --no-input dockerfile (nginx): FROM nginx:latest RUN mkdir /server RUN rm /etc/nginx/conf.d/default.conf COPY ./nginx.conf /etc/nginx/conf.d/ WORKDIR /server nginx.conf: server { listen 80; server_name mydomain.com return 301 https://$server_name$request_uri; location / { proxy_pass http://server; } location /static/ { alias /server/static/; } } server { listen 443 ssl; server_name mydomain.com; } Thanks for your time I have tried searching online but i couldn't find much answers -
How to change the size of UserCreationForm?
I wanna modify the weight of the fields in UserCreationForm. How ist that possibly? class SignUpForm(UserCreationForm): username = forms.CharField( widget=forms.TextInput(attrs={ "class": "input", "type": "text", "placeholder": "Username", }) ) email = forms.CharField(widget=forms.TextInput(attrs={ "class": "input", "type": "email", "placeholder": "Email" })) password1 = forms.CharField(widget=forms.TextInput(attrs={ "class": "input", "type": "password", "placeholder": "Password" })) password2 = forms.CharField(widget=forms.TextInput(attrs={ "class": "input", "type": "password", "placeholder": "Password" })) class Meta: model= User fields = [ "username", "email", "password1", "password2" ] I wanna modfy the size of the fields: Username, Email, Password1 and Password2 More precisely, I want the fields longer -
How to Optimize a loop "For" in Django
I want to optimize this functions, because they take too long, each of them bring specific atributes, if you can help me. I think there's maybe a way to call the atributes in the function. The functions are made with python and Django. This is what i've done so far. Definition of the functions. cand_seleccionados = ListaFinal.objects \ .filter(interesado__id_oferta=efectiva.oferta.id) seleccionados_ids = cand_seleccionados.values_list('interesado_id', flat=True) cand_postulados = Postulados.objects \ .filter(interesado__id_oferta=efectiva.oferta.id) \ .exclude(interesado_id__in=seleccionados_ids) postulados_ids = cand_postulados.values_list('interesado_id', flat=True) cand_entrevistados = Entrevistados.objects \ .filter(interesado__id_oferta=efectiva.oferta.id) \ .exclude(interesado_id__in=postulados_ids) This is the loop for cand_Postulados, the others are the same so i thought it wouldnt be necesary to put more for p in cand_postulados: postulado = dict() telefono = Perfil.objects \ .values_list('telefono', flat=True) \ .get(user_id=p.interesado.candidato.id) postulado['id'] = p.interesado.candidato.id postulado['nombre'] = p.interesado.candidato.first_name postulado['email'] = p.interesado.candidato.email postulado['teléfono'] = telefono if p.interesado.id_oferta.pais is None: postulado['pais'] = "Sin pais registrado" else: postulado['pais'] = p.interesado.id_oferta.pais.nombre postulado['nombre_reclutador'] = p.interesado.id_reclutador.first_name postulado['id_reclutador'] = p.interesado.id_reclutador.id postulados.append(postulado) -
Deploying Django Postgres to Digital Ocean Droplets
I have to deploy a Django API to Digital Ocean, a service that should scale a bit over the next year. I also need a database to save all the data from the users, and I will use Postgres. Recently I saw a lot of video tutorials, official guides from the digital ocean and so on that tell us to use the Postgres that you install on the Droplets "locally" as the database, so install locally postgres and put there all the data. It actually can make sense since the droplet I will pay for is about 25 GB that I will never really reach. So, my question was if this approach makes sense at all, or is way better to set up right now a different possibility, like a database on the digital ocean itself? If I keep these settings, will I be able to easily migrate in the future? Or will it be painful if not impossible? Is there a very good cost-efficient way to do this, or this solution is good enough even for a platform that needs to scale (let's say 100,000 users and a really high amount of requests for each one of them at … -
How to add email to be able to log in via Google oauth Django
I'm building a Django project and I have 3 applications. Students log in to complete the given items. Teachers log in to manage the list of student actions. Administrators manage permissions and logins. Administrators will add student and teacher email addresses. to check that only the added email will be able to log in and my project is using only google oauth login, can anyone guide me what i need to do? If you want an admin to add an email address And only the added email will be able to login. what i tried views.py def admin_user_setting(req): if req.method == "POST": email_user = req.POST.get('email_user') obj = Add_User_Email_User(email_user=email_user) obj.save() return redirect('/admin_user_setting') else: obj = Add_User_Email_User() obj = Add_User_Email_User.objects.all() AllUser = Add_User_Email_User.objects.all() page_num = req.GET.get('page', 1) p = Paginator(AllUser, 10) try: page = p.page(page_num) except: page = p.page(1) context = { "AllUser": Add_User_Email_User.objects.all(), "page" : page, } return render(req, 'pages/admin_user_setting.html', context) urls.py urlpatterns = [ path('admin_user_setting',views.admin_user_setting, name="admin_user_setting"), ] forms.py class UserForm(ModelForm): class Meta: model = Add_User_Email_User fields = ['email_user'] admin.py admin.site.register(Add_User_Email_User) models.py class Add_User_Email_User(models.Model): email_user = models.CharField(max_length=500, null=True) def __str__(self): return self.email_user -
I want to make a subscription system with django
How can I make an auto incrementing timer, for example, it will count forward 1 year from now and these transactions will be saved in the database. -
How to check django login status in JavaScript?
What is the best way to check django user is authenticated in JavaScript file?