Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
comment model not attached to ticket model
Creating a separate comments app for ticket app. My issue is that when I create and submit my comment on a particle ticket, it creates its own new page of tickets instead of being attached to original ticket. I think the issue has to do with my urls.py file and I feel like i'm close to solving this but i’m not sure how to proceed. Here is my comment models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from tickets.models import Ticket class Comment(models.Model): ticket = models.ForeignKey(Ticket, related_name='comments', on_delete=models.CASCADE, null=True) title = models.CharField(max_length=20) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('tickets:ticket-detail', kwargs={'pk': self.pk}) Here is my ticket models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from users.models import Profile class Ticket(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) assignee = models.ForeignKey(Profile, on_delete=models.SET_NULL, blank=True, null=True) status = models.BooleanField(choices=MARKED, default=True) priority = models.TextField(choices=PRIORITIES, default='None', max_length=10) label = models.CharField(choices=TYPES, default='Misc', max_length=100) def __str__(self): return self.title def get_absolute_url(self): return reverse('ticket-detail', kwargs={'pk': self.pk}) Here is the main urls.py from django.conf import settings … -
How can i automatically fill fields for new users that register django?
i have got a problem with automatically filling fields for new users that register in django. I don't know how can i get some informations. so this is my Profile Model class Profile(models.Model): user = models.ForeignKey(MyUser, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=45) last_name = models.CharField(max_length=60) profile_picture = models.ImageField(default='profile_pics/Default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.first_name} {self.user.last_name}' this is the function that automatically creates Profile. @receiver(post_save, sender=MyUser) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) and this is MyUser model that i use. class CustomUserManager(BaseUserManager): def _create_user(self, email, password, first_name, last_name, mobile, **extra_fields): if not email: raise ValueError("Email must be provided") if not password: raise ValueError("Password is not provided") user = self.model( email= self.normalize_email(email), first_name = first_name, last_name = last_name, mobile = mobile, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, first_name, last_name, mobile, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_active', True) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password,first_name, last_name, mobile, **extra_fields) def create_superuser(self, email, password, first_name, last_name, mobile, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_active', True) extra_fields.setdefault('is_superuser', True) return self._create_user(email, password, first_name, last_name, mobile, **extra_fields) class MyUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(db_index=True, unique=True, max_length=254) first_name = models.CharField(max_length=240) last_name = models.CharField(max_length=240) mobile = models.CharField(max_length=50) is_staff = models.BooleanField(default=True) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) objects= CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', … -
How to change a django venv (coded on windows) in the way to get it running on linux server?
Iam trying to get my windows django project working on a linux server. I realised that the venv causing trouble to get it running on a linux server. Is there an easy way to convert the venv to linux without booting a linux dist and setup the whole project on linux? Thanks for helping. -
create a django-queryset with all objects but not all related many to many fields by a condition
class Post(models.Model): text = models.TextField() class Project(models.Model): name = models.CharField(max_length=60) description = models.CharField(max_length=500) class Tag(models.Model): name = models.CharField(max_length=60) project = models.ForeignKey(Project, on_delete=models.CASCADE) class TaggedPost(models.Model): org_post = models.ForeignKey(Post, on_delete=models.CASCADE) tags = models.ManyToManyField(Tag) Assumed I have defined above models. There exist multiple projects which all have multiple tags. Eg: Project1 -> Tag1, Tag2 Project2 -> Tag3 Not every Post do have a TaggedPost object. Eg. Post1 -> no tags Post2 ->TaggedPost -> Tag1 Post3 ->TaggedPost -> Tag2 Post4 ->TaggedPost -> Tag2, Tag3 (Here are tags of multiple Projects) What I now want to do is a queryset which contains all Posts (also the untagged posts) but only tags of a defined project. qs.include_tags_of_project(Project1) results in: Post1 -> no tags Post2 -> Tag1 Post3 -> Tag2 Post4 -> Tag2 qs.include_tags_of_project(Project2) results in: Post1 -> no tags Post2 -> no tags Post3 -> no tags Post4 -> Tag3 any sugestions how to handle that? Thx -
AWS RDS postgres runing locally but not on EC2
i set a DB on AWS postgres and its connected locally, but when i push them same app on EC2 server, it give following error django.db.utils.OperationalError: connection to server at "portfolio-db.cco9tqdwh3aa.us-east-1.rds.amazonaws.com" (172.00.69.176), port 5432 failed: Connection timed out Is the server running on that host and accepting TCP/IP connections? Here is the security group of server Security group of DB -
Images are uploaded into S3 but URL within django application is not displaying correctly
Problem I am able to upload images into S3, however the structure of the URL within my django app is not structured properly. The URL appears like this: http://localhost:8000/plants/https://'%s.s3.amazonaws.com'%AWS_STORAGE_BUCKET_NAME/media/plant_images/image.jpeg However, I want it to appear as https://opensprouts-dev-media.s3.amazonaws.com/media/plant_images/images.jpeg Context I have a model that allows me to upload multiple images. I think I need to rewrite the way I call for the image within my template, or within my model. After reading through Django documentation and other stackoverflow questions, I'm not sure how to resolve this issue. settings.py/base.py # MEDIA # ------------------------------------------------------------------------------ USE_S3 = os.getenv('USE_S3') == 'TRUE' AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') AWS_QUERYSTRING_AUTH = config('AWS_QUERYSTRING_AUTH') AWS_S3_CUSTOM_DOMAIN = config('AWS_S3_CUSTOM_DOMAIN') AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = config('AWS_LOCATION') PUBLIC_MEDIA_LOCATION = 'media' AWS_QUERYSTRING_AUTH = False MEDIA_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATIN) DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') The section of my template that is calling for the URL {{ image.images.url }} {% for image in plant.plant_images.all %} {% if forloop.first %} <div class="carousel-item active"> {% else %} <div class="carousel-item"> {% endif %} <img src="{{ image.images.url }}" alt="{{ plant.name }}"> </div> {% endfor %} </div> models.py import datetime from django.conf import settings from django.db import models from django.utils import … -
Chain filtering with OR operator in the filterset - Django Rest Framework
I want to use multiple filter fields together in the filterset class which I can populate in the browsable api and make queries with OR condition. For example: SELECT name FROM Person WHERE age > 17 OR address LIKE ‘%New%’ I wonder how to implement something like this as HTML controls in the browsable API : f = Q(name__contains='Ja') | Q(age>500000) qs = qs.filter(f) -
Django channels for personal chat and keep websocket connected
I've been successful to create Websocket to connect and also able to personalize chats with route by doing something like path(r'chat/<str:user_id>/<str:other_user_id>/', ChatConsumer.as_asgi()) This works great with creating room/group with user_id and other_user_id on Django channels consumer. However scaling it with flutter and keeping the user connected to WebSocket in the background. To simplify I can't send connect request to the above mentioned endpoint to keep the user connected in the background on a flutter application. How do I create a room to have personal chats function on Django Channels? Create room/group specifically for two users when messages is sent to a user. -
Is the output of Next.js SSG build, SEO friendly?
I would like to know if the output generated by nextjs SSG build is SEO friendly, the same way as using nextjs with SSR. The reason I am asking is, because I would like to build a full stack app with React frontend (Django/DRF backend for what is worth), and SEO is really important. Also I would prefer to not have a separate nodejs instance serving the frontend separately. tl:dr I would like to serve only static files for the frontend while also being SEO friendly. Thanks very much in advance. -
Conditional processing of CreateView Django
i Have the following view in django : class CompraCreateView(CreateView): model = Compra fields = ['edicion'] def get_form(self, *args, **kwargs): form = super(CompraCreateView, self).get_form(*args, **kwargs) queryset = Edicion.objects.filter(promocion__fecha_de_finalizacion__gte = timezone.now()) form.fields['edicion'].queryset = queryset return form and its template: {% extends 'base.html' %} {% load crispy_forms_tags %} {% block title %}nueva compra{% endblock title%} {% block content%} <h1>Nueva Compra</h1> <form action="" method="post"> {% csrf_token %} {{ form|crispy }} <button class="btn btn-success ml-2" type="submit">Comprar</button> </form> {% endblock content %} What I'm trying to do is to force a conditional behavior of the view so it displays an error message in case the queryset of the field 'edicion' is empty. Thank you for your help. Sorry for my bad english -
How to delete data from database with a button using only DJANGO python, java script, and HTML?
I am working on a django project where my database gets populated from a post call, and for quality of life, I want to be able to clear the database at the click of a button. If it's possible, I'd like to only use python, javascript, and HTML. I've done some searching on here and haven't found any question like this so far with an answer. Here's a link to a similar question with no answer. There is a question that is similar to mine, but OP is using PHP, jquery, and SQL, which isn't ideal for me. I haven't attempted any code because I don't know where to start. If anyone has knowledge about this kind of thing, it would be much appreciated if you gave me a starting place. -
How do I retrieve file from server with graphene and Django?
How do I retrieve file from server with graphene and Django? I found graphene-file-upload, but it seems to take care of only uploading client's files to the server -
createsuperuser gives KeyError after implementing custom user
Hey I'm fairly new to Django and I'm trying to setup a pretty basic rest API. I am using djoser to handle authentication. However I want to use a custom user model. Where 1. the unique field is the email (instead of username) and 2. it is has one extra field. I tried to follow these two guides, https://testdriven.io/blog/django-custom-user-model/ (To use email instead of username) https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html#abstractuser (To extend the usermodel) I create the model like so, class MyUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) DIET_CHOICES = ( ('vegan', 'Vegan'), ('vegetarian', 'Vegetarian'), ('meat', 'Meat') ) diet = models.CharField(max_length=10, choices=DIET_CHOICES) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [diet] objects = CustomUserManager() def __str__(self): return self.email Using the CustomUserManager() as shown in https://testdriven.io/blog/django-custom-user-model/. I have also registered the user in AUTH_USER_MODEL. Looking at the migration file I get what I expect. But after migrating when I then try to run createsuperuser, it instantly results in the following error Traceback (most recent call last): File "/home/frederik/Documents/andet/madklubTests/2madklubDjango/venv/lib/python3.9/site-packages/django/db/models/options.py", line 672, in get_field return self.fields_map[field_name] KeyError: <django.db.models.fields.CharField: diet> During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/frederik/Documents/andet/madklubTests/2madklubDjango/manage.py", line 22, in <module> main() File "/home/frederik/Documents/andet/madklubTests/2madklubDjango/manage.py", line 18, in main execute_from_command_line(sys.argv) File … -
everytime i do some activity on my website i get this error :- Wallpaper.models.Wallpaper.DoesNotExist: Wallpaper matching query does not exist
Views.py def home(request): WAllPAPER_PER_PAGE = 4 WALL = Wallpaper.objects.all() from django.core.paginator import EmptyPage, Paginator from django.db.models import Q qd = request.GET.copy() qd.pop('page', None) querystring = qd.urlencode() #link formatting for ordering ordering =request.GET.get('ordering', "") #link formatting for sorting search = request.GET.get('search', "") if search: wallpapers = Wallpaper.objects.filter(Q(name__icontains=search) | Q(category__category_name__icontains=search) | Q(tags__tag__icontains=search)).distinct() WALL = None else: wallpapers = Wallpaper.objects.all() if ordering: wallpapers = wallpapers.order_by(ordering) page = request.GET.get('page', 1) wallpaper_paginator = Paginator(wallpapers, WAllPAPER_PER_PAGE) try: wallpapers = wallpaper_paginator.page(page) except EmptyPage: wallpapers = wallpaper_paginator.page(wallpaper_paginator.num_pages) except: wallpapers = wallpaper_paginator.page(WAllPAPER_PER_PAGE) context = {'querystring': querystring, "wallpapers": wallpapers, 'page_obj': wallpapers, 'is_paginated': True, 'paginator': wallpaper_paginator, 'WALL': WALL} return render(request, "Wallpaper/Home.html", context) def All_category(request): Cat = Category.objects.all() context = {'Cat': Cat } return render(request, "Wallpaper/ALL_Category.html", context ) def category(request, Category_name): cat = Category.objects.get(category_name=Category_name) wallpapers = Wallpaper.objects.filter(category__category_name=Category_name) context = {'cat':cat, 'wallpapers': wallpapers} return render(request,'Wallpaper/Category.html', context) def download(request, wallpaper_name): wallpaper = Wallpaper.objects.get(name=wallpaper_name) similar_wallpapers = wallpaper.tags.similar_objects() context = {'wallpaper': wallpaper, 'similar_wallpapers': similar_wallpapers} return render(request, 'Wallpaper/download.html', context) error C:\Users\Atharva thaware\Desktop\aman\projects\Ongoing\WallpaperTown\WallpaperTown\Wallpaper\views.py:30: UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list: <class 'Wallpaper.models. Wallpaper'> QuerySet. wallpaper_paginator = Paginator(wallpapers, WAllPAPER_PER_PAGE) [19/Jul/2022 22:29:39] "GET / HTTP/1.1" 200 10744 [19/Jul/2022 22:29:39] "GET /media/Wallpaper/Images/wp4589844-inosuke-hashibira-wallpapers.jpg HTTP/1.1" 304 0 [19/Jul/2022 22:29:39] "GET /media/Wallpaper/Images/wp2162463-shoto-todoroki-wallpapers.png HTTP/1.1" 304 0 [19/Jul/2022 22:29:39] "GET /media/Wallpaper/Images/wp2490700-haikyu-2018-wallpapers.jpg HTTP/1.1" 304 … -
ValueError in django project
I am getting the following error when running my code: ValueError at /company/3 The view company.views.dynamic_company_number didn't return an HttpResponse object. It download my project -
Django @property and setter for models field
I'm trying to create a field that should be updated by time and use getter and setter for it. Below is my code that should work but something went wrong, could you help me, what have I missed? How to add this field to the admin pannel (the result of setter)? _status = models.CharField(max_length=15, choices=status_choice, default=COMING_SOON) time_start = models.DateTimeField() time_end = models.DateTimeField() @property def status(self): return self._status @status.setter def status(self, value): if value == Lessons.COMING_SOON and self.time_end > datetime.now() > self.time_start: self._status = Lessons.IN_PROGRESS elif value == Lessons.IN_PROGRESS and self.time_end < datetime.now(): self._status = Lessons.DONE I have tried to check if it works by the manual changing value in ./manage.py shell but haven't result. Seems like @property doesn't work. -
TypeError: Failed to execute 'fetch' on 'Window': Invalid name while fetching token of jwt to authorize
trying to create a E-commerce website using django, django RestAPI & React! i'm using Rest framework simple jwt for authorization & created a view of ' MyTokenObtainPairView' to retreat token where the user data will be stored. everything is fine but i can't fetch the token from the front end after logging in & it shows me the error. what am i doing wrong & how to fix it?? #Settings: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=90), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } views: from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework_simplejwt.views import TokenObtainPairView class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) # Add custom claims token['username'] = user.username # ... return token class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer @api_view(['GET','POST']) def getRoutes(request): routes = [ '/api/token', '/api/refresh', ] return Response(routes) Urls.py: from . import views from .views import * from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, ) urlpatterns = [ … -
Generate Table Columns automatically on Django with view
I'm using django and i'm creating a table from the tutorial data. As i was building my .html i easily got a loop to write the data from my choice instance, but i can't get the same thing to work for the column names. I saw here how to get the model fields but i can't get a loop to do write them for me. table.html {% extends 'base.html'%} {% block content%} <div class="container"> <div class="row"> <p><h3 class="text-primary"> Python Django DataTables </h3></p> <hr style="border-top:1px solid #000; clear:both;" /> <table id = "myTable" class ="table table-bordered"> <thead class = "alert-warning"> <tr> <!-- i would like not to have to write those one by one for future projects --> <th> Choice </th> <th> Votes </th> </tr> </thead> <tbody> <!-- this is the kind of loop I wanted for the columns--> {% for item in qs %} <tr> <td contenteditable='true'>{{item.choice_text}}</td> <td>{{item.votes}}</td> </tr> {% endfor %} </tbody> </table> {% endblock content%} views.py class ChoiceTableView(TemplateView): model = Question template_name = 'polls/table.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["qs"] = Choice.objects.all() return context models.py class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text -
with custom user i have not the group form in admin django
I created a custom user, it works well, but I notice that in the django admin, if I create a new user, I don't have access to the form that manages the groups. If I use a standard user system, when you create a user, in the admin, you have access to the management of groups and permissions. On the other hand in my project group and user are not linked my models.py from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.db import models class CustomUserManager(BaseUserManager): def create_user(self, email, password): if not email: raise ValueError('Vous devez entrer une adresse email.') email = self.normalize_email(email) user = self.model(email=email) user.set_password(password) user.save() return user def create_superuser(self, email, password): user = self.create_user(email=email, password=password) user.is_staff = True user.is_admin = True user.save() return user class CustomUser(AbstractBaseUser): email = models.EmailField( max_length=255, unique=True, blank=False ) nom = models.CharField(max_length=50, blank=False, unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = "email" def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True def __str__(self): return self.email in the views.py from django.contrib.auth import authenticate from django.http import HttpResponse from django.shortcuts import render, redirect from django.contrib.auth import login as log_user from django.contrib.auth import logout as logout_user from accounts.forms import … -
Django Allauth not included in URL Conf through template links but URL is functional
I am new to using AllAuth and somewhat new to Django. I am developing a site and wanted to overhaul the custom user authentication that I was using before. I have implemented AllAuth into an existing solution. Everything seems to be connecting, but the template links are not working and I get returned a 404 error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/url%20'account_login' Using the URLconf defined in QuoteTool.urls, Django tried these URL patterns, in this order: admin/ [name='home'] accounts/ form/ [name='entryForm'] form/success [name='success'] quotes/ [name='quotes'] The current path, url 'account_login', didn’t match any of these. For example in my Navbar ... {% if user.is_authenticated %} <div class="m-2"> <h6>Hello, {{ request.user.firstName }}!</h6> </div> <a class="btn btn-outline-secondary" href=" url 'account_logout' ">Logout</a> {% else %} <a class="btn btn-outline-secondary" href=" url 'account_login' ">Login</a> <a class="btn btn-primary ml-2 mr-2" href=" url 'account_signup' ">Sign Up</a> {% endif %} ... These links do not work! I am not understanding why not. Especially since if I manually type the URL "http://127.0.0.1:8000/accounts/login/" it returns and renders the proper page with my custom template. My url.py file is as follows from django.contrib import admin from django.urls import path, include from QuoteTool import views from accounts import … -
Django Project Permissions for Production
I’m struggling on how to properly set up my directory and file permissions for my Django apps on my Linux Server. I set the permissions on my Development Test machine to 755 for Directories and 644 for Files. However, I was unable to run pip from the Terminal in PyCharm until I increased the permissions for pip file. Are these the correct permissions for all folders/files in the Virtual Environment as well, especially the files in the Bin directory? Also, I have ownership of files set to a specific user I elevate privileges to perform certain ops. I am reading some people use root as owner of Django directory and files. Which is preferred in production environment? Any help would be greatly appreciated. -
Proper way to manage a list of form in Django
What is the best way to handle an array of forms in django? I am trying to create a custom permissions system and I have to do the form to create a role. The models involved are listed below: class CategoryPermissions(models.Model): upload = models.BooleanField(default=False) download = models.BooleanField(default=False) history = models.BooleanField(default=False) class Category(models.Model): name = models.CharField(max_length=250, unique=True) label = models.CharField(max_length=250) directory = models.CharField(max_length=250) class GroupPermissions(models.Model): role = models.ForeignKey('repository.Role',on_delete=models.RESTRICT) category = models.ForeignKey('repository.Category',on_delete=models.RESTRICT) category_permissions = models.OneToOneField("repository.CategoryPermissions",on_delete=models.RESTRICT) class Role(models.Model): name = models.CharField(max_length=250) For each Category (which are already created) I define a CategoryPermissions that contains the permissions and I link it to the Role with GroupPermissions. How do I create a multiple form that allows me to create GroupPermissions with related CategoryPermissions, maintaining the relationship between GroupPermissions, Category and Role? I tried with a CategoryPermissions formset, but when I extract it from request.POST I don't know which one I understand that it may be unclear so do not hesitate to ask for more explanations, I will try to do my best. -
a python script that binds a google table and postgresql
How to write a python script that can: Get data from the document using Google API made in [Google Sheets]. The data should be added to the database, in the same form as in the -source file, with the addition of the column "column_name." a. Need to create DB independently, DBMS based on PostgreSQL. The script runs constantly to ensure that the data is updated online (it is necessary to take into account that the rows in the Google Sheets table can be deleted, added and changed). And this script is wrapped in Django application I have made all the necessary API's and settings -
Unable to return user data properly in Django
I am following a tutorial and I got myself stuck. I've built the login page of the website and now I was just trying to display a dropdown in the Navbar, that displayed the user's name. Here is the code that is responsible for that to happen: {userInfo ? ( <NavDropdown title={userInfo.name} id="username"> <LinkContainer to="/profile"> <NavDropdown.Item>Profile</NavDropdown.Item> </LinkContainer> <NavDropdown.Item onClick={logoutHandler}> Logout </NavDropdown.Item> </NavDropdown> ) : ( <LinkContainer to="/login"> <Nav.Link> <i className="fas fa-user"></i>Login </Nav.Link> </LinkContainer> )} Trying to debug the issue I realized that 'userInfo' is just returning me the refresh and access token of the user, and basically userInfo.name does not exist. Here's the User action: import { USER_LOGIN_REQUEST, USER_LOGIN_SUCCESS, USER_LOGIN_FAIL, USER_LOGOUT, } from "../constants/userConstants"; import axios from "axios"; export const login = (email, password) => async (dispatch) => { try { dispatch({ type: USER_LOGIN_REQUEST, }); const config = { headers: { "Content-type": "application/json", }, }; const { data } = await axios.post( "/api/users/login/", { username: email, password: password }, config ); dispatch({ type: USER_LOGIN_SUCCESS, payload: data, }); localStorage.setItem("userInfo", JSON.stringify(data)); } catch (error) { dispatch({ type: USER_LOGIN_FAIL, payload: error.response && error.response.data.detail ? error.response.data.detail : error.message, }); } }; And the user views: from django.shortcuts import render from rest_framework.decorators import api_view, permission_classes … -
How to display data from Django manager's method in Django templates?
I'm implementing an app where a manager can control the products and their batches where he can activate or deactivate batches by selecting the,, so I'm trying to display a dropdown list to show all the available batches with their 'expiration status' and 'quantity availability status' and 'activation status'. What I did so far is that i have created a QuerySet and Manager classes in my Django model class, and I want to retrieve these classes and display them in my template. But the problem is that it didn't work, in my templates it displays nothing, and the select field doesn't show any choices. Here's what I did in models.py: class ExpirationStatus(models.TextChoices): VALID='VALID',_('Valid') ONE_MONTH= 'ONE_MONTH',_('One month or Less') THREE_MONTHS='THREE_MONTHS',_('Three Months Or Less') EXPIRED='EXPIRED',_('Expired') class BatchQuerySet(models.QuerySet): def annotate_expiration_status(self): one_month=date.today() - timedelta(days=30) three_months=date.today() - timedelta(days=90) today=date.today() return self.annotate(expiration_status= Case( When(expiry_date__lt=today,then=Value(ExpirationStatus.EXPIRED)), When(expiry_date__lte=one_month,then=Value(ExpirationStatus.ONE_MONTH)), When(expiry_date__lte=three_months, then=Value(ExpirationStatus.THREE_MONTHS)), When(expiry_date__gt=three_months, then=Value(ExpirationStatus.VALID)), )).order_by('arrival_date') class BatchManager(models.Manager): use_for_related_fields = True def annotate_expiration_status(self): return self.get_queryset().annotate_expiration_status() def get_queryset(self): return BatchQuerySet(model=self.model, using=self._db) class Batch(models.Model): class Status(models.TextChoices): ACTIVE = 'active', _('Active') INACTIVE = 'inactive', _('Inactive') product = models.ForeignKey(Product, on_delete=models.PROTECT, related_name='product_batch') expiry_date = models.DateField() quantity_bought = models.PositiveIntegerField() status=models.CharField(max_length=32, null=True, choices=Status.choices) arrival_date = models.DateField(auto_now_add=False) objects=BatchManager() def available_quantity(self): return self.quantity_bought-(self.issued_batches.aggregate(total_issued_quantity=Sum('issued_quantity')).get('total_issued_quantity') or 0) def __str__(self): return self.product.name + ' …