Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Like text to icons or svg image and claps like medium implementation on my post like
**how can i use icon for like ** Is there a method to include claps like medium for my like post how to implement Clap html file for like post <span class="count"> <span class="total">{{ total_likes }}</span> like{{ total_likes|pluralize }} </span> <a href="" data-id="{{ post.id }}" data-action="{% if request.user in users_like %}un{% endif %}like" class="like button"> {% if request.user not in users_like %} Like {% else %} Unlike {% endif %} </a> ajax script to like $('a.like').click(function(e){ e.preventDefault(); $.post('{% url "blog:like" %}', { id: $(this).data('id'), action: $(this).data('action') }, function(data){ if (data['status'] == 'ok') { var previous_action = $('a.like').data('action'); //toggle data-action $('a.like').data('action', previous_action == 'like' ? 'unlike' : 'like'); //toggle link text $('a.like').text(previous_action == 'like' ? 'Unlike' : 'Like'); //update total likes var previous_likes = parseInt($('span.count .total').text()); $('span.count .total').text(previous_action == 'like' ? previous_likes + 1 : previous_likes - 1); } }); }); -
Django Template Round to Nearest Non Zero
Problem: Rounding variable size input to variable lengths based on the trailing decimals. Description: I am building a recipe app for cocktails meaning I want to have some variability with storing measurements in ml at varying lengths. Let's say I have a recipe consisting of: 50ml Gin 25ml Lime Juice 12.5ml Simple Syrup 1.25ml Maraschino Liqueur (This is just an example recipe - it's gonna taste like sour piss - don't bother making it) This is currently stored in this model: class Ingredients(models.Model): SLU = ForeignKey("Spec", on_delete=CASCADE) PLU = ForeignKey("Product", on_delete=CASCADE) measure = models.DecimalField(decimal_places=3, max_digits=5) This means the values in storage are: 50.000 Gin 25.000 Lemon Juice 12.500 Simple Syrup 1.250 Maraschino Liqueur How do I best get these values displayed to the user with no trailing zeroes in the same way as originally displayed above when first showing the recipe? Solutions Using Django's |floatformat does not solve the problem as it displays as follows: floatformat:"2": 50.00, 25.00, 12.50, 1.25 floatformat:"-2": 50, 25, 12.50, 1.25 Using a regular Math rounding function in python backend will cause similar results as above unless I make it longer with hard coded options for all 3 possible decimals. Any good suggestions for this? -
Field 'id' expected a number but got 'A1'
When I visit http://localhost:8000/details/A1/ I get this error “Field 'id' expected a number but got 'A1'”. What am I doing wrong? models.py class Chips(models.Model): id = models.AutoField(primary_key=True) brand = models.CharField(max_length=300) cost = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return "{}: {}, {}".format( str(self.pk), self.brand, self.cost, ) views.py from django.shortcuts import render, redirect, get_object_or_404 from .models import * def details(request, pk): w = get_object_or_404(Chips, pk=pk) return render(request, 'MyApp/details.html', {'w': w}) urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('details/<pk>/', views.details, name='details'), ] -
How to get BSSID of Access Point from client?
I am developing a Django application and I need to know to which access point the client/user is connected to. By searching in the internet I found out that I can find it using the BSSID of the access point. The problem is I am unable to find a way to get that BSSID. So, I want to know is there any information in the request object of Django. If not, is there any other way to get the BSSID using JavaScript. (Note: Please share any way that can be helpful to me). If all those can't work can we set some configurations in the access point and use them to find the client access point (Yes, I have the option to set them as we are developing this application to be run on a organization server). Any information will be appreciated. Thank you in advance. -
get() got an unexpected keyword argument 'pk_news'
views.py: class NewsCommentsUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Comment fields = ('comment',) template_name = 'news/comment_edit.html' def get_absolute_url(self): return reverse_lazy('news_detail', args=[str(self.object.news.id)]) def get(self, request): return Comment.objects.get(pk_news=self.request.GET.get('news_id'), pk=self.request.GET.get('id')) def test_func(self): obj = self.get_object() if self.request.user.has_perm('news.all') or self.request.user.has_perm('news.delete_news') or obj.author == self.request.user: return True urls.py: path('<int:pk_news>/comment_edit/<int:pk>/', NewsCommentsUpdateView.as_view(), name='comment_edit'), path('<int:pk_news>/comment-delete/<int:pk>/', NewsCommentsDeleteView.as_view(), name='comment_delete'), template: {% for comment in object.comments.all %} <a href="{% url 'comment_edit' pk_news=news.pk pk=comment.pk %}">Edit</a> | <a href="{% url 'comment_delete' pk_news=news.pk pk=comment.pk %}">Delete</a> {% endfor %} It does not work and gives me an error (get() got an unexpected keyword argument 'pk_news'). -
look up the value in jsonfield of django
The model contains a jsonfield: class MyModel(Model): test_result = JSONField() the data to be handled is dynamic, {'test1':100,'test2':95,'test9':80,...} , { 'test2':60, 'test3':80,'test6':70,... } ... I want to find all the test results of 'test2' and save them into a list. all_score_of_test2 =[x.test_result['test2'] for x in MyModel.objects.filter(test_result__has_keys=['test2'])] it works but the performance is not good. Is there any faster way to do the task? I am using postgresql13.1 -
Django - 'Paginator' object has no attribute 'get_page'
I am trying to use paginator for the first time on my django. I am having problems getting it to work. When i run it I get the error AttributeError: 'Paginator' object has no attribute 'get_page'. I cannot seem to resolve it. Can somebody help me please? The error seems to be o the line def index(request): page = request.GET.get('page', '1') posts = BoardTbl.objects.raw( # ORM 미사용 'SELECT b.idx, u.last_name, u.first_name, b.subject, b.content, b.date ' 'FROM board_tbl b ' 'JOIN auth_user u ' 'ON b.writer = u.id' ) paginator = Paginator(posts, 15) page_obj = paginator.get_page(page) #count = len(list(posts)); context = {'posts': page_obj} # return render(request, 'post/index.html', {'posts':posts, 'count':count}) return render(request, 'post/index.html', context) -
Why does my Environ import doesn't import .env variables?
I'm building a Django app but I've got an issue... I've imported the environ package in order to store all my variables in a .env file, but actually it seems my app doesn't read it and I can't get why. Here is my .env file: DEBUG=True SECRET_KEY='9l=jjp#g0-mbdfsntqww91&s9b^a!kj44ljl4f5h!+uoft$h6u' DB_NAME=djcrm DB_USER=djcrmuser DB_PASSWORD=djcrm123 DB_HOST=localhost DB_PORT= EMAIL_HOST= EMAIL_HOST_USER= EMAIL_HOST_PASSWORD= EMAIL_PORT= DEFAULT_FROM_EMAIL=davide@davidemancuso.com Here is my settings.py file: from pathlib import Path import environ env = environ.Env( DEBUG=(bool, False) ) READ_DOT_ENV_FILE = env.bool('READ_DOT_ENV_FILE', default=False) if READ_DOT_ENV_FILE: environ.Env.read_env() DEBUG = env('DEBUG') SECRET_KEY = env('SECRET_KEY') # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Third party apps 'crispy_forms', 'crispy_tailwind', 'tailwind', 'theme', # Local apps 'leads', 'agents', ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'djcrm.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / "templates" ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'djcrm.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': env("DB_NAME"), 'USER': env("DB_USER"), 'PASSWORD': env("DB_PASSWORD"), 'HOST': env("DB_HOST"), 'PORT': env("DB_PORT"), } } # Password … -
Pass query params but got error that query params is required
I write some unit tests for my django app. but test failed, because of that query params missed but I passed the quarry params. this is one of my tests: def test_delete_card(self): url = reverse("postideas-urls:DeleteCard") card_pk=self.test_card_second.id data3 = { 'card_pk':card_pk } self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + self.token) response = self.client.delete(url,params=data3) print(response.__dict__) self.assertEqual(response.status_code, status.HTTP_200_OK) and this is my response.__dict___ ... '_container': [b'{"error":"card_pk query param(s) are required"}'], '_is_rendered': True, 'data': {'error': 'card_pk query param(s) are required'}, 'exception': False, 'content_type': None, 'accepted_renderer': <rest_framework.renderers.JSONRenderer object at 0x7fb757f3aad0>, 'accepted_media_type': 'application/json', 'renderer_context': {'view': <postideas.views.DeleteCardView object at 0x7fb757f37d10>, 'args': (), 'kwargs': {}, 'request': <rest_framework.request.Request: DELETE '/api/v1/postideas/Delete_Card/'>, 'response': <Response status_code=400, ...'request': {'PATH_INFO': '/api/v1/postideas/Delete_Card/', 'REQUEST_METHOD': 'DELETE', 'SERVER_PORT': '80', 'wsgi.url_scheme': 'http', 'params': {'card_pk': 5}, 'QUERY_STRING': '', 'HTTP_AUTHORIZATION': 'Bearer ... -
Want to edit filename in django form
from django.shortcuts import render, redirect, reverse from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.decorators import login_required from .forms import UploadFileForm, EditFileName from .models import Image @login_required def home(request): context = {} if request.method == "PUT": print(request.FILES) form2 = EditFileName(request, request.FILES) if form2.is_valid(): username = request.user image = request.FILES["image"] image_text = form2.cleaned_data.get("image") obj = Image.objects.filter(id = ).update( image_text = image_text ) else: form2 = EditFileName() if request.method == "POST": print(request.user) form = UploadFileForm(request.POST, request.FILES) print(request.FILES) if form.is_valid(): username = request.user image_text = request.FILES["image"].name image = form.cleaned_data.get("image") obj = Image.objects.create( username=username, image_text=image_text, image=image ) obj.save() print(obj) else: form = UploadFileForm() context['form'] = form context['data'] = Image.objects.all() context['form2'] = form2 print(context) return render(request, "registration/success.html", context) def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') user = authenticate(username=username, password=password) login(request, user) return redirect('home') else: form = UserCreationForm() return render(request, 'registration/register.html', {'form': form}) this is my views.py, i want to use form2 to edit the filename of the image that i uploaded in form. from django import forms from django.contrib.auth.models import User from django.forms.fields import CharField class UploadFileForm(forms.Form): image = forms.ImageField() class EditFileName(forms.Form): filename = CharField(max_length=200) this is my forms.py. I just want … -
How to handle data concurrency in web applications with rest API Django/Spring
How is data concurrency handled in web applications, does it have something to do with multi threading, I have developed a few web applications but didn't came across this problem until now. An audio file on my website has 10 plays If 50 people play the audio at the same time, how do I ensure that the play count is now 60 and not 11. Which technology should be used for this kind of problem , is it possible with Django (rest api) ? If yes how ? I'm an amateur all criticism is welcome. -
Internal Server Error occurs during using flask
Internal Server Error The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application I got that error using flask how can I solve this error Thank you in advance. -
Uncaught SyntaxError: Unexpected identifier at my fetch headers
I try to runserver and it runs but my chrome console identifies error at headers and it does npt execute the add to cart. I have refreshed my page several times. P have even turned off my server and ran my server multiple times but same issues remain. My Cart.js File var updateBtns = document.getElementsByClassName('update-cart') for (var i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:',productId, 'action:',action) console.log('USER:',user) if (user === 'AnonymousUser') { console.log('user is not logged in') }else{ updateUserOrder(productId, action) } }) } function updateUserOrder(productId, action){ console.log('user is logged in, sending data') var url = '/update_item/' fetch(url, { method:'POST' headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, } body:JSON.stringify({'productId':productId, 'action':action}) }) .then((response) =>{ return response.json() }) .then((data) =>{ console.log('data:', data) }) } This is my views.py which does not execute on my console My views.py from django.shortcuts import render from django.http import JsonResponse import json from .models import * # Create your views here. def store(request): products = Product.objects.all() context = {'products':products} return render(request, 'store/Store.html', context) def cart(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() else: items = [] order = {'get_cart_total':0, 'get_cart_items':0} context = {'items':items, 'order':order} return … -
Virtual Env name not written in terminal when activated
I am using atom text editor and when I am activating my virtual environment the name is not written in the start so while programming I am not aware that the environment is activated or not. The environments in my library are as following. when I activate using command activate MyDjangoEnv but the name of the environment is not shown in brackets like it is usually there. I am always confused that the environment is activated or not while installing the libraries. Following picture explains my issue. -
Writing custom ORM in Django
I was interviewed for a position as a backend developer. What the interviewer said was they don't use Django in particular, "we write our own custom ORMs". What did he mean by that? I kept thinking about what he said. What did he mean by that? What I have understood till now is ORM does most of our work so that we don't need to write SQL queries by ourselves. ORM converts all our Python/Django code into SQL queries which makes it so much easier. My next question might be related to this as well. The interviewer asked whether I can use another architecture while building the app from Django/Django Rest. I asked if he meant another framework. But he said no and said not another framework but another architecture. What did he mean by this? -
Items of a Model are not counting seperatly
I am building a BlogApp and I am stuck on a Problem. models.py class Album(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,default='',null=True) file = models.ImageField(upload_to='posts',null=True,blank=True) video = models.FileField(upload_to='videos',null=True,blank=True) views.py def new_story(request): file = Album.objects.filter(user=request.user) context = {'file':file} return render(request, 'mains/new_story.html', context) What i am trying to do :- There are two fields in the Albummodel AND I am trying to count file and video separately. when i count in the template using {{ file.count }} then it count all the files and videos BUT when i try to count separately {{ file.video.count }} then it is not showing. I have no idea, how can i count separately. Any help would be Appreciated. Thank You in Advance. -
Method Not Allowed (POST): Django Todo app
I am working on a Django todo list app that allows you to add and remove tasks and categorize them. There's also a user authentication function to login and signup. I am stuck with a bug when I try to add or remove a task saying "Method Not Allowed (POST) 405 0. I think it's something with the urls, but I kept working on it and still can't resolve it. Here's a link to what I am talking about. The task form is in todoApp/pages/templates/home.html: https://github.com/AdhamKhalifa/COM214-Final-Project/tree/main/todoApp/pages/templates -
Django Rest Framework parse error in PUT API
I'm using DRF (Django Rest Framework) to develop API's I am getting below error. rest_framework.exceptions.ParseError: JSON parse error - Expecting value: line 1 column 1 (char 0) Everything I have created as per the documentation Below is my code def blog_detail(request, pk): try: single_blog = Blog.objects.get(pk=pk) except Blog.DoesNotExist: return HttpResponse(status=404) if request.method == "GET": if pk: serializer = BlogSerializer(single_blog) return JsonResponse(serializer.data, safe=False) if request.method == "PUT": data = JSONParser().parse(request) serializer = BlogSerializer(single_blog, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) In the above code, GET is working properly PUT is having some errors. I'm using Postman to hit API Data: { "blog_title": "My blog using API", "blog_description": "Update: This is a test blog. UPDATED.", "blog_user_id": 10, "user_name": "admin" } -
How I can pass a model class attribute as a context from a class based view
I want to pass the Post model's title as a context to the template from my class-based view called PostDetailView. This title context would be the title of my template. How I can do this? All the necessary codes are given below plz help. models.py: from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=150) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return f'{self.author}\'s Post' views.py: from django.shortcuts import render from .models import Post from django.contrib.auth.decorators import login_required from django.views.generic import ListView, DetailView from django.utils.decorators import method_decorator @method_decorator(login_required, name='dispatch') class PostListView(ListView): model = Post context_object_name = 'posts' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = 'Home' return context class PostDetailView(DetailView): model = Post def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = '?' return context -
django filter across multiple model fields using predefined choices
I am trying to filter through a model with the choices defined before the filter. store_choices = ( ('harveynichols', 'Harvey Nichols'), ('houseoffraser', 'House of Fraser'), ('selfridges', 'Selfridges'), ('lookfantastic', 'LOOKFANTASTIC'), ('superdrug', 'Superdrug'), ('boots', 'Boots'), ('allbeauty', 'allbeauty'), ('asos', 'asos'), ) class ProductFilter(django_filters.FilterSet): store = django_filters.MultipleChoiceFilter(choices=store_choices) brand = django_filters.MultipleChoiceFilter(choices=brand_choices) price = django_filters.RangeFilter() class Meta: model = Product fields = ['store', 'brand', 'price'] def store_checks(self, queryset, name, store_choices): return Product.objects.filter( Q(store__icontains=store_choices) | Q(storehn__icontains=store_choices) | Q(storehof__icontains=store_choices) | Q( storesf__icontains=store_choices) | Q(storelf__icontains=store_choices) | Q(storesd__icontains=store_choices) | Q(storeboots__icontains=store_choices) | Q(storeab__icontains=store_choices) | Q(storea__icontains=store_choices) ) This does not work and returns no products, I am not sure what variable to use instead of store_choices with the Q(XXX__icontains = ). Any help would be appreciated -
Why is Django trying to insert infinite decimal places into my decimal field?
I had this model: class ErrorReproduction(models.Model): amount = models.DecimalField(primary_key=True, max_digits=65535, decimal_places=65535) class Meta: managed = False db_table = 'error_reproduction' In my view, I was running ErrorReproduction.objects.create(amount=1.0), which gave me the error [<class 'decimal.InvalidOperation'>]. I then read this post, which said that max_digits should be greater than the decimal_places, so I changed the model to this: class ErrorReproduction(models.Model): amount = models.DecimalField(primary_key=True, max_digits=65535, decimal_places=32000) class Meta: managed = False db_table = 'error_reproduction' Now, the same operation in the view gives me: value overflows numeric format LINE 1: ...SERT INTO "error_reproduction" ("amount") VALUES ('1.0000000... ^ Why is the value 1.0 overflowing the decimal field? Is it because of the infinite .00000? How am I supposed to insert values into decimal fields? I have also tried: ErrorReproduction.objects.create(amount=1) ErrorReproduction.objects.create(amount=Decimal(1.0)) ErrorReproduction.objects.create(amount=Decimal(1)) ErrorReproduction.objects.create(amount=float(1.0)) ErrorReproduction.objects.create(amount=float(1)) ErrorReproduction.objects.create(amount=math.trunc(1.0)) ErrorReproduction.objects.create(amount=math.trunc(1)) ErrorReproduction.objects.create(amount=round(1.0, 3)) ErrorReproduction.objects.create(amount=round(1, 3)) -
DJANGO: Save two forms within one class-based view
I have difficulties saving 2 forms within one view the only first one is saving but I cant figure out how to save the second one. Here is my code and issue : models.py class Office(models.Model): name = models.CharField(max_length=100,null=True) Address = models.ForeignKey(Address, on_delete=models.CASCADE, related_name='officeAddress',blank=True,null=True) def __str__(self): return self.name class Address(models.Model): address_line = models.CharField(max_length=60, blank=True) address_line2 = models.CharField(max_length=60, blank=True) country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='District') province=ChainedForeignKey(Province,chained_field="country",chained_model_field= "country",show_all=False,auto_choose=True,sort=True) district=ChainedForeignKey(District,chained_field="province", chained_model_field="province",show_all=False,auto_choose=True,sort=True) class Meta: verbose_name = "Address" verbose_name_plural = "Addresses" forms.py class OfficeModelForm(BSModalModelForm): class Meta: model = Office fields = ['name'] class AddressForm(forms.ModelForm): class Meta: model = Address fields = ['address_line','address_line2','country','province','district'] views.py class OfficeCreateView(BSModalCreateView): form_class = OfficeModelForm second_form_class = AddressForm template_name = 'settings/create_office.html' success_message = 'Success: Office was created.' success_url = reverse_lazy('company:office-list') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['address'] = self.second_form_class return context create_office.html {% load static i18n %} {% load widget_tweaks %} <form method="post" action="" enctype="multipart/form-data"> {% csrf_token %} {{ address.media.js }} <div class="modal-body"> <div class="form-group">{% render_field form.name %}</div> <div class="form-group">{% render_field address.address_line %}</div> <div class="form-group">{% render_field address.address_line2 %}</div> <div class="form-group">{% render_field address.country %}</div> <div class="form-group">{% render_field address.province %}</div> <div class="form-group">{% render_field address.district %}</div> <button class="btn btn-primary ms-auto" type="submit">{% trans "Create new office" %}</button> </div> </form> I think I need first to save the … -
How to display both selection (request)and result (return) on the same page
I want to show both request and its result on same page without corresponding to web-server or DB or with asynchronous(?) at each time. For example, a page display author list on the left side, and when an author is clicked, the list of the author’s book title are displayed on right side of same page. The simple method is, I think, that requested author on a page is sent to server (DB), getting the book list on there, building new html file, returning it and display the result on other page. I think it might be better off using jQuery or Javascript, but I’m not sure because of not good in Javascript Please tell me that is it possible and giving something of example code or references. The environment is Python 3.7 Django 2.2 Thank you -
Only allow a field to be edited and NOT written to in Django Rest Framework
so I am trying to create a todo app using the Django rest Framework, and have my models.py as... class Task(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) task = models.CharField(max_length=150) date_created = models.DateTimeField(auto_now=True) completed = models.BooleanField(default=False) What I want is that when a user inputs their task, I want the completed attribute to be hidden to the user and automatically set that to false. But then allow the user to change to true or false later on. With my current serializer.py.. class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ('id', 'task', 'date_created', 'completed') extra_kwargs = { "date_created":{"read_only":True}, # 'completed':{"read_only":True} } And my views.py... class ListView(viewsets.ModelViewSet): serializer_class = serializers.TaskSerializer permission_classes = (IsAuthenticated, permissions.ViewOwnTask) def get_queryset(self): return Task.objects.filter(user=self.request.user) def perform_create(self, serializer): serializer.save(user=self.request.user) In my serializer.py, the commented code 'completed':{"read_only":True} allows the user to edit the field and write on that field when uploading, as shown in this image However when I uncomment the 'completed':{"read_only":True} field, the option of writing the completed field disappears however I am not allowed to edit that field. Is there anything such as {"edit_only":True}, allowing the user to edit the field only. If you get my point. Any help would be greatly appreciated. Thanks! -
When to use which, Class-based views, Function-based view or generic veiws
So this is more like a discussion and guideline. When I should use which one(Function/Class/Generic). What are the advantages/disadvantages of one over and another, in which scenario one is the most suitable. Is it possible to handle multiple request with same request method GET/POST/... with a single class based view,i.e handle 2 get request in one class.