Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display an error message with a function?
I want to create a basic function for payment. I have several cards and when the user click the button, if the card did not receive a payment this month, it should be refilled, but if did receive a payment this month I want to display an error message in the front end. How can I do it? views.py def paycheck(request, id): card = Card.objects.get(id=id) today = format(datetime.date.today() - datetime.timedelta(days=1), '%B %Y') if card.last_payment != today: if card.type == "City": card.amount = 500 else: card.amount = 300 card.last_payment = today card.save() else: print("Some error message for client") return redirect(request.META['HTTP_REFERER']) def card(request, id): card = Card.objects.get(id=id) restaurants = Restaurants.objects.filter(is_member=True) logs = CardLogs.objects.filter(card_id=id) context = { 'card': card, 'restaurants': restaurants, 'logs': logs } return render(request, "card.html", context) card.html ... <a class="btn btn-success" href="{% url 'paycheck' card.id %}" > Make Payment </a> ... -
save large json objects in postgres, Django
I have a model in db: class Test(models.Model): title = models.CharField(max_length=32, verbose_name='title', default='') json = models.JSONField(default=dict) ... I get the data from the front and save it to the db, requests come in quite often. The average weight of a json field is 10MB, but it can vary greatly and I don’t understand how it would be better for me to save and give it, I don’t do any work with json on server. To begin with, I think need to compress this json and save it to the database and, when requested to receive it, decompress it. Can you please advise me on the best way to save memory and query execution time. Also, is it worth removing this json in a separate table so that changing other data in the test table takes less time, or is it better to use Test.objects.update()? -
Why the login_required decorator doesn't work?
Working on a simple project using Django 3.2 and the loqin_required decorator is not working. When I close the server and re-open it again, it works the first time but not anymore. It used to work very well, but I'm not sure what I changed in the code that it doesn't work anymore. views.py from django.http.response import HttpResponse from django.shortcuts import render, redirect from django.utils import timezone from django.db.models import Count from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.contrib import messages from .models import * from .models import __str__ from .forms import CreateUserForm # Create your views here. @login_required(login_url='login/') def home(request): count_item = todo.objects.count() all_items = todo.objects.all().order_by("created") context = {'all_items': all_items, 'count_item':count_item} return render(request, 'html/home.html', context) @login_required(login_url='login/') def add_todo(request): current_date = timezone.now() new_item= todo(content = request.POST["content"]) new_item.save() return redirect('/') @login_required(login_url='login/') def delete_todo(request, todo_id): item_to_delete = todo.objects.get(id=todo_id) item_to_delete.delete() return redirect('/') urls.py from django.urls import path from django.views.generic.base import RedirectView from . import views app_name = 'todo' urlpatterns = [ path('', views.home, name="home"), path('add_todo/', views.add_todo), path('delete_todo/<int:todo_id>/', views.delete_todo), path('login/', views.login_user, name='login'), path('logout/', views.logoutUser, name='logout'), path('register/', views.register_user, name="register"), ] Any suggestion or response would appreciate it Thanks! -
Can I run 2 gunicorn doing different tasks to one and other on one server?
Currently I am running with 1 worker. I want to increase my number of workers. But now if I increase the number of workers my background services will also increase. Leads to duplicate data. For example: I have an email inbox scanning service that runs on repeat every minute. If there is new email will generate data in mongoDB. So if run with 1 worker it's fine. but when increase to 3 workers it will loop, resulting in 1 email coming it will scan 3 times and generate 3 data on mongoDB. My idea would be to separate the services that run repeatedly for a period of time that will run gunicorn with 1 worker. The remaining Gunicorn will run with 3 workers to increase API processing performance. According to the manual: recommend (2 x $num_cores) + 1 as the number of workers to start off with. My computer has 4 CPUs. So I will follow the formula (2 * core) + 1. We get (2 * 4) + 1 = 9 is the number of workers that are suitable for the system. - I use 8 workers to run the first Gunicorn to process the API with port 8000: … -
How to create a tag input field in django
I am trying to create an input field for tags in django. I've see streamlit enables to do it (https://discuss.streamlit.io/t/new-component-streamlit-tags-a-new-way-to-do-add-tags-and-enter-keywords/10810), and I am sure it is doable in django. I'd like to have all tags be read from a list/dict and possibly even have the autocomplete suggestions. I did see it on many sites, but I can't find a tutorial to insert it into the django project. Thanks! -
Getting a JSON string via the Django API in Android
I'm trying to get a JSON string by JSON with the API. The API is self-made (very simple) on Django. If you open /127.0.0.1:8000/get_last_data in the browser, then everything is displayed. I tried to run it on the emulator (using /10.0.0.2:8000/get_last_data) I get an error - Failed to connect to /10.0.0.2:8000. I tried to run on a real device (/192.168.0.104:8000/get_last_data) I get - Failed to connect to /192.168.0.104:8000. I tried using a third-party API - it works. Tell me what to do? I apologize for my English -
I get a invalid TemplateSyntaxError in Django for using the {% else %}-statement
My django-project (a tutorial https://www.youtube.com/watch?v=PtQiiknWUcI) keeps crashing on the basis that it doesn't accept my '{% else %}'-statement. I can't wrap my head around it. {% if request.user.is_authenticated %} <div class="header__user"> <a href="profile.html"> <div class="avatar avatar--medium active"> <img src="{{request.user.avatar}}" /> </div> <p>{{request.user.username}} <span>{{request.user.username}}</span></p> </a> <button class="dropdown-button"> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"> <title>chevron-down</title> <path d="M16 21l-13-13h-3l16 16 16-16h-3l-13 13z"></path> </svg> </button> </div> {% else %} <a href="{% url 'login' %}"> <img src="./assets/avatar.svg" /> <p>Login</p> </a> {% endif %} Django gives me a TemplateSyntaxError with the text: 'Invalid block tag on line 82: 'else'. Did you forget to register or load this tag?' The if-statement is there to control if the user is logged in. The 'else-statement' is there to show someone the inlog-page when not logged in. I tried to google this. But for other people this 'error' comes up when they wrote there if-statement wrong. I hope that someone can help me. It's so frustrating. -
Django interprets safe filter weirdly
at start I will mention that I'm not a backend developer, so please be gentle :p We have a django template however I have a strange problem with data that is a rich-text. Example: template: <p class="correctClass">{{team.description|safe}}</p> source code for team.description in our CMS: <p>Correct text</p> result: <p class="correctClass"></p> <p>Correct text</p> <p></p> without safe filter it's like that: <p class="correctClass"> <p>Correct text</p> (this line is text, not parsed as html) </p> Of course wanted output is: <p class="correctClass">Correct text</p> -
Model in Django training course project
I was adding training courses to my project, but in the model writing section I came across a question: The question was whether I should have a model for the specifications of all training courses (including name, description, price, etc.) along with a Have a model for the content of all courses (including course content and textbooks)? I did the same, but when I wanted to go to the next section for each textbook with the help of id, he realized that the content of another course might come because maybe the next ID is for another course! Please help me in this regard and tell me how should I write my model? And if I have to write like this, do I have to put a field in the content model to specify which period the content is from? But I think this method is not very suitable. Pictures of models: -
How to make users edit field.options in Django?
I am making an app where users can track their income and expenses. I want each transaction to be categorized based on where it is stored - like in checking, credit, savings, wallet, gift card, venmo, etc. I am planning to use Django Field.choices but the options are permanent and I want the users to edit their own choices. How can I do that? -
How to display your queries using filter?
So I am trying to set up a filter for my website and it is not working; It does not give me an error and the url updates like a query is being made but when I click "submit" it still shows all of the content in the page. I can't quite figure out what is wrong. filters.py import django_filters from django_filters import DateFilter from .models import * class UserpostFilter(django_filters.FilterSet): start_date = DateFilter(field_name = "date_published", lookup_expr='gte') end_date = DateFilter(field_name = "date_published", lookup_expr='lte') class Meta: model = Userpost fields = '__all__' exclude = ['image', 'user', 'date_published'] models.py class Userpost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) Year = models.CharField(max_length = 4) Mileage = models.CharField(max_length = 8) Make = models.CharField(max_length = 50) Model = models.CharField(max_length = 50) Price = models.DecimalField(max_digits=15, decimal_places=2) email = models.EmailField() date_published = models.DateField(default = timezone.now) image = models.ImageField(null = True, blank = True, upload_to = r"C:\Users\gabri\Desktop\test\ecommerce\static\images") def __str__(self): return self.Year + " " + self.Make + " " + self.Model @property def imageURL(self): try: url = self.image.url except: url = '' return url views.py def posts(request): cars = Userpost.objects.all() p = Paginator(Userpost.objects.all(), 9) page = request.GET.get('page') cars_list = p.get_page(page) nums = "a" * cars_list.paginator.num_pages myFilter = UserpostFilter(request.GET, queryset = … -
FieldError when creating User Model Types
I have been trying to customise User Model such that it can have different roles and i'm stuck. I can't figure out what i'm missing or when i went in the wrong direction. I'm supposed to create 4 roles Teacher, Student, Parent and HeadTeacher. Here is my models.py: #importing modules from django.db import models from django.db.models.fields import proxy from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin, AbstractUser from django.utils import timezone from class_apps.models import Classes from class_apps.models import Subjects from phone_field import PhoneField ####MODELS #Managers class UserManager(BaseUserManager): def _create_user(self, username, password, is_staff, is_superuser, is_active, **extra_fields): if not username: raise ValueError('Users must have an username') now = timezone.now() user = self.model( username=username, is_staff=is_staff, is_active=is_active, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, username=None, password=None, is_active=True, **extra_fields): return self._create_user(username, password, False, False, is_active, **extra_fields) def create_superuser(self, username, password, **extra_fields): user = self._create_user(username, password, True, True, True, **extra_fields) user.save(using=self._db) return user def save(self, *args, **kwargs): if not self.pk: self.type = User.Types.STUDENT return super().save(*args, **kwargs) class TeacherManager(models.Manager): def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).filter(base_type=User.Types.TEACHER) class StudentManager(models.Manager): def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).filter(base_type=User.Types.STUDENT) class ParentManager(models.Manager): def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).filter(base_type=User.Types.PARENT) def create_parent(self, user, title, surname,other_names,email,phone_no,address,gender,marital_status,proposed_wards): … -
Modify model value when retrieved in django
I have a model that save created_at in UTC format in database. When I want to show it to the user I want the datetime is shown in TIME_ZONE that I set in settings.py(which is 'Asia/Jakarta'). Right now every time I want to show it to the user, I have to manually change it using timezone.localtime(). Is there a way to automatically set the datetime to 'Asia/Jakarta' when field is retrieved from the model? Here is my model: from django.db import models class Product(models.Model): name = models.CharField(max_length=255) quantity = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'product' def __str__(self): return self.name -
Multiple Websites in Django - Gunicorn-Nginx
Please i have deploy a project in Digital Ocean and made all theese Made The DB mkdir pyapps 3 .python3 -m venv ./venv 4 .source venv/bin/activate 5 .pip install -r requirements.txt 6 .Made the settings.py try: from .local_settings import * except ImportError: pass Run Migrations python manage.py makemigrations 8 . python manage.py migrate 9 .Create super user 10 . Create static files 11 .python manage.py collectstatic 12 .Create exception for port 8000 python manage.py runserver 0.0.0.0:8000 I made the above until there TWICE for 2 websites in Django and of course there are working when i go in their seperated VENV and make python manage.py runserver 0.0.0.0:8000 After all these Gunicorn comes up.... i made a full search and i can not find Nowhere what happens if i can run both of them in a single droplet. There need to be 2 sockets? 2 services and after that 2 sites available? and link to 2 sites enable folder????! do i miss something because i canot not understand..do you have any tutorial for multiple websites deploy in droplet with nginx and gunicorn? -
Zappa Django: instead of re-querying the database, it uses an outdated in-memory cache. Can this behavior be changed?
In my project, I use Django as a frontend only. All backend logic is several AWS Lambda Python functions coordinated by the state machine. The database is SQLite in the S3 bucket. I use django_s3_storage and django_s3_sqlite. My backend functions change the number of model instances and their details in the SQLite database. I'd like those changes to be reflected by the Django frontend ASAP. However, it does not happen. I see only the outdated in-memory cache. I have tried several things. My initial view: class AllPortfolioRowsView(ListView): model = PortfolioRow template_name = "portfolio_all_rows.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # do something else context['object_list'] = PortfolioRow.objects.all().order_by('row_type') return context I have read the advice to do stuff inside the get function. In this case, supposedly, a query to the database must be executed every time the function is called. Variant #2: class AllPortfolioRowsView(View): def get(self, request): template = loader.get_template('portfolio_all_rows.html') object_list = PortfolioRow.objects.all().order_by('row_type') # do something else context = { 'object_list': object_list, # other stuff } return HttpResponse(template.render(context, request)) It worked but did not help. Then I tried to force querying the database, as recommended by the Django documentation. Variant #3: class AllPortfolioRowsView(View): def get(self, request): template = loader.get_template('portfolio_all_rows.html') object_list = PortfolioRow.objects.all().order_by('row_type') … -
What is the best way to track users on django website in 2021?
I finished my django project and I would like to add some kind of analytics, custom analytics, Google analytics or something else. I'm looking for best solution and easiest to implement. Can you give me some insights or advice? Thanks in advance! -
Why django respond back "TypeError: argument of type 'NoneType' is not iterable" when I use base64.b64decode
I am in trouble to develop the function to upload user image file into the database. I wrote the code like below from django.core.files.base import ContentFile import base64 def decode_base64_file(file_name, data): if 'data:' in data and ';base64,' in data: header, data = data.split(';base64,') try: decoded_file = base64.b64decode(data) except TypeError: TypeError('invalid_image') return ContentFile(decoded_file, name=file_name) return None Trying to store the user image file temporally and show it in "confirm page". I confirmed that image data captured through browse however when I tried to save it in database, then django respond back that TypeError: argument of type 'NoneType' is not iterable What should I be careful to conduct this code??? best, -
How to set field via function in django model?
I want the field "ripening time" to be determined when the model is created and calculated by function snippet class ActiveBusiness(models.Model): owner = models.ForeignKey(Profile, on_delete=models.CASCADE, default=None) id = models.AutoField(primary_key=True) business = models.ForeignKey(Business, on_delete=models.CASCADE, default=None) ripeningDate = models.DateTimeField(default=ripeningDate(self)) def __str__(self): return str(self.business.label def ripeningDate(self): ripeningTimeInSeconds = self.business.ripeningTimeInSeconds now = datetime.datetime.now() result = now + datetime.timedelta(seconds = ripeningTimeInSeconds) return result but it is not work if i use @property i dont get it in api what am I doing wrong? -
django is there better variant to use CBV approach in my project?
Sorry for such a long question and my bad english. I have finished Python Crash Course, an introductory programming book by Eric Matthes. After that decided to continue study Django and found that CBV method is more acceptable for site creating. I rewrited via CBV training program from the book which was written by functions, but I still feel a bit lost with methods of CBV after reading the official documentation. Could somebody tell, is there a lot of hardcoding in my CBV variant? And it's possible to do it better ? Every variant works fine. Here the variant of views from the books with comments, I inserted a comments to understand what code does: from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from django.http import Http404 from .models import Topic, Entry from .forms import TopicForm, EntryForm # Create your views here. def index(request): """Home page of Learning Log.""" return render(request, 'learning_logs/index.html') def more_inf(request): return render(request,'learning_logs/more_inf.html') def topics(request): """List of topics""" public_topics = Topic.objects.filter(public=True).order_by('date_added') if request.user.is_authenticated: private_topics = Topic.objects.filter(owner=request.user).order_by('date_added') topics = public_topics | private_topics else: topics = public_topics context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) @login_required def topic(request, topic_id): """Show one topic with details""" topic = get_object_or_404(Topic, … -
How to create a modal in django without Jquery
Currently, I have created functionality to display some information regarding one of my models in HTML, in the spirit of succinctness, I would like to present the client information model using a modal pop-up window. My main problem is that when the user clicks the view button, I'm getting data from the database and sending it to a view and this is rendered as HTML - I can certainly use Jquery AJAX to pass the data to the server and get a JSON file to construct my form in my main HTML page using bootstrap modal forms, however, is there another more pythonic way to achieve this? views.py #Receives the client name and gets a queryset that is passed on to the HTML page def ind_client_view(request): name = request.GET.get('name','') firstname,lastname = name.split() client = Client.objects.filter(firstname=firstname,lastname=lastname) return render(request,'account/leads_list.html', {'client':client}) {% for lead in pag_leads %} <tr> <td><a href = "{% url 'leads_update' lead.project_id %}">{{ lead.project_id }}</a></td> <td>{{ lead.agent }}</td> <td>{{ lead.company }}</td> <td><a href = "{% url 'ind_client_view' %}?name={{ lead.point_of_contact }}" class="btn btn-primary btn-sm">{{ lead.point_of_contact }}</a></td> <td>{{ lead.country }}</td> <td>{{ lead.services }}</td> <td>{{ lead.expected_licenses }}</td> <td>{{ lead.expected_revenue }}</td> <td>{{ lead.estimated_closing_date }}</td> <td> {% if lead.age_in_days <= 30 %} <b style="color:Red">{{ lead.age_in_days … -
Anotation in Serializer not working correctly
suppose [ {"folder": "cs", "post": {"id": "jqux3ipm", "content": "content", "username": "username", "liked": false, "saved": false, "seen": false}, "liked": true, "saved": true, "seen": false}, ] How do i convert it to [ {"folder": "cs", "post": {"id": "jqux3ipm", "content": "content", "username": "username", "liked": true, "saved": true, "seen": false}, ] models class Post(models.Model): content = ... ... class SavedPost(models.Model): user = models.ForeignKey(User,...) post = models.ForeignKey(Post,...) class LikedPost(models.Model): user = models.ForeignKey(...) post = models.ForeignKey(Post,...) Serializer i am using class SavedPostSerializer(serializers.ModelSerializer): seen = serializers.BooleanField(default=True, read_only=True) liked = serializers.BooleanField(default=False, read_only=True) saved = serializers.BooleanField(default=True, read_only=True) post = PostSerializer(read_only=True) class Meta: model = SavedPost fields = ("folder", "post", "liked", "saved", "seen") view @login_required() def GetSavedPost(request): obj = SavedPost.objects.select_related("post").annotate( liked=Exists(LikedPost.objects.filter( user=request.user, post_id=OuterRef('post_id'))), saved=Exists(SavedPost.objects.filter( user=request.user, post_id=OuterRef('post_id'))) ).filter(user_id=request.user.id) serializer = SavedPostSerializer(obj, many=True) result = JsonResponse(serializer.data, safe=False) return result All i want is to show some anotation field using a defined serializer and extra field i.e. cs. Thanks in advance! -
Django override query set method
I am trying to override get_queryset in a django ViewSet class but I am getting a router error : extra_actions = viewset.get_extra_actions() AttributeError: 'function' object has no attribute 'get_extra_actions' Here is my ViewSet class : class InvestmentViewSet(NestedViewSetMixin, ModelViewSet): """ A viewset that provides `retrieve`, `create`, and `list` actions for Investments. """ model = Investment serializer_class = InvestmentSerializer queryset = Investment.objects.all() def get_active_investment(self): """Get active investment Only One investment/startup is active """ queryset = Investment.objects.all() active = self.request.query_params.get('active') if active is True: queryset = queryset.filter(investment_status=active) return queryset Here is how I am calling it with router : from django.conf import settings from django.contrib import admin from django.urls import path, re_path from django.views.static import serve from rest_framework_extensions.routers import ExtendedSimpleRouter from back import views router = ExtendedSimpleRouter() ( router.register(r'api/startups', views.StartUpViewSet, basename='startup') .register(r'investments', views.InvestmentViewSet.get_active_investment, basename='startups_investment', parents_query_lookups=['startup']) ) urlpatterns = [ path('admin/', admin.site.urls), *router.urls, re_path(r'media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}), ] -
Hosting Angular and Django on a VPS
I've already hosted my Django application on a VPS using gunicorn and Nginx. I created a config file for the Django app under /etc/nginx/sites-available/myapp and the app is running well on port 80. The below image is the config file regarding the Djagno app: Now, I want to run the Angular application on the same server. How can I do that taking in consideration that I already did a research on it and tried creating a config file for angular under /etc/nginx/sites-available/angular-app but failed? The below image is the config file regarding the Angular app: -
django.db.utils.OperationalError: foreign key mismatch - "businesses_activebusiness" referencing "businesses_business"
I have a Business class, I want to make an active business class that depends on the first class class Business(models.Model): name = models.CharField(max_length=50, primary_key=True,unique=True,default='new') label = models.CharField(max_length=50, blank=True, null=True) ripeningTimeInSeconds = models.IntegerField() requiredLevel = models.IntegerField() price = models.IntegerField() def __str__(self): return str(self.label) class ActiveBusiness(models.Model): owner = models.ForeignKey(Profile, on_delete=models.CASCADE, default=None) id = models.AutoField(primary_key=True) business = models.ForeignKey(Business, on_delete=models.CASCADE, default=None) def __str__(self): return str(self.business.label) @property def ripeningDate(self): ripeningTimeInSeconds = self.business.ripeningTimeInSeconds now = datetime.datetime.now() result = now + datetime.timedelta(seconds = ripeningTimeInSeconds) return result Why can't I refer to the Business class? Where is the problem here? -
How to declare variable using loop in Python?
I just wanted to know how I can shorten my code using loop in python, can someone help me? Thanks! I'm using Python-flask. app.route('/data', methods=["GET", "POST"]) def data(): con = sqlite3.connect('tmonitor.db') con.row_factory = sqlite3.Row cur = con.cursor() cur.execute("SELECT * FROM monitors ORDER BY id DESC limit 1") rows = cur.fetchall() value = [row[1] for row in rows] //to split the array value1 = '-'.join(str(e) for e in value) value2 = value1.split('-') //Insert inside the loop to shorten the code Cell1_raw = value2[0] Cell2_raw = value2[1] Cell3_raw = value2[2] Cell4_raw = value2[3] Cell5_raw = value2[4] Cell6_raw = value2[5] Cell7_raw = value2[6] Cell8_raw = value2[7] Cell9_raw = value2[8] Cell10_raw = value2[9] // To convert in integer (Also need to shorten the code) Temperature1 = int(Cell1_raw) Temperature2 = int(Cell2_raw) Temperature3 = int(Cell3_raw) Temperature4 = int(Cell4_raw) Temperature5 = int(Cell5_raw) Temperature6 = int(Cell6_raw) Temperature7 = int(Cell7_raw) Temperature8 = int(Cell8_raw) Temperature9 = int(Cell9_raw) Temperature10 = int(Cell10_raw) // to shorten also data = [time() * 1000, Temperature1, Temperature2, Temperature3, Temperature4, Temperature5, Temperature6, Temperature7, Temperature8, Temperature9, Temperature10] response = make_response(json.dumps(data)) response.content_type = 'application/json' return response I added some comments for you to see what needs to be shorten, I'm still studying python, thank you so much!