Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Don't want confirm password field in add_fieldsets in django custom UserAdmin
django custom UserAdmin required password1 and password2 in add_fieldsets.I don't need that confirm password field.I already created register form and custom user model with one password field for registration.Now when I want to register from registration form password is not being hashed because of one password field but when I register user from admin dashboard with password1 and password2 is being hashed succesfully.How to solve it.Below is my admin.py code: from django import forms from django.contrib import admin from django.contrib.auth.models import Group from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.forms import ReadOnlyPasswordHashField from .models import Employee class UserCreationForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = Employee fields = ('email', 'date_of_birth',) def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user class UserChangeForm(forms.ModelForm): password = ReadOnlyPasswordHashField() class Meta: model = Employee fields = ('name', 'email', 'password', 'date_of_birth', 'is_active') def clean_password(self): return self.initial["password"] class UserAdmin(BaseUserAdmin): form = UserChangeForm add_form = UserCreationForm list_display = ('name', 'email', 'date_of_birth','created_at','updated_at',) list_filter = () fieldsets = ( (None, {'fields': ('name', 'email', 'password')}), ('Personal info', {'fields': ('date_of_birth','gender','role',)}), ) … -
How to set different permissions depending on the request method?
I am creating an API for some polls. I need the author to be the only one who can view the votes, but the authenticated users to view the polls, questions, and to post votes. The author is just an instance of User, as like as the voters. I'm using Djoser to provide the authentication API, model serializers, and breaking my mind between CBVs and viewsets. Here are my models, if it can help. from django.db import models from django.contrib.auth import get_user_model from django.utils import timezone import datetime User = get_user_model() class Poll(models.Model): title = models.CharField(max_length=200, verbose_name="Naslov ankete") description = models.TextField(verbose_name="Opis ankete") author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="polls", verbose_name="Autor") class Meta: verbose_name = "Anketa" verbose_name_plural = "Ankete" def __str__(self): return self.title class Question(models.Model): poll = models.ForeignKey(Poll, on_delete=models.CASCADE, related_name="questions", verbose_name="Anketa") question_text = models.CharField(max_length=200, verbose_name="Tekst pitanja") pub_date = models.DateTimeField(verbose_name="Datum objavljivanja") class Meta: ordering = ["pub_date", "question_text"] verbose_name = "Pitanje" verbose_name_plural = "Pitanja" def __str__(self): return self.question_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now def verbose_question_text(self): return f"Pitanje: {self.question_text}" class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="choices", verbose_name="Pitanje") choice_text = models.CharField(max_length=200, verbose_name="Tekst opcije") # votes = models.IntegerField(default=0, verbose_name="Glasovi") class Meta: ordering = ["-votes", "pk"] verbose_name = "Opcija" verbose_name_plural = … -
Django - Display Image in Template from form ( ImageField ) without saving to Model
I have been struggling with this for a couple of days. I am trying to create an html page in which the user imports an image and resizes it ( all of this without saving anything to a model ). I want to do 3 main things: After the user selects his image, to have the image displayed even if the form has not been submittedand to display the current width and height of the image. To be able to access and modify those width and height values and to change the values. After "submit" has been sent, to have on the same page the transformed image and to be able to download. Also, I am a beginner, this being my first project. I would much appreciate if you can share some of your knowledge and leave me some tips :) forms.py class ImageForm(forms.Form): image = forms.ImageField() views.py def image_resize(request): form = forms.ImageForm() if request.method == "POST": form = forms.ImageForm(request.POST or None, request.FILES or None) if form.is_valid(): image_object = form.cleaned_data['image'] w, h = image_object.image.width, image_object.image.width print(w, h) else: form = forms.ImageForm(request.POST or None, request.FILES or None) context = {'form':form} return render(request, 'images/image-grayscale.html', context) Let me know if something else is … -
How can I use current object as variable
I'm a complete beginner at django and currently trying to create a library website. Users can issue books, and I want users who have done so, to see 2 extra buttons: unissue and extend. In my mind, this is what I want to be able to write: {% for b in Borrower %} {% if b.book == {{book}} %} {% if b.student == {{user}}%} #buttons {% endif %} {% endif %} {% endfor %} Obviously the error happens at {{book}} and {{user}} because it cannot parse the rest. I'm not sure what the correct syntax is to access current object and user being viewed. -
Django rest framework PUT method work with Postman but not Javascript FormData
Currently in a model, I defined a JsonField: bounding = models.JSONField(blank=True, null=True) The Postman request work well: But when I use XMLHttpRequest in Javascript: let data = new FormData(); data.append('bounding', JSON.stringify(myArray)); let xhttp = new XMLHttpRequest(); xhttp.open('PUT', '/image/', true); xhttp.send(data); The bounding field is always None. What can I do to fix this problem? -
Django CSRF Cookie Not saved but is sent in request
I have made a Django Rest api backend, which is called by a React application using axios. When the user logs in the csrf token is not saved in the cookies (the cookie field is "") but is sent in every request, but Django still says that it is not set or is invalid (because it must be set in header).I have tried to implement some solutions that I have found on other stack overflow questions, but it hasn't fixed the problem. My question is what is the best way to make Django read the csrf cookie from the request or is there a way for react to get it so I can send it manually in every request. The csrf cookie is set to samesite:none and it is secure (Because Firefox deletes the cookie if it isn't set up that way). Thanks in advance for every answer I get. -
Django Rest Global Exception Handling in debug=False
You know Django rest framework return 500 internal as white page server error without details in debug=False So we don't have a chance to check what actually causes the error but debug=True does it. The problem is, if you enable debug=True in production, it means we just put in security risk, also it exposes all the configuration of the settings.py file. As i am using django rest framework, You may suggest me to like this: try ... except Exception as e: raise APIExcption(e) But the problem with above solution, i have to handle this exception everywhere and every classes which i dont like. I want to handle it one place only. I googled, search on stackoverflow, couldn't found any better solution for this. Can you please help me to get it done correctly? -
define and display date based on TruncMonth date as a url in django
i'm trying to show to show monthly reports ( profit and cost ) based on TruncMonth, i have two models class Invoice(models.Model): title= models.CharField(max_length=80) price = models.DecimalField(max_digits=20,decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) class Cost(models.Model): title= models.CharField(max_length=80) price = models.DecimalField(max_digits=20,decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) my views.py def monthly_reports(request,date): total_monthly = Invoice.objects.annotate(date=TruncMonth('created_at')).values('date').filter(date=date).annotate( total_price=Sum(F('price'))) total_costs = Cost.objects.annotate(date=TruncMonth('created_at')).values( 'date').filter(date=date).annotate(total_price=Sum(F('price'))) context = { 'total_monthly':total_monthly,'total_costs':total_costs,'date':date } return render(request,'monthly_report.html',context) urls.py app_name= 'reports' path('reports/<int:date>',monthly_reports , name='monthly_reports'), my template <a href="{% url 'reports:monthly_reports' i.date %}"><td class="p-2 text-xs border border-purple-900 md:text-base textpurple">{{i.date | date:'d-m-Y'}}</td></a> but it raise this error Reverse for 'monthly_reports' with arguments '(datetime.datetime(2021, 7, 1, 0, 0),)' not found. 1 pattern(s) tried: ['reports/(?P[0-9]+)$'] does i done something wrong ? how to achieve it please ? -
Why flutter is unable to send data using POST method to django rest api?
This is my part of code in auth.dart: Future<void> signup(String username,String email, String password) async { final url = 'https://ymukeshyadavmrj.pythonanywhere.com/register/'; try { final jb = jsonEncode({ 'username': username, 'email':email, 'password':password, 'password2':password, }); print(jb); final response = await http.post(url,body:jb); final responseData = json.decode(response.body); if (responseData.containsKey('code')) { throw HttpException(responseData['message']['message']); } _token = responseData['access']; print("Token =======$_token"); _refreshToken = responseData['refresh']; It is returning null on printing _token after assigning it responseData['access']. Note: I am using jwt authentication for my project and api is working fine in Postman. -
Django - JQuery autocomplete custom select from multiple fields
I have a user search that autocompletes by both ticker and name. The search results come back as "{{ticker}} - {{name}}". When a result is selected, I want it to fill with only the ticker, where as it currently fills with "{{ticker}} - {{name}}". Here is my python code: if 'term' in request.GET: tickers = Company.objects.filter(ticker__istartswith = request.GET.get('term')) | Company.objects.filter(name__istartswith = request.GET.get('term')) companies = [] for ticker in tickers: companyTicker = ticker.ticker + " - " + ticker.name companies.append(companyTicker) return JsonResponse(companies, safe=False) and here is my javascript: <script> $( function() { $( "#ticker3" ).autocomplete({ source: '{% url "financials:get_financials" %}' }); $( ".selector" ).autocomplete({ select: function ( event, ui ) { ticker.ticker } }); $( ".selector" ).on( "autocompleteselect", function( event, ui ) { ticker.ticker }); } ); </script> Any help greatly appreciated! -
Unable to assign a Foreign Key in DJango
I am trying to save data into a mysql database using 2 tables main and public, but am unable to store data into the public table. ERROR: ValueError: Cannot assign "4": "public.unq_id" must be a "main" instance. Models.py: class main(models.Model): unq_id = models.BigAutoField(primary_key=True) email = models.CharField(max_length=80) password = models.CharField(max_length=256) first_name = models.CharField(max_length=80) last_name = models.CharField(max_length=80) dob = models.CharField(max_length=80) phone = models.BigIntegerField(default=0) status = models.CharField(max_length = 12, default = 'active') def __str__(self): return self.unq_id def verify_password(self, raw_password): return pbkdf2_sha256.verify(raw_password, self.password) class public(models.Model): unq_id = models.OneToOneField(main, on_delete=models.CASCADE, primary_key = True) lang = models.CharField(max_length=80) expert = models.CharField(max_length=80) country = models.CharField(max_length=80, default = "None") Views.py: Email1=request.POST['Email'] a = main.objects.filter(email = Email1).exists() if a is True: error = "Email taken" return render(request, 'Main/registration.html',{'error':error}) password1=request.POST['password'] password = pbkdf2_sha256.encrypt(password1,rounds=12000,salt_size=32) Fname=request.POST['Fname'] Lname=request.POST['Lname'] DOB=request.POST['dob2'] lang= request.POST['lang'] phone=request.POST['phone'] c = main.objects.filter(phone = phone).exists() if c is True: error = "phone number taken" return render(request, 'Main/registration.html',{'error3':error}) country=request.POST['country'] r = countrycode.objects.filter(country = country).exists() if r is True: s = countrycode.objects.get(country = country) country = s.code main2=main(email=Email1,password=password,first_name=Fname,last_name=Lname,dob=DOB,phone=phone) main2.save() mainobj= main.objects.get(email = Email1) public2=public(lang=lang,expert="false",country=country,unq_id=mainobj.unq_id) public2.save() When I look in my database, the mainobj gets stored but the public object doesn't get saved; despite having the same "unq_id" Please do help , thank you -
Why the hell django custom auth is tough for beginners?
I recently got my first freelancing project in django - the requirement is simple ( i dont wanna say fully). It has a simple auth and dashboard has few functions thats it ! But the problem here is - clients asking for registration with the following fields: Name Phone Email And other defaults like password etc ! I have seen 100's of youtube videos, everyone is using default django auth but no one is clearly explaining how to use custom user model to authenticate ? Please someone help me to understand what are the steps to be followed ! Figured out steps: - We need to use AbstractBaseUser & UserManager in customusers model and create two class inherit - Then need to admin respective admin things and add as per documentation But how to perform email verification, and if i use above things - then will i be able to use all auth functions in django like to check if authenticated etcs ? How the permissions works if i use to custom model - like this there are 1000's questions with unknow answer ! Totally getting frustrated as a beginner freelancer Please help -
Google Cloud App Engine Deploy Fail (Django)
I'm trying to deploy my app but I keep getting this error on the website: Error: Server Error The server encountered an error and could not complete your request. Please try again in 30 seconds. The error logs for this are: 2021-07-15 12:36:04 default[20210715t122912] [2021-07-15 12:36:04 +0000] [20] [INFO] Worker exiting (pid: 20) 2021-07-15 12:36:04 default[20210715t122912] [2021-07-15 12:36:04 +0000] [23] [ERROR] Exception in worker process 2021-07-15 12:36:04 default[20210715t122912] Traceback (most recent call last): File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/workers/gthread.py", line 92, in init_process super().init_process() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/workers/base.py", line 119, in init_process self.load_wsgi() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi self.wsgi = self.app.wsgi() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 49, in load return self.load_wsgiapp() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp return util.import_app(self.app_uri) File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/util.py", line 358, in import_app mod = importlib.import_module(module) File "/opt/python3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 855, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/srv/main.py", line 1, in <module> from booking.wsgi import application File … -
Can someone please explain me what exactly going on here? (Django dependent dropdown + ajax)
I am following a tutorial on the dependent dropdown in Django. However not able to understand some lines of code... https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html snippet def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['city'].queryset = City.objects.none() # have to understand this line of code if 'country' in self.data: try: country_id = int(self.data.get('country')) self.fields['city'].queryset = City.objects.filter(country_id=country_id).order_by('name') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['city'].queryset = self.instance.country.city_set.order_by('name') -
Ajax seems to execute only once
I'm using Jquery's ajax method to update the data on the screen (go to the next data item in the database). When I click the next button I want it to go to the data record with the next id (current_id + 1). It works on the first click but not after that, I'm pretty new to Django and WebDev so let me know if you need any more context. Here's the jquery code: {% block javascript %} <script type="text/javascript"> $(document).on('click','#next',function(){ var id = "{{record.id}}"; console.log(id) $.ajax({ url : "{% url 'next' %}", data : {'id':id}, dataType: 'json', success : function(data){ console.log("success"); console.log(data); $("#word").text(data['word']); $("#meaning").text(data['meaning']); } }) }) </script> {% endblock %} Here's the code for the view that handles the request: def next(response): id = int(response.GET.get('id',None)) record = Words.objects.filter(id = id+1).first() data = { 'word' : record.word, 'meaning' : record.meaning } return JsonResponse(data) -
using class base view facing a issue of reverse not found
i am using a class base d view for section.html in which i trying to implement add to cart functionality with the help of forms but after clicking add to car but it showing error Reverse for 'section' with no arguments not found. 1 pattern(s) tried: ['(?P<subject_id>[0-9]+)/Sections/$'] here is my views.py @method_decorator(login_required, name='dispatch') class Sections(View): def post(self, request, subject_id): sections =request.POST.get('section') print(sections) return redirect('subjects:section') def get(self, request, subject_id): subject = get_object_or_404(Subject, pk=subject_id) # retrieve the subject sections = subject.section.all() # get the sections related to the subject return render (request, 'sections.html',{"section_list" : sections }) my urls.py urlpatterns = [ path('<int:subject_id>/Sections/', Sections.as_view(),name='section'), ] my section.html <ul class="sec"> {% for section in section_list %} <div class="card col-11"> <div class="card-header"> {{ section.title }} </div> <div class="card-body"> <h5 class="card-about">{{ section.about_section }}</h5> <br> <i class="price fas fa-rupee-sign"> {{ section.price }}</i> <br> <br> <i class="icon text-white fas fa-chalkboard-teacher"> {{ section.teacher }}</i> <i class="icon text-white fas fa-clock"> {{ section.content_duration}}</i> <i class="icon text-white fas fa-tags"> {{ section.subject.name }}</i> <form action="#" method="POST"> {% csrf_token %} <input hidden type="text" name="section" value="{{section.id}}"> <input type="submit" class="btn btn-outline-primary" value="Add To Cart"> </form> </div> </div> {% endfor %} </ul> my section model is contected with another models name subject with foriegn key -
Question about getting an IP address in Genie
I am a novice in Django and I got this code from a specialist, but I do not know how it works and how anyone can explain how it works? def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip -
Annotate Sum in Django
gap_condition = Feedback.objects.filter(Q(register_date__gte='2020-05-01')) \ .annotate(gap=(Cast('create_at', DateField()) - F('register_date'))).values('student_id') register_gap = Student.objects.values('teacher').distinct().order_by('teacher').annotate( gap_chart=Sum('???', filter=Q(id__in=gap_condition)) ).values('teacher', 'gap_chart') First, the gap is output as a queryset. I would like to add the 'gap' obtained above in place of the question mark. However, when I get annotate sum in Django, I get an error saying that I can only select fields from the model I am using. Is there a way to reference fields from other models? The final thing I want to find is the difference between the register date of the students assigned to each teacher and the date the register date was entered into the computer. -
Django Inline Formset Factory Unrequire a field
I'm working on restaurant management system. I'm Taking orders, and add order items to orders with inline formset factory.But for some reason extra fields require an input, and it's annoying because I can't submit my form unless I fill all the fields.I'm pretty new to formsets so any help/suggestion is appreciated. Here is my views.py : class OrderOrderItemView(SingleObjectMixin, FormView): model = Order template_name = 'order/add-order_item.html' def get(self, request, *args, **kwargs): self.object = self.get_object(queryset=Order.objects.all()) return super().get(request, *args, **kwargs) def post(self, request, *args, **kwargs): self.object = self.get_object(queryset=Order.objects.all()) return super().post(request, *args, **kwargs) def get_form(self, form_class=None): return Order_OrderItemFormset(**self.get_form_kwargs(), instance=self.object) def form_valid(self, form): orderitem_instance = form.save() for order_item in orderitem_instance: food = order_item.food_size.food order_item.food = food order = Order.objects.get(id=order_item.order.id) order_item.total_cost += str(float(order_item.food_size.price) * float(order_item.quantity)) order.total_cost = float( order_item.total_cost) + order.total_cost order.save() order_item.save() return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return reverse('menu:detail-order', kwargs={'pk': self.object.pk}) And my forms.py: Order_OrderItemFormset = inlineformset_factory( Order, Order_Items, fields=('food_size', 'quantity'), extra=5, can_delete=False) -
Django model inheritance column check
I'm working on a game website with multiple different gamemodes. I have basemodel that I want to generate unique join link for each model that inherits from basemodel.py. from django.db import models import random import string class Room(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=32) description = models.TextField(blank=True) date_created = models.DateTimeField(auto_now_add=True) @classmethod def generate_join_code(cls): while True: unique_code = ''.join(random.choices(string.ascii_uppercase, k=6)) if cls.__name__.objects.filter(join_code=unique_code).count() == 0: break return unique_code join_code = models.CharField(max_length=6, default=generate_join_code) class Meta: abstract=True And the other file that inherits from the Room model: from core.basemodel import Room class tttRoom(Room): pass I can't find a way to pass a specific model name into generate_join_code. It has to check the current model that it works on and I need a way to pass that information into it. And when I run python manage.py makemigrations it raises AttributeError: module 'core.basemodel' has no attribute 'generate_join_code'. Is there any way to create join_code automatically or I need to create it each and every time I add a new model? I don't need the join_code to be unique for all the database but just for that table that uses it. Thanks in advance -
Running Django applications on white ip
I got a white ip from my ISP, it's 195.214.223.143 I have an application with microservices, which all I want to run on this IP. I have a main server app (which I will deploy with nginx and gunicorn) and 6 microservices (user-service, session-service, mail-service and so on), which I want to deploy only with gunicorn (just cause endpoints from these services can be called only through main server, so I don't really care about outside attack). Now for tests I try to run services only with gunicorn (I use a dedicated laptop for this purpose). I use such a command to run every service "gunicorn --bind 0.0.0.0:PORT --workers 4 APPNAME.wsgi" (4 workers cause I have cpu with 2 cores (i3)) So I set this in every project: ALLOWED_HOSTS = ['195.214.223.143', '127.0.0.1', '0.0.0.0'] I also use TP-Link router and I used "Port Forwarding" tab in settings to forward ports (8000, 5000, 5001, 5002, 5003, 5004, 5006). So when I run all this stuff I can reach my app with localhost url and with http://195.214.223.143:5001 (that's url for my main server). But trouble is that I can't get stable using of my ip on another devices. Sometimes I can open my … -
set category in product using apis rest framework
I want to set category in product using category that exist not creating a new one but i get this response. "category": "slug": "product category with this slug already exists." this is view : def creat_product_view(request): user = request.user product = Product(user=user) data = {} if 'category_slug' in request.data: try: category = ProductCategory.objects.get(slug=request.data['category_slug']) except ProductCategory.DoesNotExist: data['response'] = 'category dose not exist' return Response(data=data, status=status.HTTP_404_NOT_FOUND) request.data['category'] = CategorySerializer(category).data else: request.data['category'] = CategorySerializer(ProductCategory.objects.get(slug='another')).data serialized_data = ProductSerializer(product, data=request.data) if serialized_data.is_valid(): product = serialized_data.save() data['response'] = 'successfully created' data['title'] = product.title data['cost'] = product.cost data['description'] = product.description data['slug'] = product.slug else: data = serialized_data.errors return Response(data=data) serializers.py class CategorySerializer(serializers.ModelSerializer): class Meta: model = ProductCategory fields = "__all__" class ProductSerializer(serializers.ModelSerializer): user = serializers.SlugRelatedField( read_only=True, slug_field='email' ) category = CategorySerializer(many=False) class Meta: model = Product fields = "__all__" -
Display ManyToManyField in Django Admin Detail view
I have a model Order which has a ManyToManyField of CartItems. I want to display this in the django admin panel. I tried the following approach: (admin.py) class OrderDisplay(admin.ModelAdmin): list_display = ['get_items'] fieldsets = ( (None, {'fields':('user','completed','time_created')}), ) def get_items(self, obj): return "\n".join(item.item.name + "-" + str(item.quantity) for item in obj.items.all()) By adding get_items in list_display its being displayed as the title of orders in the list. I want the list of items to be displayed when the admin clicks on the order, not on the title. How can I display a ManyToManyField in the DetailView -
create custom user permissions manually django
i'm trying to create custom permissions , for every user(admin) we have several permissions like (delete,creaet,post,update,view a specific part of the app) , every users have multiple permissions class UserPermission(models.Model): type_of_permission = models.CharField(max_length=30,unique=True) active = models.BooleanField(default=True) def __str__(self): return self.type_of_permission class Meta: db_table = 'user_permission' class UserAccount(AbstractBaseUser): username = models.CharField(max_length=80,unique=True) active = models.BooleanField(default=True) permis = models.ManyToManyField(UserPermission) class Post(models.Model): admin = models.ForeignKey(UserAccount,on_delete=models.CASCADE) title= models.CharField(max_length=80) for example we have type_of_permission = create new post , active = True type_of_permission = delete posts , active = False and so on ,and a user wants to delete a post , i want to filter users by if request.user has delete posts active = False then dont allow that user to delete the object def delete_posts(request,id=id): obj = get_object_or_404(Post,id=id) #how to filter if the requested user have permission to delete post obj.delete() #if not have permission then messages.error(request,'you dont have permission to delete') is it possible to define permissions manually please ? -
Django filter a related model only if a foreign key is not saved as an attribute
I have the following models: class Route(Model): first_stop = models.ForeignKey( Stop, help_text="The departure point", ) last_stop = models.ForeignKey( Stop, help_text="The destination point", ) class Stop(Model): location = models.CharField(max_length=100) route = models.ForeignKey( Route, related_name="stops", related_query_name="stop", help_text="the route that this stop belongs to", ) a route has at least two stops and references to the first and last stops are kept as attributes. I'm trying to filter routes that pass through a specific location but not just on the first or last stop. If the location is only present on its first or last stop then that route should be excluded. If the location is present on an intermediate stop(not first_stop or last_stop) then that route should be included regardless of whether that location is also present on its first or last stop or not. if a route has only two stops then it should be excluded. I made a solution but it's very verbose and ugly and probably inefficient: routes_to_exclude = [] for route in result: # result is a queryset matched_stops = False for stop in route.stops.exclude( pk__in=(route.first_stop_id, route.last_stop_id) ): # to make sure the desired location isn't only on the first or last stop if str(stop.location) == desired_location: matched_stops …