Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any reliable way to get the data from PostgreSQL according to the user interest in the Django Rest Framework?
Our Project is similar in functionality to Twitter We want to show the posts on the feed according to the user's interest based on the user's likes, shares, and comments on the posts how and where we can save the user's activities? how we can filter and get the post data using the Django QuerySet and DRF paginations for a user how we can sort the post data with the recent + interest-related data if there is any better approach that exists, then please share some details about it. Thanks in Advance! -
multiple serializers in a single ListAPIView
I have a APIView where i list the data and the same displayed data can be exported to XLS file or pdf file apart from the data which uses the same serializer fields to be displayed on the file. now i am adding a couple of new fields which needs to be on file but not displayed on website, I want to create a new serializer with all the fields along with couple of new fields for exporting them to the file ExportSerializer. class MyDataListAPIView(ListExportMixin, ListAPIView): serializer_class = MySerializer permission_classes = [IsAuthenticated] pagination_class = StandardResultsSetPagination filter_backends = (filters.OrderingFilter,) queryset = MyModel.objects.all() ordering = '-created' ordering_param = 'ordering' export_fields = ( 'number', 'issue_date_formatted', 'due_date_formatted', 'hearing_date', 'status', 'total_amount_formatted', 'amount_received_formatted', 'balance_formatted', 'unapplied_amount_sum_display', 'firm', 'last_past_due_sent_on_formatted', 'fee_amount_formatted', 'payments_formatted', ) column_header = { 'titles': [ ], 'header_title': 'Statement of Services Rendered' } I want Myserializer to be used to list the data but i want the other serializer called SecondSerializer just for exporting how can i achieve that when i am exporting the data to file i need to use SecondSerializer but when i want to just list i need Myserializer mentioned in the view -
Running LibreOffice calc inside Django website
Looking for a way to run / open an xlsx file with plots as is - inside Django. any suggestion will be consider. -
Accept physical payments for a web application
I have a building bussiness and the web application on Django related to it, does anyone know how is it possible to accept physical payments via POS terminal after interaction with a website? -
How to retain two forms data in the same view/template/page?
I have two forms and two views using the same profile.html template. When I GET/POST to the ProfileUpdateView, all of the users profile data is present. However, when I post to UserDeleteView and not select the "accountActivation" box the page renders but the user profile data which is above is empty. # urls.py from django.contrib import admin from django.urls import include, path from apps.iam.views import ProfileUpdateView, UserDeleteView urlpatterns = [ path("accounts/profile", ProfileUpdateView, name="profile_detailupdate"), path("accounts/delete", UserDeleteView, name="user_delete"), ] """ # views.py import zoneinfo from django.contrib.auth import get_user_model from django.contrib.auth import logout as auth_logout from django.contrib.auth.decorators import login_required from django.shortcuts import HttpResponseRedirect, get_object_or_404, render from django.utils import timezone from django.views.decorators.http import require_http_methods from django.views.generic import TemplateView, UpdateView from .forms import ProfileForm from .models import Profile User = get_user_model() # Homepage class HomeDetailView(TemplateView): template_name = "home.html" # Profile ## Update @login_required @require_http_methods(["GET","POST"]) def ProfileUpdateView(request): # dictionary for initial data with field names as keys context = {} # fetch the object related to passed id profile_object = get_object_or_404(Profile, id=request.user.id) # pass the object as instance in form profile_form = ProfileForm(request.POST or None, instance=profile_object) # save the data from the form if profile_form.is_valid(): profile_form.save() # add form dictionary to context context["profile_form"] = profile_form # … -
Update python 3.5 to 3.9 or 3.10 in my remote server
I have an application with django 4.1 locally, I wanted to deploy it online in my ovh Cloud server. however I can't update python on this remote server which uses version 3.5.8 (this version is old) and when I create an online django application I have version 2.2.28 How to update it? see screenshot -
Django REST multipart data converted to string
Passing a JSON + image data to a post endpoint, ends in converting part of request data to string. The part which is converted to string contains the file as well. Here is the input data: data = { "external": "90000001", "sales": [ { "total": 4, "quantities": {"xs":2, "s":4}, "product": { "type": self.type.id, "product_image": { "name": "First test files", "product_files": [ { # "file": base64.b64encode(f.read()).decode(), "file": test_file, "description": "Patterns file.", "type": "pattern_file", } ] }, }, } ], } I am sending request to my endpoint in the test in this way: res: Response = self.client.post(self.create_ext_so_url, data) It returns an error: rest_framework.exceptions.ValidationError: {'sales': [ErrorDetail(string='Must specify at least one sales', code='blank')]} Here is the sales data extracted in the run_validation(...) attrs.get("sales", []) "{'total': 4, 'quantities': {'xs': 2, 's': 4}, 'product': {'type': 1, 'product_image': {'name': 'First test files', 'product_files': [{'file': <SimpleUploadedFile: test.svg (image/svg+xml)>, 'description': 'Patterns file.', 'type': 'pattern_file'}]}}}" Here it is visible that the sales in converted to string and later it won't be available as an object/dictionary and the object won't be created, which makes it fail the test. Here is the view if someone wants to check it. @action(detail=False, methods=["POST"], url_path="create-sales") def create_sales_order(self, request: Request)-> Response: ser_class = self.get_serializer_class() ser … -
Nginx service of type LoadBalancer vs ingress (using nginx-ingress) vs ingress + nginx service of type ClusterIP
We are moving from standalone docker containers architecture to K3s architecture. The current architecture uses a Nginx container to expose multiple uwsgi and websocket services (for django). I'm reading conflicting opinions on the internet over what approach should be used. The options are: Nginx service of type LoadBalancer (Most conf from existing architecture can be reused) Nginx-ingress (All conf from existing architecture will have to be converted to ingress annotations and ConfigMap) Nginx-ingress + nginx service of type ClusterIP (Most conf from existing architecture can be reused, traffic coming into ingress will simply be routed to nginx service) -
Filter objects based on token expiry date and user date_joined using Q and "gt" Django
I want to delete users that haven't activated their accounts when the activation token have expired, activation token expires after 30 minutes. from django.db.models.functions import Now def delete_unactivated_users(): User = get_user_model() expiry = User.date_joined + timedelta(seconds=1800) unactivated_users = User.objects.filter(Q(Now()__gt=expiry) & (Q(is_active = False))) for user in unactivated_users: user.delete() print('<<<User Deleted>>>') user.save I am getting a syntax error on line 5 of the code, I tried using unactivated_users = User.objects.filter(Q(expiry__lt=Now()) & (Q(is_active=False))) but it didn't result in the same meaning. The problem seems to be the placing of Now() and expiry on line 5 -
How we can get the updated data by refreshing the cache using the cache_page in DRF with the same route?
The website is similar in functionality to Twitter and we're using a Django caching mechanism for the feed but when the user created his post he is not able to find his post for the next 10 minutes due to the caching and we want to show the latest results to the user so, how we can show the latest data to the user after creating his post using the same route Here is the urls.py code from django.views.decorators.cache import cache_page from . import views CACHE_TIME=60*10 urlpatterns = [ path('', cache_page(CACHE_TIME)(views.PostListAPIView.as_view()), name="post-list") ] if I call the API --> http://127.0.0.1:8000/v1/posts/ then data will be stored in the cache for the next 10 minutes but I want to refresh after the specific event so, how can I get the updated data before the 10 minutes also, I have found a solution for it if we pass http://127.0.0.1:8000/v1/posts/?{username}=true then we can get the latest data for the user but is there any other better approach or possibility to show the latest data? if yes, then please list the method and some details about it -
Merging multiple migration files into a single migration file in Django
I have multiple migration files in an app. I want to merge all those migration files into a single file using squash command. I want to how to handle circular dependency issue. -
Can I access the child model from the parent?
I have created a productForArt and albomForArt model From producForArt I inherit to albomForArt Making a view based on generic.ListView And I output it in the template, Can I access the number Of Pages field in the template albomForArt models, or in this case Django returns an object of the albomForArt model, but with properties that were inherited from albomForArt? models from django.db import models class productForArt(models.Model): class Meta: verbose_name = u'товар' verbose_name_plural = u'товары' price = models.IntegerField(verbose_name="цена", default=0) title = models.CharField(max_length=300, verbose_name="название товара", null=True) description = models.CharField( max_length=1000,verbose_name="Описание товара", null=True) type = models.ForeignKey('typeProductForArt', on_delete=models.PROTECT) def getType(self): return self.type def __str__(self): return str(self.title) + ' по цене' + str(self.price) + ' шт' class albomForArt(productForArt): numberOfPages = models.IntegerField(default=10,verbose_name="количество станиц" ) class typeProductForArt(models.Model): title = models.CharField(max_length=200, default="none") def __str__(self): return self.title vievs from django.views import View, generic from .models import productForArt class startPage(generic.ListView): model = productForArt template_name = "startPage.html" context_object_name = "productForArt_list" queryset = productForArt.objects.all()[:20] templates {% if productForArt_list %} <section class="productsStartpage"> {% for productForArt in object_list %} <article class="productForArtStartpage"> <h1>{{productForArt.title}}</h1> <p>{{productForArt.description}}</p> {% endif %} </article> {% endfor %} </section> {% else %} <p>товара нету</p> {% endif %} -
Multi screen user input in Django to create one composite order
I am designing a consumer app and I will be writing it in Django. What I would like to be able to do is over a series of templates/screens accept user input. The input from one screen will be relevant to subsequent screen and should be available to the javascript and html in these subsequent screens e.g. I have one lead screen where you choose a type of 1, 2 or 3 and depending on that the javascript on the following screen controls how many pins a user is allowed to drop on a map. At the end of the last user input screen I would like to create an order with a status of ‘payment pending’ with all of the user variables stored on it and then go to a payment screen, and if there is a successful payment set the order to a status of ‘ready to process’. I have looked at some video tutorials about building an e-commerce aplication and read some online resources and I wondered is a ‘context’ the way to do this of is another method such as a session variable or is there another recommended method. Also, is best practice to wait to … -
How to prevent data tampering when form is set as readonly with Django?
INTRO: I have a Django web app which does the following: Allows the user to fill the form After the form is submitted, it shows the form with the previously filled values In step 2, the form fields are set as read-only because they should not be modified. So in my views.py file I have the following information: def insert_data(request): # Get the form from a previous post request (coming from step1) form_one_item = ProductForm(request.POST, request.FILES) # Set the fields as readonly (this is step 2) form_one_item.fields['name'].widget.attrs['readonly'] = True return render(request, 'mypage.html', {'form_one_item':'form_one_item'}) The form therefore looks like this: and it is supposed to be resubmitted through another post request (I know it is confusing but I need to do so). PROBLEM: At first glance, it looks like it is all fine but then I noticed that I can right-click on the field and modify its content: As a matter of fact if I repost the readonly form, the value shown is modified according to what I write into the value field. QUESTION: Are you able to suggest a possible way to keep the readonly option but at the same time to avoid to pass a modified value once I … -
selenium + python + django - web driver locally but not after deployment
When i run app locally this error does not appear ,it appears when i run the live version on heroku Error from heroku :raise WebDriverException( selenium.common.exceptions.WebDriverException: Message: Service /app/.wdm/drivers/chromedriver/linux64/106.0.5249/chromedriver unexpectedly exited. Status code was: 127 from selenium import webdriver from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time import os import requests from pathlib import Path from twilio.rest import Client from webdriver_manager.chrome import ChromeDriverManager account_sid = '' auth_token = '' client = Client(account_sid, auth_token) def download_path(path:str): """add download path """ try: file = open("down_path.txt","w") file.write(path) file.close() except: print("cannot write path") def download(song, artist = None, play_after_downloading = True): """Downloads the video to given directory""" try: file=open("down_path.txt") down_path=file.read() down_path=down_path.strip() file.close() except: down_path = os.getcwd() print("It will not take more than 1 minute if your download speed is good") if artist: song=song+ ' by ' +artist video=song chromeOptions=Options() chromeOptions.add_experimental_option("prefs",{"download.default_directory":down_path}) chromeOptions.add_argument("--headless") #service = Service(executable_path=ChromeDriverManager().install()) #driver = webdriver.Chrome(service=service) driver = webdriver.Chrome(ChromeDriverManager(path=os.getcwd()).install(),options=chromeOptions) wait=WebDriverWait(driver,3) presence = EC.presence_of_element_located visible = EC.visibility_of_element_located driver.get("https://www.youtube.com/results?search_query=" + str(video)) ads =True wait.until(visible((By.ID, "video-title"))) try: driver.find_element(By.XPATH,"//span[contains(@class,'style-scope ytd-badge-supported-renderer') and text()='Ad']") except Exception as e: ads=False if ads: vid = driver.find_element(By.ID,"video-title") vid.click() … -
Django CRUD works but wrong path
@login_required(login_url='/users/login') @permission_required('users.change_user', login_url='users/login') def edit(request, profile_id): try: user = User.objects.get(pk=profile_id) except User.DoesNotExist: raise Http404("Profile does not exist") return render(request, 'UI/edit.html', {'users': user}) def processedit(request, profile_id): user = get_object_or_404(User, pk=profile_id) profile_pic = request.FILES.get('image') try: fname = request.POST.get('fname') lname = request.POST.get('lname') email = request.POST.get('email') position = request.POST.get('position') except (KeyError, User.DoesNotExist): return render(render, 'UI/detail.html', {'user': user, 'error_message': "Problem updating record"}) else: user_profile = User.objects.get(id=profile_id) user_profile.user_fname = fname user_profile.user_lname = lname user_profile.user_email = email user_profile.user_position = position if profile_pic: user_profile.user_image = profile_pic user_profile.save() return HttpResponseRedirect(reverse('users:detail', args=(profile_id,))) from views.py here from edit.html {% extends 'base.html' %} {% block title %} {{ user.user_fname }} {{ user.user_lname }} {% endblock %} {% block content %} {% if error_message %} <p class="alert alert-danger"> <strong>{{error_message}}</strong> </p> {% endif %} <h1> Edit User Profile</h1> <form action="{% url 'users:processedit' user.id %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label>First Name</label> <input type="text" name="fname" id="fname" class="form-control" required value="{{ users.user_fname }}"> </div> <div class="form-group"> <label>Last Name</label> <input type="text" name="lname" id="lname" class="form-control" required value="{{ users.user_lname }}"> </div> <div class="form-group"> <label>Email</label> <input type="text" name="email" id="email" class="form-control" required value="{{ users.user_email }}"> </div> <div class="form-group"> <label>Position</label> <input type="text" name="position" id="position" class="form-control" required value="{{ users.user_position }}"> </div> <div class="form-group"><br> <label>User Image</label><br><br> <input type="file" name="image" id="image"> </div> <br> <button … -
'QuerySet' object has no attribute 'id'
I was building a django project in that I need to create an edit option for a particular model named SchoolDetail. But while fetching the data from this table using id, its showing the above error views.py def SchoolPage(request): school_details = SchoolDetail.objects.all() school_details_pk = school_details.id context = {'school_details': school_details, 'school_details_pk':school_details_pk} return render(request, 'busschool.html', context) models.py class SchoolDetail(models.Model): school_name = models.CharField(max_length=100, blank= True, null=True) school_place = models.CharField(max_length=100, blank= True, null=True) school_email = models.CharField(max_length=100, blank= True, null=True) school_address = models.CharField(max_length=100, blank= True, null=True) school_phone = models.CharField(max_length=15, blank= True, null=True) is_verified = models.BooleanField(default=False) def __str__(self): return self.school_name template enter code here <tbody> {% for i in school_details %} <tr> <td>{{i.school_name}}</td> <td>{{i.school_place}}</td> <td>{{i.school_email}}</td> <td>{{i.school_address}}</td> <td>{{i.school_phone}}</td> <td>{{i.is_verified}}</td> <td><a href="{% url 'schooledit' school_details_pk %}">click</a></td> </tr> {% endfor %} <tbody> -
Keyerror at file in Python Django
KeyError at /file/ It's working on 25% but when I select 50% or 75% it gives this error. Please help. My website https://summarizingtool.org. Keyerror -
Tagged Duplicate Entries After user submits the form Django
can someone help me figure out... I would want to automatically trigger in database if the entries that was posted by a different user is a possible duplicate. if entries like date, time and location are the same... how can I do this? Thank you -
Django - How to force server time on DateTimeField?
I have a datetime field on a model date_time = models.DateTimeField(auto_now_add=True, blank=True, null=True) I need it to be as server time, the problem is when i change local time on pc the field created with the modified time and date. Is it because my server is local (for dev) or is it how datetimefield field works? Thanks! -
Django dumpdata generating
I have a question how to generate dumpdata without this txt on start: [1mLoading .env environment variables...[0m Here is an example: [1mLoading .env environment variables...[0m [ { "model": "auth.permission", "pk": 1, "fields": { "name": "Can add permission", "content_type": 1, "codename": "add_permission" } }, .... I can't find solution, it is annoying, because i want to do a sh script docker-compose exec django pipenv run python manage.py dumpdata --indent 2 > fixtures/test_dumpdata.json Thanks for all help. -
Scheduled tasks in Django to update data in the models (database)
I need to schedule tasks via Pythonanywhere, to update some records in my database. As an example, I do have Events as models: models.py class Events(models.Model): event_title = models.CharField(max_length=300) event_info = models.TextField(max_length=2000) event_date = models.DateField(default=now) event_time = models.TimeField(default='00:00') event_location = models.CharField(max_length=150) event_status = models.CharField(max_length=30, choices=EVENT_STATUS_CHOICES, default='New Event') Also within that Events class in models.py I have the following: def save(self, *args, **kwargs): if date.today() > self.event_date: self.event_status = 'Completed Event' super(Events, self).save(*args, **kwargs) Thanks to that, all events in the past, change their status to Completed. Problem is, you need to refresh the page to have the save function run on the production website. It also drives some other functions, e.g. showing the user the count of active events - this one as well, in order to show the right active number of events, has to be refreshed manually. By scheduling tasks in PA to run overnight, iterating through all Events, and if in the past, changing their status. I created the below file and uploaded it to PA Tasks. tasks.py from .models import Events from datetime import date def verify_events(): all_events = Events.objects.all() for event in all_events: if event.event_date < date.today(): event.event_status = 'Completed Event' event.save() I got an … -
Can i use both django autofield and foreignkey on one field?
so i have specific use case currently the database has a table with one field that acts as both primary key and foreign key (and i have no access to change this as it would break other processes) so what i tried with the models is something like this: class Foos(models.Model): foo_id = models.AutoField(primary_key=True) foo_name = models.CharField(max_length=15) foo_dt = models.DateTimeField() class Bars(models.Model): bar_id = models.AutoField(primary_key=True) bar_id = models.ForeignKey(Foos, db_column='bar_id', on_delete=models.CASCADE, blank=True, null=True, related_name='bars') bar_qty = models.IntegerField() bar_image = models.ImageField() That didn't work as django will keep the last bar_id (the foreignField) and ignore the AutoField, the thing is i need the foreign key to do some reverse lookup like Foos.object.values(bars__bar_qty) so i can get the left outer join query. But someone else need the AutoField. I know django is really strict on it but is there a possible solution? i just need to keep the reverse lookup i am fine with autofield if it is possible but the thing is django return an error not permitted. -
My if statement doesn't work with two str
i'm trying to use Django to build a wikipedia like. When I want to search an article, i type the research in the search input. I collect my research in my views.py in a function. I have a list of different entries stores in the wiki. But when i try to compare with an if statement if the content of the request is in my list, automatically, the case is false. below my silly function just for testing what's happened def search(request): request_dict = json.dumps(request.GET) print(request_dict, type(request_dict)) request_dict = json.loads(request_dict) print(request_dict, type(request_dict)) title = request_dict["q"] print(title, type(title)) for item in util.list_entries(): print(item, type(item)) title = title.casefold() print(item.casefold().encode("utf-8"), title.encode("utf-8")) if item.casefold().encode("utf-8") == title.encode("utf-8"): entry(request, item) else: print("ko") pass and this is the print in my terminal {"q": "html"} <class 'str'> {'q': 'html'} <class 'dict'> html <class 'str'> CSS <class 'str'> b'css' b'html' Django <class 'str'> b'django' b'html' Git <class 'str'> b'git' b'html' HTML <class 'str'> b'html' b'html' Python <class 'str'> b'python' b'html' ko how can i fix that? I know that here json.loads and dumps here doesn't do anything more than request.GET["q"]. I'm so disappointed and try everything that i could to fix this bug -
Django get users who have updated their age field in the last 1 day
How can I get users who do not update their age information in last 1 day? I need to use Django ORM. not For loop. I tried something in the second code block but without success. You can tell by looking at what I've done from simple_history.models import HistoricalRecords class User(AbstractUser): age = models.IntegerField() history = HistoricalRecords() ################################################################################ date_start = timezone.now() - timezone.timedelta(days=1) queryset = User.history.filter(history_user_id__in=users,history_date__lte=timezone.now(),history_date__gte=date_start).annotate( lag=Window( partition_by=[F("id")], expression=Lag("age"), order_by=[F("history_date")], ) ) here what i have to do is compare lag with age and see if it is updated