Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem with starting a Django project in current directory?
I am trying to start a django project in my current directory. Online I found this command as a solution: django-admin startproject . ^(Also the command used by my lecturer in one of his videos) However when I enter this into my terminal I get: CommandError: '.' is not a valid project name. Please make sure the name is a valid identifier. Edit: The command works fine if I give it a valid project name and creates a new directory with the project. The '.' from my understanding is meant to signify that the project should be started in the current directory, so I don't understand why it is treating it as a name -
Django Integrity Error 1048 cannot be null
Under views.py def addcomments(request): comment_text = request.POST.get('comment') user_id = request.POST.get('user_id') name = request.POST.get('name') email = request.POST.get('email') comment = Comment.objects.create(user_id=user_id, body=comment_text, name=name, email=email) comment.save() return HttpResponseRedirect(reverse('users:detail', args=(user_id, ))) this one, from detail.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 %} <div class="row"> <div class="col-lg-6"> <div class="mb-5"> <h1>{{ user.user_fname }} {{ user.user_lname }}</h1> <p class="text-muted">{{ user.user_email }}</p> <p>Position: {{ user.user_position }}</p> </div> <div class="img-responsive"> <img src="/users/media/{{user.user_image}}" alt="profile_user" class="img-rounded" width="300"> <!-- ito yung hinahanap ng search engine--> </div> <div class="btn-group mt-5"> <a href="{% url 'users:delete' user.id %}" class="btn btn-sm btn-danger">Delete</a> <a href="{% url 'users:edit' user.id %}" class="btn btn-sm btn-info">Edit</a> <a href="{% url 'users:index'%}" class="btn btn-sm btn-success">Back</a> </div> </div> <div class="col-lg-6"> <h2>Comment</h2> <p class="text-muted"> Number of comment : {{ comments_count }}</p> {% if comments_count > 0 %} {% for comment in comments %} {% if comment.active %} <p><strong>{{comment.name}}</strong> : {{comment.body}}</p> {% endif %} {% endfor %} {% endif %} <hr> <br><br><br><br><br><br> <form action="{%url 'users:addcomments'%}" method="post"> {% csrf_token %} <div class="form-group"> <label>Comment</label> <textarea name="comment" id="comment" cols="30" rows="5" class="form-control" required placeholder="Enter your comment here ..."></textarea> </div> <br> <input type="text" name="name" id="name" … -
'Posts_update' object is not iterable in django
i am just try to get data from db table and show on detail page but i am getting error -'Posts_update' object is not iterable. I have two tables posts and posts_update. in posts table i am doing CRUD operation and on each update i am adding information in posts_update table now i am trying to get information from posts_update table using mobile as a parameter but i am getting error -'Posts_update' object is not iterable. models.py from django.db import models class Posts(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(unique=True) content = models.TextField() mobile = models.CharField(max_length=15,default='') class Posts_update(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(unique=True) content = models.TextField() mobile = models.CharField(max_length=15,default='') urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('create/', views.create, name='create'), path('detail/<int:post_mobile>', views.read, name='detail'), path('delete/<int:post_id>', views.delete, name='delete'), path('update/<int:post_id>', views.update, name='update') ] views.py from django.shortcuts import render, redirect from django.template.defaultfilters import slugify from django.http import HttpResponse from django.contrib import messages from .models import Posts from .models import Posts_update def index(request): posts = Posts.objects.all() return render(request, 'index.html', { 'posts': posts }) def create(request): if request.POST: req = request.POST post = Posts(title=req.get('title'), slug=slugify(req.get('title')), content=req.get('content'), mobile=req.get('mobile')) post.save() messages.success(request, 'The record was saved successfully') return redirect('/') else: return render(request, … -
Custom User Model, Custom Authentication not working
I am a beginner in Django and I am working on a project which requires Custom user model as I Don't require is_staff, is_superuser, is_admin. So, but searching and other ways I made my own Custom user model. But it is not working and I am stuck on it for days. It will be a huge help if someone can help me with the code. settings.py AUTH_USER_MODEL = 'accounts.Usermanagement' AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'accounts.backends.EmailAuthBackend', ] models.py (models + manager) #models.py class UsermanagementCustomUserManager(BaseUserManager): # create_user(username_field, password=None, **other_fields) def create_user(self,emailid,roleid,organizationid,firstname, password=None, passwordexpirydate="2022-12-12 12:00:00",createdby=0,modifiedby=0): """ Creates and saves a User with the given email, date of birth and password. """ if not emailid: raise ValueError('Users must have an email address') user = self.model( emailid=self.normalize_email(emailid), roleid = roleid, organizationid=organizationid, firstname = firstname, password=password, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,emailid,roleid,organizationid,firstname,passwordexpirydate,password=None,createdby=0,modifiedby=0): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( emailid=emailid, roleid = roleid, organizationid=organizationid, firstname = firstname, password=password, passwordexpirydate=passwordexpirydate, ) user.save(using=self._db) return user class Organization(models.Model): organizationid = models.AutoField(db_column='OrganizationID', primary_key=True,blank=True) organizationname = models.CharField(db_column='OrganizationName', max_length=45,blank=True) def __str__(self): return self.organizationname class Meta: managed = False db_table = 'Organization' class Role(models.Model): roleid = models.AutoField(db_column='RoleID', primary_key=True,blank=True) organizationid = models.ForeignKey(Organization, … -
django-autotranslate doesn't install, returns Preparing metadata (setup.py) ... error during installation
I'm trying to install django-auto translate but it keeps telling me: Preparing metadata (setup.py) error error: subprocess-exited-with-error i've also tried older versions of the package and i keep getting errors concerning metadata setup, how can i go about this? Input: pip install django-autotranslate Output: #cmd execution after running :pip install django-autotranslate Collecting django-autotranslate Using cached django_autotranslate-1.2.0-py3-none-any.whl (10 kB) Collecting six Using cached six-1.16.0-py2.py3-none-any.whl (11 kB) Collecting goslate Using cached goslate-1.5.4.tar.gz (14 kB) Preparing metadata (setup.py) ... done Collecting polib Using cached polib-1.1.1-py2.py3-none-any.whl (20 kB) Requirement already satisfied: django in c:\users\vyktor\dev\language-translator\venv\lib\site-packages (from django-autotranslate) (4.1.2) Requirement already satisfied: sqlparse>=0.2.2 in c:\users\vyktor\dev\language-translator\venv\lib\site-packages (from django->django-autotranslate) (0.4.3) Requirement already satisfied: tzdata in c:\users\vyktor\dev\language-translator\venv\lib\site-packages (from django->django-autotranslate) (2022.5) Requirement already satisfied: asgiref<4,>=3.5.2 in c:\users\vyktor\dev\language-translator\venv\lib\site-packages (from django->django-autotranslate) (3.5.2) Collecting futures Using cached futures-3.0.5.tar.gz (25 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [27 lines of output] -
Python web app form generates excel or pdf after submit
So I have this questions and answers form in a web application, most questions are input based, there are some that are checkbox, list or a date, but most are text/number input. I want that after the submit button it generates a link to download or downloads directly after the file is written. I cannot seem to find this answer anywhere and I'll gladly appreciate some help. Code is written as Django form with python. -
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