Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Writing your first Django app, part 5 error import models
I’m doing the first django application tutorial, I’m in part 05 and I’m having problems with “tests.py”, when I run “python manage.py test polls”, it returns the following error message: “RuntimeError: Model class mysite.polls.models.Question doesn’t declare an explicit app_label and isn’t in an application in INSTALLED_APPS.” However, ‘polls.apps.PollsConfig’ has already been added to INSTALLED_APPS, and the error continues to appear. I started “from polls.models import Question”, I managed to start the entire test through the shell, but in tests.py it gives this error I want the error to go away so I can run the necessary tests and continue the django tutorial -
Response Data from Django API not Fetching correctly, got an empty array #React,
I have the following data in the API in the backend (does this mean that I have backend well settled??): enter image description here And I'd like to display them in the frontend something like this: enter image description here Instead, I got the following empty page: enter image description here The structure of the folder is: enter image description here And the code of api.js file is the following: import { toast } from 'react-toastify'; function request(path,{ data = null, token = null, method = "GET"}) { return fetch(path, { method, headers: { Authorization: token ? `Token ${token}` : "", "Content-Type": "application/json", }, body: method !== "GET" && method !== "DELETE" ? JSON.stringify(data) : null, }) .then((response) => { console.log(response) // If it is success if(response.ok) { if (method === "DELETE") { // if delete, nothing return return true; } return response.json(); } //Otherwise, if there are errors return response .json() .then((json)=>{ // Handle Json Error, response by the server if (response.status === 400) { const errors = Object.keys(json).map( (k) => `${(json[k].join(" "))}` ); throw new Error(errors.join(" ")); } throw new Error(JSON.stringify(json)); }) .catch((e) => { if (e.name === "SyntaxError") { throw new Error(response.statusText); } throw new Error(e); }) … -
simplejwt token work for all tenants for django-tenants
I just want to mention about my problem. I have already researched many documents but I could not find any solution. I just try to use django-tenants. Everything seems OK. But If any user gets the token after login, that token works for all tenants. It's a big leak of security. I have been thinking about an idea SIGNING_KEY. If I can change SIGNING_KEY for each tenant, it may be fixed. But It did not. class TenantJWTAuthenticationMiddleware(MiddlewareMixin): def process_request(self, request): tenant = Client.objects.get(schema_name=connection.schema_name) jwt_secret_key = tenant.jwt_secret_key settings.SIMPLE_JWT['SIGNING_KEY'] = jwt_secret_key This is my Middleware to change SIGNING_KEY for each tenant. class Client(TenantMixin): name = models.CharField(max_length=100) paid_until = models.DateField() on_trial = models.BooleanField() created_on = models.DateField(auto_now_add=True) jwt_secret_key = models.CharField(max_length=100, null=True, blank=True) # default true, schema will be automatically created and synced when it is saved auto_create_schema = True class Domain(DomainMixin): pass This is my model. So, I added jwt_secret_key into my model and I got this field in Middleware and tried to set SIGNING_KEY for jwt. But still, jwt after user login can be used for all tenants. Does anyone have any idea about my problem? Any suggestion or amendment to my solution? Thanks. -
how to refresh the page without reloading, using django, ajax, jquerry?
So I am trying to delete products from cart without refreshing the entire page, I can delete an item and then I need to reload the page to delete another item. I am using Django, jQuery and AJAX to attain the desired result after going through questions of similar nature. In another branch I have implemented the auto refresh feature, whereby after deletion the page automatically reloads but it is not a great user experience. Any help will be greatly appreciated. here's my views.py delete item from cart function def delete_item_from_cart(request): cart_total_amt = 0 product_id = str(request.GET['id']) if 'cart_data_obj' in request.session: if product_id in request.session['cart_data_obj']: cart_data = request.session['cart_data_obj'] del request.session['cart_data_obj'][product_id] request.session['cart_data_obj'] = cart_data if 'cart_data_obj' in request.session: for p_id, item in request.session['cart_data_obj'].items(): cart_total_amt += int(item['qty']) * float(item['price']) context = render_to_string("core/async/cart-list.html", {"cart_data":request.session['cart_data_obj'], 'totalCartItems':len(request.session['cart_data_obj']), 'cart_total_amount':cart_total_amt}) return JsonResponse({"data":context, "totalCartItems":len(request.session['cart_data_obj'])}) here's my function.js implementation $(document).ready(function(){ $(".delete-product").on("click", function(){ let product_id = $(this).attr("data-product") let this_val = $(this) console.log(product_id); console.log(this_val); $.ajax({ url:'/delete-from-cart', data:{ 'id':product_id }, dataType: 'json', beforeSend: function(){ console.log("IN before send"); this_val.hide() console.log("IN after send"); }, success: function(response){ console.log("Starting success"); this_val.show() $("#cart-items-count").text(response.totalCartItems) $("#cart-list").html(response.data) console.log("successfully removed"); }, error: function(response){ alert('error'); } }) }) }) To be able to delete the next item in the cart without refreshing … -
Redirect Django TemplateDoesNotExist to 404
When the template does not exist, a 500 error returns to the user. I want Django to redirect to the 404 page for any view that gets a TemplateDoesNotExistError. Is there a way to accomplish this? -
The problem of creating a relationship between database tables in Django
Hello I wrote a ticketing system for site support and created a ticket class and a ticket response class in the model MODEL.py : class Ticket(models.Model): status_choices = ( ('Active','Active'), ('Completed', 'Completed'), ('Pending', 'Pending'), ) ticket_number = models.UUIDField(default=uuid.uuid4) title = models.CharField(max_length=200,verbose_name='Title') description = models.TextField(verbose_name='Description') created_by = models.ForeignKey(User,on_delete=models.CASCADE,related_name='created_by') date_created = models.DateTimeField(auto_now_add=True) ticket_status = models.CharField(max_length=15,choices=status_choices) def __str__(self): return self.title class TicketReply(models.Model): description = models.TextField(verbose_name='Description') ticket_user = models.ManyToManyField('Ticket') date_update = models.DateTimeField(auto_now_add=True) assigned_to = models.ForeignKey(User, on_delete=models.DO_NOTHING, null=True, blank=True) def __str__(self): return self.description And I created a form to create and update tickets FORMS.py : class CreateTicketForm(forms.ModelForm): class Meta: model = Ticket fields = ['title','description'] class UplateTicketModelForm(forms.ModelForm): class Meta: model = TicketReply fields = ['description'] widgets = { 'description': forms.Textarea(attrs={ 'class': 'form-control', 'rows': 4, }), } labels = { 'description': 'Reply', } error_messages = { 'description': { 'required': 'Enter the description' } } And finally, I wrote the two function so that the user can create and track the ticket. VIEW.py : def create_ticket(request): if request.method == 'POST': form = CreateTicketForm(request.POST) if form.is_valid(): var = form.save(commit=False) var.created_by = request.user var.ticket_status = 'Pending' var.save() messages.info(request,'Your ticket has been successfully.') return redirect('all-tickets') else: messages.warning(request,'Somthing went wrong.') return redirect('create-ticket') else: form = CreateTicketForm() context = { 'form': form … -
How to render a template after a form submit?
I have a django view where i upload a CSV file in a form. In my view i have some validations like check if the file is a CSV: class SabanaFileUploadView(CreateView): http_method_names = ['get', 'post'] form_class = UploadSabanaFileForm template_name = 'reasignacion/sabana_file_upload.jade' enabled_upload = False success_url = reverse_lazy('sabana') def get(self, request, *args, **kwargs): return render(request, self.template_name, {'form': self.form_class}) def get_success_url(self): return reverse_lazy('sabana') def post(self, request, *args, **kwargs): form = UploadSabanaFileForm(request.POST, request.FILES) if form.is_valid(): file = form.cleaned_data['file'] start_date = form.cleaned_data['start_date'] sabana = self.get_sabana(start_date) file_error = False // list instrucciones a validar // list unidad medida a validar // list motivos // list inicio periodo // list unidad a validar self.validate_bloqueo(request, sabana, form) try: csv_data = file.read().decode('utf-8') except: file_error = True form.add_error('file', 'El archivo debe ser CSV UTF-8') file_error, error_messages = validate_csv_data(csv_data, instrucciones_a_validar, unidad_medida_a_validar, listado_motivos, listado_inicio_periodo, central_unidad_a_validar) if file_error: for error_message in error_messages: print(error_message) form.add_error("file",error_message) else: print("CSV data is valid.") if not file_error and self.enabled_upload is True and sabana: registros_sabanas = load_tmp_registros_sabanas(sabana, csv_data) context = {'registros_sabanas': registros_sabanas} for registro in registros_sabanas: registro_model = RegistrosSabana( // vars // ... // ... ) registro_model.save() return render(request, 'reasignacion/sabana_list_masivo.jade', context) return render(request, self.template_name, {'form': form}) validating extension When the file pass every validation it loads a temporary … -
More than one initial migration file in a django project
In my project, to recreate the migrations, I removed all the migration files, leaving only the "initial.py" intact. Following that, I dropped my PostgreSQL database and executed the "makemigrations" command. In some of the applications, it generated more than one migration file, such as "0001_initial.py" and "0002_initial.py." Is this behavior considered normal? -
ImportError: cannot import name 'AdminConfig' from 'django.contrib.admin'
Why am I getting this error I am inside an app named reviews/adminconfig.py but when I run the server I get the following error: ImportError: cannot import name 'AdminConfig' from 'django.contrib.admin' (C:\Users\PERSONAL\AppData\Roaming\Python\Python310\site-packages\django\contrib\admin_init_.py) here is the code from django.contrib.admin.apps import AdminConfig class ReviewsAdminConfig(AdminConfig): default_site = 'admin.BookrAdminSite' I have already update the setting.py file notice: INSTALLED_APPS = [ 'reviews.adminconfig.ReviewsAdminConfig', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'reviews', ] -
Feed 100s of markdown pages into waagtail cms programmatically
I have some 1000+ page data as a markdown scrapped from a huge site. I am planning on creating a wagtail page model that has a title and a markdown. I want to feed all these scrapped page data into wagtail cms. One way I thought of doing is through admin commands. Any suggestions on how to proceed with this? -
Django Amazon RDS Tunnel Connection with Key File
When I run manage.py, I get this error. Any idea what I did wrong? django.db.utils.OperationalError: connection to server at "myserver.amazonaws.com" (XXX.XXX.XXX.22), port 56133 failed: Operation timed out Settings.py: import paramiko private_key_path = '../Mykeyfile.pem' tunnel_config = { 'ssh_address_or_host': ('XXX.XXX.XXX.XXX', 22), 'ssh_username': 'myusername', 'ssh_pkey': paramiko.RSAKey.from_private_key_file(private_key_path), 'remote_bind_address': ('myserver.amazonaws.com', 5432), } with SSHTunnelForwarder(**tunnel_config) as tunnel: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'myusername', 'PASSWORD': 'mypassword', 'HOST': 'myserver.amazonaws.com', 'PORT': tunnel.local_bind_port } } I've tried localhost and 127.0.0.1 for the addresses. I can connect easily with my datagrip with the same pam file and configuration. When I step debug, I can see pam file too. -
Order by one of two fields
I have a model that has two character fields, one or both of which may be populated. I'd like to called QuerySet.order_by something like: qs.alias(name=lambda x: if x.field1 then x.field1 else x.field2).order_by('name') That is, for each row, take the value that you're ordering by from field1 if it's defined, and from field2 if it's not. Is there any way to accomplish this with a Django queryset? -
Select * for reverse lookup
I've have three models in Django. class Product(models.Model): name = mdoels.CharField() class ProductCharateristics(models.Model): name = models.CharField() description = models.TextField() class ProductCharacteristicValues(models.Model): product_characteristic = models.ForeignKey(ProductCharacteristics) value = models.IntegerField() prduct = models.ForeignKey(Product) The list of characteristics may change, it's the same for all products and each characteristics can have multiple value. I'd like to replicate with django ORM the following SQL statement: select * from ProductCharateristics as pc left join ProductCharacteristicValues as pcv on pc.id = pcv.product_characteristics where pcv.product = 1 This query retrieves all rows and all columns from both tables. -
Django migration/model created a foreign key field that is not model_id but instead modelID?
I am trying to figure out why I get an error in my app: ProgrammingError at /admin/auth/user/ column programscheduler_proposal.program_id does not exist LINE 1: SELECT "programscheduler_proposal"."id", "programscheduler_p... ^ HINT: Perhaps you meant to reference the column "programscheduler_proposal.programID". Model: class Program(models.Model): programName = models.CharField(max_length=100) institution = models.ForeignKey("mainpage.Institution", on_delete=models.CASCADE) #should act as blackout constraints class ProposalConstraint(models.Model): objects = models.Manager() proposal = models.ForeignKey("Proposal", on_delete=models.PROTECT) date_time_constraint = models.DateTimeField() note = models.CharField(max_length=200) isPersonal = models.BooleanField(default=False) class Proposal(models.Model): objects = models.Manager() program = models.ForeignKey("Program", on_delete=models.CASCADE) institution = models.ForeignKey("mainpage.Institution", on_delete=models.CASCADE) title = models.CharField(max_length=100) #scheduler = models.ForeignKey('accounts.APOUser', on_delete=models.CASCADE) scheduler = models.ForeignKey('accounts.APOUser', related_name='%(app_label)s_%(class)s_scheduler_related', on_delete=models.CASCADE) pi = models.ForeignKey('accounts.APOUser', related_name='%(app_label)s_%(class)s_pi_related', on_delete=models.PROTECT) #observers recahback to proposal observer. untrained_observer_list = models.CharField(max_length=200) #just seperate via commas collaborators = models.CharField(max_length=200) #just seperate via commas contact_information = models.CharField(max_length=200) #might break this out to a complete address? #instrument = models.ForeignKey("Instrument", on_delete=models.PROTECT) instrument = models.ManyToManyField("Instrument") #each program can have many instruments. primary_dis_grating = models.CharField(max_length=20) #is this going to be replaced by FILTER DB? or based on instrument? independent from instrument? secondary_dis_grating = models.CharField(max_length=20, null=True, blank=True) slits = models.CharField(max_length=150) #is this based on instrument? independent of instrument? several options per instrument? filters = models.CharField(max_length=150) #same as above targetofop = models.CharField(max_length =200, null=True, blank=True) #can be blank location = models.CharField(max_length=20) … -
Deleting django form field help_text after errors are shown
I'm trying to delete the password help texts once a form is being re-rendered with errors. For some reason, it keeps recreating the help_text before the form is rendered. from allauth.account.forms import SignupForm, SetPasswordForm # Helper function used to switch the password help texts # So that it appears under the second password instead of the first def switchHelpTexts(form): ### This works ### help_text = form.fields["password1"].help_text form.fields["password1"].help_text = None form.fields["password2"].help_text = help_text ### This works ### # Helper function used to delete the password help texts # when validation errors are displayed. We don't need the same info twice def deleteHelpTexts(form): ### This doesn't work ### form.fields["password1"].help_text = None form.fields["password2"].help_text = None ### This doesn't work ### class MyCustomSignupForm(SignupForm): field_order = ["username", "email", "password1", "password2"] def __init__(self, *args, **kwargs): super(MyCustomSignupForm, self).__init__(*args, **kwargs) switchHelpTexts(self) # # Commented out because deleteHelpTexts doesn't work for some reason # if self.errors and (self.errors.keys() & {"password1", "password2"}): # deleteHelpTexts(self) Even more surprising, if I do this: def deleteHelpTexts(form): form.fields["password1"].help_text = None form.fields["password2"].help_text = "Hello" print(form.fields["password2"].help_text) the console prints "Hello" like it's supposed to, but the form still re-renders with the original helptext instead of "Hello" -
Authenticate returns null always
when i authenticate it returns null and so i cant login even when i have username and password in my database from django.shortcuts import render,redirect from django.contrib import messages from django.contrib.auth import authenticate, login ,logout from .models import Signups from .forms import SignForm from django.contrib.auth.models import User from django.contrib.auth.forms import AuthenticationForm from django.shortcuts import get_object_or_404 from django.http import HttpResponse # Create your views here. def loginpage(request): a=Signups.objects.all() form1 = AuthenticationForm() if request.method == 'POST': form1 = AuthenticationForm(data=request.POST) username = request.POST.get('username') password = request.POST.get('password') print(username,password) user = authenticate(request,username=username, password=password) if user is not None: login(request,user) return redirect('signed', pk=user.pk) else: return HttpResponse("username or password is incorrect") return render(request, 'database/loginpage.html', {'form1': form1}) def frontpage(request): return render(request,'database/frontpage.html') def signup(request): form=SignForm() if request.method=='POST': form = SignForm(request.POST) if form.is_valid(): user=form.save() return redirect("signed",pk=user.pk) return render(request,'database/signup.html',{'form':form}) def signed(request,pk): sign=Signups.objects.get(id=pk) return render(request,'database/signed.html',{'sign':sign}) this is my views.py i want to go to a page where it shows username and password and i have written the code for that and it works but the login form is not taking me there. -
Wagtail 4 Upgrade: 'BlockWidget' object has no attribute '_block_json'
After reading through and updating possible breaking changes stated in the Wagtail changelog, I am getting the following error when viewing any edit menu for any page: 'BlockWidget' object has no attribute '_block_json' Request Method: GET Request URL: https://example.com/admin/pages/530/edit/ Django Version: 3.2.9 Exception Type: AttributeError Exception Value: 'BlockWidget' object has no attribute '_block_json' Exception Location: /home/user/.virtualenvs_dev/mysite/lib/python3.10/site-packages/wagtail/blocks/base.py, line 526, in block_json Python Executable: /home/user/.virtualenvs_dev/mysite/bin/python3.10 Python Version: 3.10.9 Python Path: ['/home/user/projects/mysite/django', '/home/user/.virtualenvs_dev/mysite/bin', '/usr/local/lib/python310.zip', '/usr/local/lib/python3.10', '/usr/local/lib/python3.10/lib-dynload', '/home/user/.virtualenvs_dev/mysite/lib/python3.10/site-packages', '/home/user/projects/mysite/django/mysite'] Server time: Tue, 17 Oct 2023 11:02:12 -0500 Error during template rendering In template /home/user/.virtualenvs_dev/mysite/lib/python3.10/site-packages/wagtail/admin/templates/wagtailadmin/panels/object_list.html, error at line 9 'BlockWidget' object has no attribute '_block_json' 1 {% load wagtailadmin_tags %} 2 3 <div class="w-form-width"> 4 {% if self.help_text %} 5 {% help_block status="info" %}{{ self.help_text }}{% endhelp_block %} 6 {% endif %} 7 {% for child, identifier in self.visible_children_with_identifiers %} 8 {% panel id_prefix=self.prefix id=identifier classname=child.classes|join:' ' heading=child.heading heading_size="label" icon=child.icon id_for_label=child.id_for_label is_required=child.is_required %} 9 {% component child %} 10 {% endpanel %} 11 {% endfor %} 12 </div> 13 I've used python poetry in attempt to have all libraries compatible. It builds just fine and the site runs. It is just this specific portion of the site that has to do with the actual Wagtail … -
django orm filter doesn't find the result but I know the result exists
I have a mySql database in server and it has about 5000 rows of data in one table. my model is like this: class Names(models.Model): title = models.CharField(max_length=100) descriptions = models.CharField(max_length=500) is_approved = models.BooleanField(default=False) count_stars = models.FloatField(default=0.0) count_visited = models.FloatField(default=0.0) count_shared = models.FloatField(default=0.0) gender = models.ForeignKey(Genders, on_delete=models.CASCADE) root = models.ForeignKey(Roots, on_delete=models.CASCADE) def __str__(self) -> str: return self.title my mission is to find a specific row in the database by the field of 'title', when the title is in the first tens of rows in the database, everything works good but when the title is in the deeper rows, it can not find it. my view function is: @api_view(["Get"]) def get_name_by_name(request, keyName): value = models.Names.objects.filter(title=keyName).first() serializedValue = serializers.nameSerializer(value) result = serializedValue.data return Response(result) database rows: 1- found 2- found . . n- not found . . 5000. not found what is the problem? I searched about async programming but it didn't work -
Django CustomUser model stores password as plain text
I'm developing django based website. I'm extends auth.user model like below from django.contrib.auth.models import AbstractUser class User(AbstractUser): first_name = None last_name = None is_active = models.BooleanField(default=True) is_granted = models.BooleanField(default=False) class Meta: verbose_name = '사용자' verbose_name_plural = '사용자' But I'm in trouble when I create new user data in django site admin. When I create new user, the password doesn't encrypt. I don't want to store password in plain text but hash doesn't work. How should I handle this. -
Python: Django: Cant find a field for some reason in a model
Here is : models.py from django.db import models class identifierModel(models.Model): identifierField = models.CharField(max_length=32, unique=True), ipField = models.CharField(max_length=15), views.py from django.shortcuts import render, HttpResponse from getidentifier.models import identifierModel def commands(request, identifier): if identifier in identifierModel.objects.all(): return HttpResponse("ok") # only for testing is "ok" else: HttpResponse.status_code = 401 return HttpResponse(identifierModel.objects.filter(identifierField=identifier).exists() ) Error: FieldError at /commands/d984b583c27f4b84a7d39b1a3a44c54e/ Cannot resolve keyword 'identifierField' into field. Choices are: id Error from browser I both ran makemigrations and migrate but still its the same thing, i really don't get why it doesent find identifierField, sorry if it was an obvious error i didn't see -
Wagtail 5.1 - Hidding promote tab will stop any user from editing a page
I currently have a wagtail 5.1 project where there's a need to hide the promote tab. I'm hiding the tab like this: from wagtail.admin.panels import ( TabbedInterface, ObjectList, ... ) ... edit_handler = TabbedInterface([ ObjectList(content_panels, heading='Content'), ObjectList(Page.promote_panels, heading='Promote', permission="superuser"), ]) The problem is that, any user besides the wagtail admin cannot save the edited page. A normal user with the group Moderator or Editor (or both) although he is not able to see the tab (what I want) he is not able to save the page because of the required slug in that tab. Is there any workaround or am I stuck with this? Thank you in advance. -
When using django-tinymce, where do I specify referer?
I'm trying to integrate tinyMCE with a django app. I have the following specified in my settings.py: TINYMCE_JS_URL = "https://cdn.tiny.cloud/1/<my api key>/tinymce/6/tinymce.min.js"; tinyMCE does display, but it's giving me the following message: We’re unable to check your domain because the referer header is missing. Please read the Guide on how to ensure your referer header is present, so we can then customize your editor experience. Where do I specify the referer header? I tried putting 'referrer_policy': 'origin', in my TINYMCE_DEFAULT_CONFIG, but I still get the error. -
Django grequests batch call fail
Thank you for willing to see this question. It block me for a long time and try to ask help here. I have 100 api to pin in Django, I tried to use grequests to do batch call, the batch call code looks like this: class BatchCall: def __init__(self, urls, BO_urls): self.urls = urls self.BO_urls = BO_urls def exception(self, request, exception): print("Problem: {}: {}".format(request.url, exception)) def asyncCall_release(self): return grequests.map( (grequests.get(u, auth=HTTPBasicAuth(username, password), verify=False) for u in self.urls), exception_handler=self.exception, size=10) def asyncCall_BO(self): return grequests.map( (grequests.get(u, auth=HTTPBasicAuth(username, password), verify=False) for u in self.BO_urls), exception_handler=self.exception, size=10) test = BatchCall(urls, BO_urls) # here we collect the results returned by the async function results_release = test.asyncCall_release() results_BO = test.asyncCall_BO() When I test all the stuff in Jupyternotebook, everything goes well, it can give me the result. but when I run it in Djgano, I use this to run the app python manage.py runserver The whole app will exit itself in Django after pin 1 batch (10 api) with no reason. *I use Pytharm to run Django InsecureRequestWarning: Unverified HTTPS request is being made to host xxxxx. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#ssl-warnings warnings.warn( it will have 10 warning looks like this but it … -
Django Filterset data not cleaned as expected
I have a FilterSet defined as such: from django_filters import rest_framework class SomeFilter(filters.FilterSet): id = filters.BaseInFilter() sort_by = rest_framework.OrderingFilter(fields=["name", "creation_date", "location"]) I use DRF to define API view. In the view, I access the filter data with filterset = self.get_filterset(queryset). What I noticed: filterset.form.data gives me a QueryDict({"sort_by": ["name", "location"]} (for example) and if I run filterset.form.cleaned_data.get("sort_by"), I only get "location" This is expected if I look at the doc for QueryDict but this is clearly not what I would expect from the cleaning. Any idea how I could override this cleaning so I can keep all values passed as query params ? -
Does Django DRF have a way to do read-only tokens?
I have a Django REST API using Django REST Framework. I want to use TokenAuthentication, but I want to have read-only tokens and read-write tokens. Read-only just has access to GET methods. Read-Write have access to everything (POST, PUT, DELETE, etc). Does DRF already have something for this? Or would I just create my own Token model with an extra field that keeps track of the type of token, and use my own version of TokenAuthentication that returns a 403 if the token is READ_ONLY, and the method is other than a GET method? I don't want to be re-inventing the wheel here if this already exists.