Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using sourcedefender with Django
I have a python Django code that I wish to encrypt and can still run the django server from the encrypted folder. I read the PyPi specifically under Integrating encrypted code with Django and I could not get it to work. My python Django project structure is as follows: -- backend ---- config directory (where the settings.py file, wsgi.py are) ---- services directory (contains multiple directories of which all are encrypted, service1, service2, service3 which contains the Django rest framework APIs and code logic) ---- manage.py -- requirements.txt For me, it is not important the config directory, manage.py, and requirements.txt to be encrypted. What is important is that the services directory is encrypted. So how can I achieve that? Here is what I have tried. cd backend sourcedefender --remove encrypt --password 1234abcd --salt dcba4321 services In the manage.py, and wsgi.py I add import sourcedefender to the very top and then run python3 -m sourcedefender manage.py runserver and I get ImportError: manage Any help is appreciated. -
How to Post line items in Django REST API
This GET Response data [ { "id": "055444eb-5c4d-445b-99cc-a01be17deeb7", "transaction_line_items": [ { "id": "5b0ea944-a032-4b8e-a29a-3f52e0863040", "title": "Sambar Powder", "description": "Sambar Powder 100g", "price": "10", "quantity": 1, "created_at": "2022-08-17T14:01:39.387406Z", "updated_at": "2022-08-17T14:01:39.387406Z" }, { "id": "ace1546b-12e4-4a6d-991e-b867cf64515a", "title": "Tomato", "description": "Tomato 10kg", "price": "20", "quantity": 10, "created_at": "2022-08-17T14:01:05.194278Z", "updated_at": "2022-08-17T14:01:05.194278Z" } ], "transaction_no": "6aa623a3", "cgst_per": 8, "igst_per": 8, "sgst_per": 0, "created_at": "2022-08-17T14:01:58.694463Z", "updated_at": "2022-08-17T14:01:58.694463Z", "account": "0b68e37e-ba15-4427-8a45-d48b152a42d5", "main_biiling_account": "edc9d792-ffdb-4122-8589-d499f05e4f7b" } ] This POST Request data { "transaction_line_items":[ { "title":"Tomato", "description":"2 kg Tomato", "price":"10", "quantity":2 }, { "title":"Fish", "description":"2 kg Fish", "price":"500", "quantity":2 } ], "cgst_per":"8", "igst_per":"8", "sgst_per":"0", "account":"edc9d792-ffdb-4122-8589-d499f05e4f7b", "main_biiling_account":"edc9d792-ffdb-4122-8589-d499f05e4f7b" } This POST Response data { "id": "dc2ed349-2e3b-42a3-9ce8-1ecd6f11a225", "transaction_line_items": [], "transaction_no": "6aa623a3", "cgst_per": 8, "igst_per": 8, "sgst_per": 0, "created_at": "2022-08-17T14:08:02.995195Z", "updated_at": "2022-08-17T14:08:02.995195Z", "account": "edc9d792-ffdb-4122-8589-d499f05e4f7b", "main_biiling_account": "edc9d792-ffdb-4122-8589-d499f05e4f7b" } View Code @api_view(['GET','POST']) @permission_classes([IsAuthenticated]) def apiTransactions(request,account_id): if request.method == 'GET': transactions = Transaction.objects.filter(account=account_id,account__user=request.user) serializer = TransactionSerializer(transactions, many=True) return Response(serializer.data) elif request.method == 'POST': data = request.data if (data["account"]==account_id): serializer = TransactionSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response({'meassage': 'Account ID not match'}, status=status.HTTP_400_BAD_REQUEST) Above I gave codes and JSON data. Why my line items aren't saved? When I enter data using the admin page it's working properly. When I use API it isn't saved properly. How … -
Django and Flutter wth http Plugin
I've created a REST API with Django and I want to use it in Fluter. I've created the endpoints and tested them; they work fine, I've also created the models in flutter. I've done the get all endpoint. I'm now struggling with how to decode the details endpoint and use it in Flutter. Anyone's thoughts ? -
how to apply bubble sort in django queryset
*how to sort object using bubble sort in django.TypeError: '<' not supported between instances of 'Product' and 'Product' -
What is the advantage of binding to a socket instead of an IP?
I'm following this guide to deploy a flask application to production using gunicorn I get to this line gunicorn --bind 0.0.0.0:5000 wsgi:app and it works perfectly After that the author recommends this instead gunicorn --workers 3 --bind unix:/home/movieapp/app.sock -m 777 wsgi:app So my (dumb) question: what is the advantage of binding to a socket instead of an IP? Thank you for your help! -
DRF: Serializer for different queryset
I have following serializer class VoteBaseSerializer(serializers.Serializer): likes = serializers.IntegerField() dislikes = serializers.IntegerField() is_voted = serializers.SerializerMethodField() def get_is_voted(self, obj): user = self.context.get('request').user vote = None if user.id: try: vote = Vote.objects.get(pk=obj.pk, user_id=user.id).choice except Vote.DoesNotExist: pass return vote My problem that i want yo use this serializer for different views. I have view that return article with prefetch_relted comments, then i annotate likes, dislikes and is_voted I have view that update vote object. And i want to return new condition. The problem in SerializerMethodField, when i trying get vote object In 1 case i'm working with post object and comment, then with reverse relation i get votes In 2 case i'm update vote by comment_id and there different lookups models.py class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) slug = models.SlugField(blank=True) body = models.TextField() tags = TaggableManager(blank=True) pub_date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-pub_date'] class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) text = models.TextField(max_length=500) pub_date = models.DateTimeField(auto_now=True) parent = models.ForeignKey('self', blank=True, null=True, on_delete=models.CASCADE, related_name='children') class Meta: ordering = ['-pub_date'] class Vote(models.Model): comment = models.ForeignKey(Comment, on_delete=models.CASCADE, related_name='votes') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) choice = models.BooleanField(null=True) views.py class PostViewSet(viewsets.ModelViewSet): serializer_class = PostSerializer permission_classes = [IsOwnerOrAdminOrReadOnly] pagination_class = PostPagination lookup_field … -
how to create a API for user model in Django?
I am Trying To create a API for my custom user model to register a user and get details about current user that is logged in . I tried to Follow a tutorial but I faced 2 problems, 1.The confirmation password is not being hashed when creating a user, 2. The Get method didn't work. I hope any one can help me. This is my models.py: from django.db import models from django import forms # Create your models here. from django.db import models from django.contrib.auth.models import ( AbstractUser, BaseUserManager, AbstractBaseUser ) from django.forms import Widget from django.urls import reverse class CustomUserManager(BaseUserManager): def create_user(self,email,password=None,is_active=True,is_staff=False,is_admin=False): if not email: raise ValueError('User Must Have Email') if not password: raise ValueError('User Must Have Password') user_obj = self.model( email = self.normalize_email(email) ) user_obj.set_password(password)#change user password user_obj.staff = is_staff user_obj.admin = is_admin user_obj.active = is_active user_obj.save(using=self._db) return user_obj def create_staffuser(self,email,password=None): user = self.create_user( email, password = password, is_staff = True ) return user def create_superuser(self,email,password=None): user = self.create_user( email, password = password, is_staff = True, is_admin = True, ) return user class CustomUser(AbstractBaseUser): username = models.CharField(max_length= 200) first_name = models.CharField(max_length = 300) last_name = models.CharField(max_length = 300) email = models.EmailField(max_length=255,unique=True) password = models.CharField(max_length=100,) password_2 = models.CharField(max_length=100,) sub_to_newsletter … -
How to change type in Django_filter input?
I have Django_filters form: class ContainerFilter(django_filters.FilterSet): def __init__(self, *args, **kwargs): super(ContainerFilter, self).__init__(*args, **kwargs) self.filters['title'].label = 'Продукт' self.filters['status'].label = ' Первый Статус' self.filters['status1'].label = 'Второй Статус' start_date = DateFilter(label='Создан от', field_name='created', lookup_expr='gte') end_date = DateFilter(label='Создан до', field_name='created', lookup_expr='lte',) class Meta: model = Container fields = ('title', 'status', 'status1', 'warehouse', 'start_date', 'end_date') And I want to change the start_date input type from text to date. I add widgedts in Meta but it's give error also i did widgets to input but it still don't work. -
Why I'm Not Getting Lable Tag Even After Loading It On The Templates?
Here Is The Template Image :- templates.html I'm Facing Problem While Rendering Template ,The Issue Is That The {{field.lable_tag}} Is Not Working I'm supposed To Get Field Lable which Is Wrapped In HTML Here Is My HTML code <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Index</title> </head> <body> <form action="" method="POST" novalidate> {%csrf_token%} {{form.non_field_error}} {% for field in form %} <div> {{field.lable_tag}} {{field}} {{field.errors|striptags}} </div> {%endfor%} <input type="submit" value="Submit"> </form> </body> </html> -
psycopg2.OperationalError: SSL SYSCALL error: EOF detected django Qcluster
Hi I'm trying to run a function as a background job from Django Qcluster and that jobs run for more than an hour based on the response of that job I update my Postgres table but when I get a response from Qcluster and try to update the table it gives me this error. How can I fix this error? psycopg2.OperationalError: SSL SYSCALL error: EOF detected. Qcluster setting: { "name": "sampleapp", "workers": 8, "recycle": 500, "compress": true, "save_limit": 250, "queue_limit": 500, "cpu_affinity": 1, "label": "Django Q", "max_attempts": 1, "attempt_count": 1, "catch_up": false, "redis": { "host": "127.0.0.1", "port": 6379, "db": 0 } } Django==3.1.7 django-q==1.3.9 Here is the complete stack trace: SSL SYSCALL error: EOF detected 15:36:35 [Q] ERROR Failed [kentucky-montana-west-alaska] - connection already closed : Traceback (most recent call last): File "/mnt/c/lyftrondatasync/LyftrondatasyncAPI/venv/lib/python3.9/site- packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.OperationalError: SSL SYSCALL error: EOF detected The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/mnt/c/lyftrondatasync/LyftrondatasyncAPI/connector/sync_utils.py", line 1361, in run_data_sync if not table_pipeline_json.count(): File "/mnt/c/lyftrondatasync/LyftrondatasyncAPI/venv/lib/python3.9/site- packages/django/db/models/query.py", line 411, in count return self.query.get_count(using=self.db) File "/mnt/c/lyftrondatasync/LyftrondatasyncAPI/venv/lib/python3.9/site- packages/django/db/models/sql/query.py", line 515, in get_count number = obj.get_aggregation(using, ['__count'])['__count'] File "/mnt/c/lyftrondatasync/LyftrondatasyncAPI/venv/lib/python3.9/site- packages/django/db/models/sql/query.py", line 500, in get_aggregation result = … -
How to filter queryset based on MethodSerializerField value?
I have serializers with SerializerMethodField field class EmployeeSerializer(serializers.Serializer): id = serializers.IntegerField() name = serializers.CharField() group_ids = serializers.SerializerMethodField() def get_group_ids(self): /* this method returns array of group_ids employee can me member of */ there is view: class EmployeeViewSet(GenericViewSet): serializer_class = EmployeeSerializer def get_queryset(self): return Employee.objects.all() If I want to list all employees I call this url and get the next resutl: http://localhost:8080/employees/ [ { "id": 1, "name": "Ann", "group_ids": [ 90, 100 ] }, { "id": 2, "name": "Tom", "group_ids": [ 90, 102 ] } ] I want to filter result by group_id. To have something like this: http://localhost:8080/employees/?group_id=102 and as a result I'll recieve only: [ { "id": 2, "name": "Tom", "group_ids": [ 90, 102 ] } ] Is there any options to filter queryset based on calculated value such as SerializerMethodField value? Thanks in advance -
Django ManytoMany field remains empty after .add() method called
Hi all so I'm using django to create a sign up platform where students can sign up to weekly classes. Each class is a django model called ClassCards with a User manytomany field called signed_up_student that represents all the users signed up for that class as seen below ''' class ClassCards(models.Model): content = models.CharField(max_length=100, default = '') date = models.DateField(blank=True, null = True) time = models.TimeField(blank=True,null=True) signed_up_students = models.ManyToManyField(User,blank=True) full = models.BooleanField(default = False) max_students = models.IntegerField(default=4) teacher = models.CharField(max_length=100, default='Adi') ''' I would like to add a subscription option that will autamatically sign up subscribed students to this weeks class. Here is my subscription model: ''' class Subscriptions(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null =True) day = models.CharField(max_length=100, choices=day_choices, null=True) time = models.TimeField(blank=True, null=True) num_of_times_used = models.IntegerField(default=0) cap = models.IntegerField(default=52) active = models.BooleanField(default= True) expirey_date = models.DateField() date_created = models.DateField(default = timezone.now) ''' To accomplish this I have created a post_save signal: ''' @receiver(post_save,sender=ClassCards) def apply_subsciptions(sender,instance,created, **kwargs): if created: subs = Subscriptions.objects.filter(day=instance.date.strftime("%A"), time=instance.time) for s in subs: instance.signed_up_students.add(s.user) print(instance.signed_up_students.get()) ''' The code runs properly when a ClassCard is saved without throwing any errors and the print statement prints the relevant User. However when i look on the admin page i … -
Heroku deploys app but can't serve it - ModuleNotFoundError: No module named 'django_app'
I'm trying to deploy an app via Digitalocean/Heroku which works for both the build and deployment. However, once I visit the successfully deployed site I get this: I already tried this without success. This is the full traceback: [cherry] [2022-08-17 13:43:20] [2022-08-17 13:43:20 +0000] [1] [INFO] Starting gunicorn 20.1.0 [cherry] [2022-08-17 13:43:20] [2022-08-17 13:43:20 +0000] [1] [INFO] Listening at: http://0.0.0.0:8080 (1) [cherry] [2022-08-17 13:43:20] [2022-08-17 13:43:20 +0000] [1] [INFO] Using worker: sync [cherry] [2022-08-17 13:43:20] [2022-08-17 13:43:20 +0000] [17] [INFO] Booting worker with pid: 17 [cherry] [2022-08-17 13:43:20] [2022-08-17 13:43:20 +0000] [17] [ERROR] Exception in worker process [cherry] [2022-08-17 13:43:20] Traceback (most recent call last): [cherry] [2022-08-17 13:43:20] File "/workspace/.heroku/python/lib/python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker [cherry] [2022-08-17 13:43:20] worker.init_process() [cherry] [2022-08-17 13:43:20] File "/workspace/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 134, in init_process [cherry] [2022-08-17 13:43:20] self.load_wsgi() [cherry] [2022-08-17 13:43:20] File "/workspace/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi [cherry] [2022-08-17 13:43:20] self.wsgi = self.app.wsgi() [cherry] [2022-08-17 13:43:20] File "/workspace/.heroku/python/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi [cherry] [2022-08-17 13:43:20] self.callable = self.load() [cherry] [2022-08-17 13:43:20] File "/workspace/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 58, in load [cherry] [2022-08-17 13:43:20] return self.load_wsgiapp() [cherry] [2022-08-17 13:43:20] File "/workspace/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp [cherry] [2022-08-17 13:43:20] return util.import_app(self.app_uri) [cherry] [2022-08-17 13:43:20] File "/workspace/.heroku/python/lib/python3.8/site-packages/gunicorn/util.py", line 359, in import_app [cherry] [2022-08-17 … -
Issue with Datetime from database and Django
I'm trying to generate some basic chart data, but I cannot, yet anyways. Whenever I retrieve datetime values from Django models, it gives me this output: [print(i) for i in UserAnalyticsMeta.objects.all().values('created_at')[:3]] {'created_at': datetime.datetime(2022, 8, 15, 22, 43, 23, 88381, tzinfo=datetime.timezone.utc)} {'created_at': datetime.datetime(2022, 8, 15, 22, 48, 43, 944993, tzinfo=datetime.timezone.utc)} {'created_at': datetime.datetime(2022, 8, 15, 22, 48, 49, 95255, tzinfo=datetime.timezone.utc)} Which translates to: 2022-08-15 22:43:23.088381+00:00 2022-08-15 22:48:43.944993+00:00 2022-08-15 22:48:49.095255+00:00 However, when I try to print out the date, this is the output I get: [print(i) for i in UserAnalyticsMeta.objects.all().values('created_at__date')[:3]] {'created_at__date': None} {'created_at__date': None} {'created_at__date': None} While I expect: 2022-08-15 2022-08-15 2022-08-15 What I've also noticed is that an old function I used also doesn't work anymore, and I feel like it has something to do with this. select_data = {"date_created": """strftime('%%m/%%d/%%Y', created_at)"""} qs = self.extra(select=select_data).values('date_created').annotate(models.Sum("page_visits")) return qs Now gives me the error: OperationalError at /admin/app_name/model_name/ (1305, 'FUNCTION app_name.strftime does not exist') Any help would be appreciated! Thank you. -
Django: assigning employees to the hotel rooms and manage dates overlaping and intersection
Task: Imagine we are a company and we want to send our employees on different work trips. Amount of employees for each trip can vary. Also, we are booking hotel rooms for each trip. The room type and max amount of employees per room can be one of these: [{"type": "single", "max_persons": 1}, {"type": "double", "max_persons": 2}, {"type": "triple", "max_persons": 3}, {"type": "quad", "max_persons": 4}] Employees can split the room if room is double, triple or quad Also, employees can live only few days in a row and then next employee could take this room. The task is to get list of dates when room is completely free (no employees lives there) and list of dates when room is partly free (there are 1-3 free beds) Image with visual task explanation The Django models.py is: class Hotels(models.Model): """ Model to store all hotels """ name = models.CharField(max_length=255) phone = PhoneNumberField(blank=True) address = models.CharField(max_length=255, blank=True) city = models.CharField(max_length=255, blank=True) country = CountryField(blank=True) zip = models.CharField(max_length=255, blank=True) REQUIRED_FIELDS = ["name", "address", "city", "country"] def __str__(self) -> str: return self.name class Meta: ordering = ["name"] verbose_name = "Hotel" verbose_name_plural = "Hotels" class RoomTypes(models.Model): """ Model to store all room types """ type = … -
Django Model While User Login
Iam new in programming. I need to make a model/table in django where details of a User has to save. If the User login It will goes to registration page if he is not completed the registration, else if he already completed the registration it will goes to home page. What should I do? models.py class UserReg(models.Model): Name=models.CharField(max_length=200) Date_of_Birth=models.DateField() Age=models.IntegerField() Gender=models.CharField(max_length=200, choices=GenderChoice) Phone_no=models.IntegerField() Mail=models.EmailField(unique=True) Address=models.TextField(max_length=700) District=models.ForeignKey(District,on_delete=models.CASCADE) Branch=models.ForeignKey(Branch,on_delete=models.CASCADE) Account_Type=models.CharField(max_length=200,choices=AccType) Materials=models.ManyToManyField(Materials) views.py def reg(request): form = Userform() if request.method == 'POST': form=Userform(request.POST) if form.is_valid(): Name=request.POST.get('Name') Date_of_Birth = request.POST.get('Date_of_Birth') Age = request.POST.get('Age') Gender = request.POST.get('Gender') Phone_no = request.POST.get('Phone_no') Mail = request.POST.get('Mail') Address = request.POST.get('Address') District = request.POST.get('District') Branch = request.POST.get('Branch') Account_Type = request.POST.get('Account_Type') Materials = request.POST.get('Materials') obj=UserReg(Name=Name,Date_of_Birth=Date_of_Birth,Age=Age,Gender=Gender,Phone_no=Phone_no,Mail=Mail,Address=Address,District=District,Branch=Branch,Account_Type=Account_Type,Materials=Materials) obj.save() return redirect('/') return render(request,'registration.html',{'form':form,}) -
How to execute javascript code after htmx makes an ajax request?
Im currently building a website with django and htmx and i like the combination so far. Lets say I use an htmx attribute on a button to replace a div in the DOM with another div that is supposed to contain a wysiwyg editor. Now the wysiwyg editor has to be initialized with javascript. How do I do this? Can I just return the script tag under the editor div that is being requested with htmx? Wouldnt that be also a little ugly or bad practice because youd have script tags in the middle of the html body? Whats the best way of solving this? Thanks in advance -
How to save form to database only if its not already in the database in django
Here is the code and Im wondering how can I make it so it saves if the input from the form is unique and not already in the db. @login_required def settings(request): form = EmailInfoForm() if request.method == "POST": form = EmailInfoForm(request.POST) if form.is_valid(): form.save() context = {'form': form} return render(request, 'tasks/settings.html', context) -
Django sync to async
I have this json file below, I wrote a code to check weather a username exists in these sites or not using request library the problem is that it takes too much time and it returns this error. ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None)) So I have been trying to make it faster by using asyncio, unfortunately i wasn't able to convert this view to async as there were no tutorial demonstrated what i am trying to implement.I have read the django sync_to_async library docs too. { "BuyMeACoffee": { "errorType": "status_code", "url": "https://buymeacoff.ee/{}", "urlMain": "https://www.buymeacoffee.com/", "urlProbe": "https://www.buymeacoffee.com/{}", }, "BuzzFeed": { "errorType": "status_code", "url": "https://buzzfeed.com/{}", "urlMain": "https://buzzfeed.com/", }, "CNET": { "errorType": "status_code", "url": "https://www.cnet.com/profiles/{}/", "urlMain": "https://www.cnet.com/", }, .... } This the code synchronous code that i wrote: def create(request): form = SearchForm() if request.method == 'POST': name = request.POST['name'] with open('sites-data.json') as f: data = json.load(f) mod_data = json.loads(json.dumps(data).replace("{}",name)) search_term = SearchTerm( user = request.user, name = name ) search_term.save() for item in mod_data: if mod_data[item]['errorType'] == "status_code": url = mod_data[item]['url'] urlMain = mod_data[item]['urlMain'] response = requests.get(url) status_code = response.status_code if status_code == 200: site_data = SearchResult( term = search_term, url … -
Please I am looking for someone who is proficient in DJANGO to help me in authenticating multiple types of users [closed]
enter image description here Help me create multiple user types -
Django - Redirect Unauthenticated User trying to access UpdateView to DetailView
This is my last brain cell speaking. I have a model called Post with title, body, author, logo and pub_date fields. There is a page in my app that the user can Update/Edit the post. I want the user to be redirected to the Post's Detail page if they tried to access it without being logged in. The problem is that I can't reference the Post's pk to redirect the user to the related page, If I want to put it simply: the user trying to access .../2/edit/ will be redirected to .../2/ if they aren't logged in I Tried using LoginRequiredMixin to block the user but I can't redirect the user to the relative details page. urls.py: urlpatterns = [ path('', PostListView.as_view(), name='index'), path('<int:pk>/', PostDetailView.as_view(), name='details'), path('new/', PostCreateView.as_view(), name='new_post'), path('<int:pk>/edit', PostUpdateView.as_view(), name='update_post'), ] views.py: class PostUpdateView(LoginRequiredMixin, UpdateView): model = Post login_url = reverse_lazy('details', args=[self.object.pk,]) form_class = PostUpdateForm template_name = "posts/update_post.html" I also tried: class PostUpdateView(LoginRequiredMixin, UpdateView): def get_login_url(self) -> str: super().get_login_url() UpdateView.get(self, self.request) self.login_url = reverse_lazy('details', args=[self.object.pk,]) model = Post form_class = PostUpdateForm template_name = "posts/update_post.html" But it returns an empty/none value Is LoginRequiredMixin even the right way to do this? I know this can easily be achieved without … -
Pycharm doesn't see change in main.py when starting local server
I created a project, added main to it for the main page in views and about, there are no errors, but the text is not displayed [page screenshot][https://i.stack.imgur.com/gIO02.png] nothing changes at startup, but on the main page it writes [page screenshot][https://i.stack.imgur.com/TWUNg.png] maybe I'm missing something? setting[settings][https://i.stack.imgur.com/2hkmx.png] [urls][https://i.stack.imgur.com/Yy4oH.png] [page screenshot][https://i.stack.imgur.com/OJUEw.png] from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls')) ] setting.py # Application definition INSTALLED_APPS = [ 'main', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', -
Limit the choices of a choice field in the model class
This SO answer shows how to limit a choice field in the form. However, I have a choice field with options that should never be shown to the user. Hence, I want to limit the choice field options in the model class to adhere to the DRY principle and to prevent myself from forgetting to adding code in future forms. Any idea how to achieve this? -
how to declare a serializer field containing list of ids in django
Models: class Author(Base): name = models.CharField(max_length=100, unique=True) class Book(Base): name = models.CharField(max_length=100, unique=True) class AuthorBookAssn(Base): author = models.ForeignKey(Author, on_delete=models.PROTECT) book = models.ForeignKey(Book, on_delete=models.CASCADE) I have an api to create a book, and along with the book data we would also get a list of author ids how should the serializer field be created such that it is a list of ids. for example: [1, 2, 3] This field would not be present in any models we only need to use these fields to create records in the AuthorBookAssn table. -
Separate Django permissions per group per user's companies
I have a CustomUser model, each user could be linked to multiple companies. I have initiated my application with 3 generic Django groups; viewer, editor, and supervisor and each user could be a member in only one group. Permissions I have used some global Django permissions like the {app_label}.add_{class_name} permisison with the editor group for an instance. In parallel, I used also django-guardian to have some object-level permissions to get deeper with my objects' permissions as they vary depending on some of the object attributes' values. So, at the end of the day, each user (depending on his group) has some global permissions and some object-level permissions. It works fine that way with no problem so far. Problem As stated earlier, each user is linked to multiple companies. Additionally, each object in my database is linked to a specific company. So, I need to have a higher level of permissions so that each user can deal and interact ONLY with the objects that are linked to one of his companies weather he/she is a viewer, editor, or supervisor. Proposed solutions Those are the solutions that I thought about, but each one of them has some drawbacks and I don't prefer …