Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Combine two count annotations from two filter queries
I am computing some statistics based on two different filters, but I'm not sure how I can combine both results into a single QuerySet. My code looks like this: qs1 = User.objects.filter(c1).annotate(count1=Count("id")) qs2 = User.objects.filter(c2).annotate(count2=Count("id")) I would like to create a third queryset, qs3 which has both count1 and count2. Basically I want to left join on User.id but I can't find a straightforward way of doing that. -
Django: capture authorization token from another service
I'm trying to capture an authentication token from another service authenticator. In summary, I have a form login that serve client with two options to sign in, throw the normal login, or a link to a second authenticator service which will redirect to a particular form page. Once the user is signed, this second authenticator service will redirect back to my application, with a token as param. I would like to include a kind of listener in my application (small script), in a way that when this redirect happen, I could capture and validate the token, finally, authenticate the user in the local django application. -
Django Rest Framework Viewsets Count Foreign Key
I am trying to add a additional field to my modelviewset. For example, if I have 1 parent and 3 children objects, I would like parent viewset json to look like. To get the count of the children I can do something like children = Child.objects.filter(parent.id=).count(), but I'm not sure how to get the parent id inside the view set. [ { "id": 1, "name": "parent1", "child_count": 3 } ] models.py class Parent(models.Model): name = models.CharField(max_length=100) class Child(models.Model): name = models.CharField(max_length=100) parent = models.ForeignKey("Parent", on_delete=models.CASCADE) views.py class ParentViewSet(viewsets.ModelViewSet): serializer_class = ParentSerializer children = Child.objects.filter() # ?? def get_queryset(self): queryset = Parent.objects.all().annotate(child_count=) # ?? return queryset serializers.py class ParentSerializer(serializers.ModelSerializer): child_count = serializers.IntegerField() class Meta: model = Parent fields = ["id", "name", "child_count"] -
How to make django boolean field true using a method in django models
I working on an e-commerce website I have the field about new arrivals so any product which is created in the last 30 days should be listed as a new arrival. In my models, I have a boolean field as is_new and the default value is false and I made a method to check the date whether the product is included in the new arrival list or not. but in my method new_arrival when I return self.is_new I get an invalid syntax. class Product(models.Model): name = models.CharField(max_length=200) description = models.TextField() price = models.IntegerField() picture = models.ImageField(upload_to='picture/') is_popular = models.BooleanField() is_cart = models.BooleanField() is_arrival = models.BooleanField(default=False) created_date = models.DateTimeField(aut_now_add=True) def new_arrival(self): if self.created_date >= self.created_date - self.created_date.timedelta(days=30): return self.is_new=True else: return self.is_new = False -
how to update value the field in model django of an object that belongs to a class that inherits from another abstract class?
class BaseModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True class PublicModel(models.Model): public_id = models.UUIDField(default=uuid.uuid4, editable=False, db_index=True, unique=True) class Meta: abstract = True class People(BaseModel): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) class Address(BaseModel): postal_code = models.CharField(max_length=255, null=True) public_place = models.CharField(max_length=255, null=True) class Contact(BaseModel): email = models.EmailField() phone = models.CharField(max_length=255, null=True) class Member(BaseModel, PublicModel): name = models.CharField(max_length=255) person = models.OneToOneField(People, on_delete=models.PROTECT) class Meta: abstract = True class Hub(BaseModel): description = models.CharField(max_length=255) address = models.ForeignKey(Address, on_delete=models.PROTECT) contact = models.OneToOneField(Contact, on_delete=models.PROTECT) class Partner(Member): hub = models.ForeignKey(Hub, on_delete=models.PROTECT, null=True) When updating a People or Hub object I would like the updated_at the Partner field also updated to reflect the current time of this modification. As it is, when updating a People or Hub object only its field updated_at has the updated time. What is the best approach to doing this? At the moment I am updating in a way that I think is very bad. Forcing Partner object update by passing a value to public_id so that updated_at has its updated value. Partner.objects.update_or_create(id=partner.id, defaults={'public_id': kwargs['public_id']}) -
how to extend class bassed view
I've crated class-based-view which shows content of the post.I also added the ability to make comments there, however the comment form dosn't work. views.py class PostDetailView(DetailView): model=Post template_name='blogdetail.html' pk_url_kwarg='id' def comments(request): comments=post.comments.all() new_comment=None if request.method=="POST": comment_form=CommentForm(data=request.POST) if comment_form.is_valid(): new_comment=comment_form.save(committ=False) new_comment.post=post new_comment.save() else: comment_form=CommentForm() return render(request, 'allblogs.html', {'comments':comments, 'comment_form':comment_form, 'new_comment':new_comment}) forms.py class CommentForm(forms.ModelForm): class Meta: model=Comment fields=['post','body'] blogdetail.html {% extends 'base.html' %} {% block content %} <h1>{{post.title}}</h1> <p>{{post.created_on}}</p> <p><a href="{% url 'userpage' post.author.username %}"></a>:{{post.author}}</p> <p>{{post.text}}</p> <form> {{comment_form.as_p}} <p><input type="submit" value="add"></p> {% csrf_token %} </form> {% endblock content %} -
How can we calculate average difference of datetime fields from related table in django?
I have two models Gigs and Orders. and want to calculate the average of diffrence between order_start_time and order_completed_time of every gig. check my code its giving following error Cannot resolve keyword 'orders' into field. Choices are: category, category_id, details, gig, id, images, price, reviews, seller, seller_id, title please help! Models.py (in seller app) class Gigs(models.Model): title = models.CharField(max_length=255) category = models.ForeignKey(Categories , on_delete=models.CASCADE) images = models.ImageField(blank=True, null = True, upload_to= upload_path) price = models.DecimalField(max_digits=6, decimal_places=2) details = models.TextField() seller = models.ForeignKey(User,default=None, on_delete=models.CASCADE) @property def average_completionTime(self): if self._average_completionTime is not None: return self._average_completionTime return self.gig.aggregate(Avg('order_completed_time'-'order_start_time')) I think here the problem is in average completion time how can I use 'order_completed_time'-'order_start_time' in one variable that I should refer in views.py Models.py(in buyer app) focus on item field from seller.models import Gigs class Orders(models.Model): buyer = models.ForeignKey(User,default=None, on_delete=models.CASCADE,related_name='buyer_id') seller = models.ForeignKey(User,default=None, on_delete=models.CASCADE,related_name='seller_id') item = models.ForeignKey(Gigs,default=None, on_delete=models.CASCADE,related_name='gig') payment_method= models.CharField(max_length=10) address = models.CharField(max_length=255) mobile = models.CharField(max_length=13,default=None) quantity = models.SmallIntegerField(default=1) status = models.CharField(max_length=13,default='new order') order_start_time = models.DateTimeField(default=None) order_completed_time = models.DateTimeField(default=None) created_at = models.DateTimeField(auto_now_add=True) Views.py class RetrieveGigsAPI(GenericAPIView, RetrieveModelMixin): def get_queryset(self): return Gigs.objects.all().annotate(_average_rating=Avg('orders__time')) serializer_class = GigsSerializerWithAvgTime permission_classes = (AllowAny,) def get(self, request , *args, **kwargs): return self.retrieve(request, *args, **kwargs) Serializers.py class GigsSerializerWithAvgTime(serializers.ModelSerializer): average_completionTime = serializers.SerializerMethodField() def get_average_completionTime(self, … -
In Django, how can i get the specific method of a class based view that is being called with a request?
I'm working on a middleware that needs to execute some routine based on if the method that is being called in a class based view has a decorator. I tried using resolve(url), but this only returns the class. Is there a way to get the specific method of a class based view based on a request? -
Django ModelForm: changing the format of a dropdown list with initial value
I created a form in Django with ModelForm: class FormulariMostra(ModelForm): class Meta: model = Sample fields = ("name", "sample_id_sex", "pools",) pools is a foreign key (m2m relationship). In my views.py I added an initial value for the field pools: formulari_mostra=FormulariMostra(initial={'pools':1}) In the form the options for the field pools are ordered by id in descending order. My problem is that the dropdown list appears like this: With the initial (default) value highlighted and what I want is that the value with the id with the highest number appears the first one: Is there a way to do this maintaining the initial value? Or to hide this specific value? -
Deploying Django application with Heroku and getting AttributeError: 'DatabaseOperations' object has no attribute 'geo_db_type'
I'm triying to deploy my app to Heroku, Iget this error: AttributeError: 'DatabaseOperations' object has no attribute 'geo_db_type' my DATABASE setting in the settings.py: import dj_database_url ... if DEVELOPMENT_MODE is True: DATABASES = { "default": { "ENGINE": "django.contrib.gis.db.backends.postgis", "NAME": "manage", "USER": "testuser", "PASSWORD": "Lin123", "HOST": "localhost", "PORT": "", } } elif len(sys.argv) > 0: if os.getenv("DATABASE_URL", None) is None: raise Exception("DATABASE_URL environment variable not defined") DATABASES = { "default": dj_database_url.config(), } ... import django_heroku GEOS_LIBRARY_PATH = os.getenv("GEOS_LIBRARY_PATH") GDAL_LIBRARY_PATH = os.getenv("GDAL_LIBRARY_PATH") django_heroku.settings(locals()) It's my first deploy of an app and I'm not sur about what I'm doing wrong -
Better way to fetch related object, in Self Refrencing ManyToMany Relationship?
I am working on a small application containing models CustomUser and PollQuestion. CustomUser having ManyToMany relation between itself and a CustomUser can have multiple PollsQuestion as well so there is Foreign Key relation between them. An authenticated user is only able to see polls raised by users he is following, to full-fill this requirement i have written following view**:-** def all_polls_utils(request): following = request.user.get_all_followings().values_list("id") user_id = [id[0] for id in following] all_polls = PollQuestion.objects.none() for u_id in user_id: user = CustomUser.objects.get(id=u_id) polls = user.poll_questions.all() all_polls = all_polls | polls return all_polls Main Question:- Is there in better way to do the same? Any suggestion will be highly appretiated I am posting the models bellow:- from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUser(AbstractUser): email = models.EmailField(max_length=250, null=False) name = models.CharField(max_length=50, null=False) username = models.CharField(max_length=50, null=False, unique=True) password = models.CharField(max_length=15, null=False) user = models.ManyToManyField('self', through='Relationship', symmetrical=False, related_name='related_to') USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['name', 'email'] def get_all_polls(self): pass def create_relationship(self, person): status, obj = Relationship.objects.get_or_create( to_person=person, from_person=self, ) return status def remove_relationship(self, person): Relationship.objects.filter( from_person=self, to_person=person ).delete() return 'dummy_value' def get_all_followings(self): return self.user.all() class Relationship(models.Model): from_person = models.ForeignKey(CustomUser, related_name='from_people', on_delete=models.CASCADE) to_person = models.ForeignKey(CustomUser, related_name='to_person', on_delete=models.CASCADE) And … -
List from key in Django QueryDict return one element instead of the whole list
I am using Django and I am accessing request.POST from my view. The code is as follows: data = request.POST print(data) Which returns: <QueryDict: {'name': ['Sam'], 'phone': ['+10795524594'], 'message': ['Es-sénia'], 'Coupon': [''], 'csrfmiddlewaretoken': ['xcGnoJOtnAmXcUBXe01t7ItuMC8BAFHE 6H9Egqd8BuooxLbp3ZrqvwzTZAxukMJW', 'xcGnoJOtnAmXcUBXe01t7ItuMC8BAFHE6H9Egqd8BuooxLbp3Zrq``vwzTZAxukMJW'], 'Size': ['S', 'M']}> But, whether using .dict() method or using data.get("Size"), I only get one element; not the whole list. How can I fix this? -
How can i link files to article model which uploaded by django-drf-filepond?
Info: I am using Django-drf-filepond in my django project for fileupload! django-drf-filepond has there two model TemporaryUpload(1) and StoredUpload(2). By defualt django-drf-filepond upload the files into TemporaryUpload before submiting the form. when user submit the form django-drf-filepond get data from TemporaryUpload and append it into StoredUpload model and remove it from TemporaryUpload model which data is appended into StoredUpload. What i want to do: When the user hit submit button the article is create and the appended files are linked with the article too. What I have so far: i have ArticleModel/ArticleForm. The article form data is submited and the files are appended into StoreUpload but the files are not linked it with an article. i want to linked it with article. when the user hit submit button. The data is submited by ajax. models.py class StoredUpload(models.Model): post = models.ForeignKey(Article, on_delete=models.CASCADE, null=True) # This is the article model ForeignKey # The unique upload ID assigned to this file when it was originally upload_id = models.CharField( primary_key=True, max_length=22, validators=[MinLengthValidator(22)] ) file = models.FileField(storage=DrfFilePondStoredStorage(), max_length=2048) uploaded = models.DateTimeField() stored = models.DateTimeField(auto_now_add=True) uploaded_by = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE ) def get_absolute_file_path(self): fsp = local_settings.FILE_STORE_PATH if not fsp: fsp = "" return os.path.join(fsp, … -
How to change english numbers to persian/arabic numbers in python
+1 9956755308 how to change this mobile number to persian or arabic numbers with unicode -
how to generate a qr code automatically when items are added in Django
here i want to automatically generate a unique qr code for each item when items are created in Django here is my models.py def qr_code_file_name(instance, filename): char_set = string.ascii_uppercase + string.digits dat = ''.join(random.sample(char_set*6, 12)) return 'qrimage/' + str(instance.client_id) + '/' + dat + '_' + re.sub(r'[^a-zA-Z0-9-_.]', r'_', filename); class Items(models.Model): client = models.ForeignKey("core.Client", related_name="job_items") item_name = models.CharField(max_length=512) cost_price = models.DecimalField(null=True, max_digits=10, decimal_places=2, default=0.00, verbose_name='Purchase price') common_name = models.CharField(max_length=512, blank=True, null=True) qr_code = models.ImageField(upload_to=qr_code_file_name, blank=True, null=True) Here is my forms.py class JobItemForm(BetterModelForm): def __init__(self, *args, **kwargs): self.client = kwargs.get("initial", {}).get("client") super(JobItemForm, self).__init__(*args, **kwargs) client = kwargs.get("initial", {}).get("client") ..... ..... def clean(self): cleaned_data = super(JobItemForm, self).clean() client = self.client pk = self.instance.pk name = cleaned_data.get('item_name') if pk is None: same_items = Items.objects.filter( item_name=name, client_id=client) if same_items.exists(): raise forms.ValidationError('The item with same name and part number already exists.') return cleaned_data class Meta: model = Items exclude = ('client') fields = ('item_name','common_name','cost_price','qr_code') Here is my views.py class JobItemCreateView(CustomAuthMixin, CreateView): model = Items form_class = JobItemForm context_object_name = "type" template_name = "jobs/jobitem_form.django.html" def get_initial(self): initial = super(JobItemCreateView, self).get_initial() initial['client'] = self.request.user.client initial['created_by'] = self.request.user return initial def form_valid(self, form): client = self.request.user.client self.object = form.save(commit=False) self.object.client = self.request.user.client with transaction.atomic(): self.object.save() messages.success(self.request, 'Item successfuly … -
I need a free static templates to build its back end, i need it like i am working in a team with front end and i am the back end
I need a free static templates to build its back end, I need it like I am working in a team with front end and I am the back end, how can I get a free template like this -
Django pass id from one model to another's foreign key
I have a User model and Employee model which stands for additional info about user, it has one to one field relation with User instance. When new User is created I use signals to create new Employee instance. Now I added new field to User model called 'fk_employee_id' just to have a link to this newly created Employee and I'm not sure how to do pass it's id to this User's fk field. I tried to write in my signals something like instance.user.fk_employee_id = sender after that I get ValueError Cannot assign "<class 'employees.models.Employees'>": "User.fk_employee_id" must be a "Employees" instance. So how do I fill this foreign key field in User instance when Employee is created? My User model: class User(AbstractBaseUser): email = models.EmailField(verbose_name='email', max_length=60, unique=True) username = models.CharField(max_length=30, unique=True, validators=[validate_username]) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=50) fk_employee_id = models.OneToOneField('employees.Employees', related_name='fk_employee_id', null=True,on_delete=models.DO_NOTHING) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] objects = UserManager() The Employee model is large, it has basic fields like number, address etc. Nothing special. My signals file in users app: from django.db.models.signals import post_save … -
how to convert ImageField to video html5 tag to take pricture - django
I've a project one of the models has image field to upload picture , i made it modelformset_factory to upload multiple images , but from webcam ! is there any django tips or modules to do that ? i tried this but i cant take more than one picture , and cant assign taken photo into the ImageField? my image upload model class Document(models.Model): booking =models.ForeignKey(Booking,on_delete=models.PROTECT) docs = models.ImageField(upload_to=upload_docs) def __str__(self): return str(self.booking.id) my forms.py class UploadDocumentsForm(forms.ModelForm): class Meta: model = Document fields = ['docs'] UploadDocumentFormSet = modelformset_factory(Document,form=UploadDocumentsForm,extra=1,can_delete=True) my views.py @login_required def add_new_image(request,id): obj = get_object_or_404(Booking,id=id) if request.method == 'POST': images = UploadDocumentFormSet(request.POST,request.FILES) if images.is_valid(): for img in images: if img.is_valid() and img.cleaned_data !={}: img_post = img.save(commit=False) img_post.booking = obj img_post.save() return redirect(reverse_lazy("booking:add_booking",kwargs={"room_no":obj.room_no.room_no})) else: messages.error(request,_('take a picture or choose an image')) images = UploadDocumentFormSet(queryset=Document.objects.none()) return render(request,'booking/add_img.html',{'obj':obj,'images':images}) const player = document.getElementById('player'); const canvas = document.getElementById('canvas'); const context = canvas.getContext('2d'); const captureButton = document.getElementById('capture'); const constraints = { video: true, }; captureButton.addEventListener('click', (e) => { // Draw the video frame to the canvas. context.drawImage(player, 0, 0, canvas.width, canvas.height); e.preventDefault(); }); // Attach the video stream to the video element and autoplay. navigator.mediaDevices.getUserMedia(constraints) .then((stream) => { player.srcObject = stream; }); $('#addButton').click(function() { var … -
Using apscheduler to run Django serializer code every 15 minutes and updates it's data
using serializers I wrote some code that will ssh to different machines and return some information about these machines. Every time I refresh my page, the code will ssh to the system and return real time data. After noticing how long it takes to ssh to the machines to return data and some other issues, I figured this approach is not the best. I would like to save whatever result I git from the ssh in a database/cache and retrieve this data when I refresh the page from the database/cache. I thought of using an apscheduler and have the serializer update it's data every 15 minutes instead of every time I refresh the page (ssh once every 15 minutes). I am not sure if this will work or if there are better ways to achieve this. I would be thankful if you guys give some pointers. Currently my serializer results are not saved in the database. So to achieve this do I need to save the results of the serializer in the database? and will apscheduler do the trick? -
How to sum up numbers for a foreign key model in djnago
I want to sum up the total number of votes made for a login in user that has an award going on. An award is having multiple categories and multiple nominations, what am trying to do is show the sum of votes all nominations that is related to an award model.py class Award(models.Model): Admin = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=100) image = models.ImageField(upload_to='award_images') slug = models.SlugField(max_length=150) about_the_award = models.TextField(blank=True, null=True) price = models.CharField(max_length=20, choices=PRICE, default='0.5') amount = models.DecimalField(default=0.0, max_digits=19, decimal_places=2) date = models.DateTimeField(auto_now_add=True) class Category(models.Model): Award = models.ForeignKey(Award, on_delete=models.CASCADE) category = models.CharField(max_length=100,) slug = models.SlugField(max_length=150) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.category class Nomination(models.Model): Fullname = models.CharField(max_length=120) Nominee_ID = models.CharField(max_length=100) Category = models.ForeignKey(Category, on_delete=models.CASCADE) image = models.ImageField(upload_to='nominations_images') slug = models.SlugField(max_length=150) votes = models.IntegerField(default=0) date = models.DateTimeField(auto_now_add=True) View.py @method_decorator([login_required], name='dispatch') class DashboardView(TemplateView): template_name = 'admin/Dashboard.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['user_awards'] = Award.objects.filter(Admin=self.request.user).order_by('-date') context['number_of_votes'] = Award.objects.filter(Admin=self.request.user, self.catgory.nomination).annotate(Sum('amount')) return context -
trying to save dict in my model but getting error due to foreign key
i am unable to get how to resolve this problem.i am trying to save a dict but getting error due to presence of foreign key in my leave model how can i counter this problem. views.py class leaveview(APIView): def post(self,request): token = request.data['jwt'] if not token: raise AuthenticationFailed('Unauthenticated') try: payload = jwt.decode(token,'secret',algorithms=['HS256']) except jwt.ExpiredSignatureError: raise AuthenticationFailed('Unauthenticated') user=User.objects.filter(id=payload['id']).first() serializer1=UserSerializers(user).data serializer2 = leaveSerializers(data=request.data) serializer2.is_valid(raise_exception=True) serializer={**serializer1,**request.data} del serializer["jwt"] final_data= leave(**serializer) final_data.save() return Response(data=serializer) models.py class hostel_manager(models.Model): hostel = models.CharField(max_length=100,primary_key=True) class leave(models.Model): name=models.CharField(max_length=100,null = True) father_name=models.CharField(max_length=100,null=True) branch=models.CharField(max_length=40,null=True) coer_id=models.CharField(max_length=12,unique=True,null=True) hostel_name = models.ForeignKey(hostel_manager,on_delete=models.CASCADE) room_no = models.CharField(max_length=10) where_to = models.CharField(max_length=100) reason = models.CharField(max_length=300) start_date = models.CharField(max_length = 100,null=True) end_date = models.CharField(max_length=100,null=True) phone_regex=RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+9999999999'. Up to 12 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=17) -
Getting list of context variables out of string
I have the following string in my Django app: "Hello, {{ name }}. I will arrive at {{ time }}". My goal is to come with a list of variables that is used in that string: def my_func(): # What should be done here ? my_str = "Hello, {{ name }}. I will arrive at {{ time }}" print(my_func(my_str)) # Desired output ["name", "time"] The desired output here should be ["name", "time"]. Currently, I am going to implement that invoking a regexp, but I feel like there must be some in-built function to achieve that. Any hints ? -
python gRPC error: "error": "13 INTERNAL: Failed to serialize response!" when trying to return a repeated message instead of stream in a List Request
I have django REST API that I am trying to convert into gRPC. I followed the Django grpc framework guide and created the following files: models.py class Organization(models.Model): Org_name = models.CharField(max_length=100, unique=True, primary_key=True, db_index=True) Address = models.CharField(max_length=100) Description = models.CharField(max_length=500) Number_of_emp = models.IntegerField() org.proto package org; import "google/protobuf/empty.proto"; service OrganizationController { rpc List(OrganizationListRequest) returns (Organizations) {} rpc Create(Organization) returns (Organization) {} rpc Retrieve(OrganizationRetrieveRequest) returns (Organization) {} rpc Update(Organization) returns (Organization) {} rpc Destroy(Organization) returns (google.protobuf.Empty) {} } message Organization { string Org_name = 1; string Address = 2; string Description = 3; int32 Number_of_emp = 4; } message OrganizationListRequest { } message OrganizationRetrieveRequest { string Org_name = 1; } message Organizations { repeated Organization organization = 1; } Note that Organizations is a message declared in org.proto to return a List or an array of objects services.py class OrganizationService(generics.ModelService): queryset = Organization.objects.all() serializer_class = OrganizationSerializerProto serializers.py class OrganizationSerializerProto(proto_serializers.ModelProtoSerializer): class Meta: model = Organization proto_class = org_pb2.Organization fields = '__all__' Problem I want to make a request using the rpc List(OrganizationListRequest) returns (Organizations) {} to fetch a list of all the organization in the database. However, whenever I make a call to the rpc, I get the following error: request error: … -
Django decorator to redirect to same page?
When a user tries to access a non permitted page, whats the right thing to do ? First option: Redirect to the same page they came from Second Option: Redirect to error page saying permission denied or not found Third Option: Redirect to login page I have created a decorator: from django.contrib.auth.decorators import user_passes_test from django.contrib.auth import REDIRECT_FIELD_NAME def is_student(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): actual_decorator = user_passes_test( lambda u: (u.is_authenticated and u.role == 'role1'), login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator So the above works and redirects to login if we give login_url ! How to redirect to same page from users came or which option is best ? -
Page not found - The current path matched the last one
Pulling my hair out over this. I have created a new update view but I keep getting the error Page not found 404 - The current path, post/118/build-log/54/update/, matched the last one. template: {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <a>Update</a> {% endblock content %} view: class BuildLogUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = BuildLog form_class = BuildLogForm template_name = 'buildlog_update.html' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): BuildLog = self.get_object() if self.request.user.id == BuildLog.author_id: return True return False url: path('post/<int:pk>/build-log/<int:pkz>/update/', BuildLogUpdateView.as_view(), name='build-log-update') most of what i found online was talking about the trailing / on the url but it did not make a difference for me urlpatterns: urlpatterns = [ path('', views.home, name='blog-home'), path('user/<str:pk_user>/', views.UsersCarsPosts, name='user-posts'), path('post/<int:pk>/', views.DetailPostView, name='post-detail'), path('post/<int:post_pk>/comment/<int:pk>/reply/', CommentReplyView.as_view(), name='comment-reply'), path('post/new/', views.createPostView, name='post-create'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), path('about/', views.about, name='blog-about'), path('allcars/', views.allCarsView, name='all-cars-url'), path('ajax/allcars/', views.loadModels, name='ajax-allcars'), path('ajax/load-models/', views.loadModels, name='ajax'), path('my-profile/', views.myProfile, name='my-profile'), path('post/<int:pk>/build-log-form/', views.buildLogCreate, name='build-log-form'), path('post/<int:pk>/build-log/<int:pkz>/', views.BuildLogDisplay, name='build-log-view'), path('post/<int:pk>/build-log/<int:pkz>/delete/', views.BuildLogDelete, name='build-log-delete'), path('post/<int:pk>/build-log/<int:pkz>/update/', BuildLogUpdateView.as_view(), name='build-log-update') ]