Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django 2.2.5 URL regex in url path
I would like to support the above views in a single view in url ...in my search I came across [this post][1] which is no longer supported and all the tutorials i've found have been outdated, which demonstrate how to accomplish the task in django 1.8.3. In 'products/views.py' I have created a views for products and details. ProductListView will display all products, while ProductDetailView will display a single product detail (title, description, price etc). products/views.py class ProductListView(ListView): queryset = Product.objects.all() template_name = "products/list.html" class ProductDetailView(DetailView): queryset = Product.objects.all() template_name = "products/detail.html" products/urls.py include path to the views for ProductListView and ProductDetailView. ProductListView appears to be correct. ProductDetailView is incorrect! I'm getting the following warnings: WARNINGS: ?: (2_0.W001) Your URL pattern '^products/(?P\d+)/$' [name='details'] has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path(). ecommerce.py/urls.py is where i've included products and details urls ecommerce/urls.py: from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include from .views import home, about, contact urlpatterns = [ path('admin/', admin.site.urls), path('', home, name='home'), path('about/', about, name='about'), path('products/', include('products.urls'), name='products'), path('products/', include('products.urls'), name='details'), path('contact/', contact, name='contact'), path('account/', … -
__init__() takes 1 positional argument but 2 were given. I'm getting this error in my django code
Views.py content import render, get_object_or_404, redirect from django.contrib.auth.decorators import login_required from blog.models import Post, Comment from django.utils import timezone from blog.forms import PostForm, CommentForm from django.utils.decorators import method_decorator from django.views.generic import (TemplateView,ListView, DetailView,CreateView, UpdateView,DeleteView) from django.urls import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin class AboutView(TemplateView): template_name = 'about.html' class PostListView(ListView): model = Post def get_queryset(self): return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') class PostDetailView(DetailView): model = Post class CreatePostView(LoginRequiredMixin,CreateView): login_url = '/login/' redirect_field_name = 'blog/post_detail.html' form_class = PostForm model = Post class PostUpdateView(LoginRequiredMixin,UpdateView): login_url = '/login/' redirect_field_name = 'blog/post_detail.html' form_class = PostForm model = Post class DraftListView(LoginRequiredMixin,ListView): login_url = '/login/' redirect_field_name = 'blog/post_list.html' model = Post def get_queryset(self): return Post.objects.filter(published_date__isnull=True).order_by('created_date') class PostDeleteView(LoginRequiredMixin,DeleteView): model = Post success_url = reverse_lazy('post_list') I'm getting following error:- TypeError at /accounts/login/ init() takes 1 positional argument but 2 were given Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/ Django Version: 2.2.5 Exception Type: TypeError Exception Value: init() takes 1 positional argument but 2 were given Exception Location: C:\Users\Hp\Anaconda3\envs\proenv\lib\site-packages\django\core\handlers\base.py in _get_response, line 113 Python Executable: C:\Users\Hp\Anaconda3\envs\proenv\python.exe Python Version: 3.7.3 Python Path: ['C:\Users\Hp\Desktop\myproject\blog_project\mysite', 'C:\Users\Hp\Anaconda3\envs\proenv\python37.zip', 'C:\Users\Hp\Anaconda3\envs\proenv\DLLs', 'C:\Users\Hp\Anaconda3\envs\proenv\lib', 'C:\Users\Hp\Anaconda3\envs\proenv', 'C:\Users\Hp\Anaconda3\envs\proenv\lib\site-packages'] Server time: Tue, 17 Sep 2019 20:11:42 +0000 -
Django cannot serialize into migration file
Hi there i'm having problems when trying to use the command makemigrations with manage.py. The output is the following: Migrations for 'reg': reg\migrations\0012_auto_20190917_1711.py - Remove field Products from tenant - Add field products to tenant - Alter field productos on preaprobado - Alter field tenant_id on preaprobado - Alter field CMS_id on producto - Alter field CMS_id on tenant Traceback errors ValueError: Cannot serialize: <Producto: Basico - ['IPTEL', 'Rocstar', 'Test_DVT']> There are some values Django cannot serialize into migration files. For more, see https://docs.djangoproject.com/en/2.2/topics/migrations/#migration-serializing The thing is that the entire app works just fine but for some reason i can't understand i cannot migrate the db. Here is the models.py: class Producto(models.Model): Name = models.CharField(max_length = 50, unique = True) CMS_id = models.PositiveIntegerField(unique = True) def __str__(self): #Toma los tenants que tienen el producto asignado por el nombre y forma una lista de los nombres de los tenants #para que aparezcan al lado del nombre del producto tenants_with_product = Tenant.objects.filter(products__Name = self.Name) tenants_dict = tenants_with_product.in_bulk(field_name = "Name") tenants_list = [] for tenant_name in tenants_dict.keys(): tenants_list.append(tenant_name) return(self.Name + " - " + tenants_list.__str__()) class Tenant(models.Model): Name = models.CharField(max_length = 30, unique = True) Enabled = models.BooleanField(default = False) CMS_id = models.PositiveIntegerField(unique … -
Wagtail: How to override default ImageEmbedHandler?
I've been having some trouble implementing Wagtail CMS on my own Django backend. I'm attempting to use the 'headless' version and render content on my own SPA. As a result, I need to create my own EmbedHandlers so that I can generate URL's to documents and images to a private S3 bucket. Unfortunately, though I've registered my own PrivateS3ImageEmbedHandler, Wagtail is still using the default ImageEmbedHandler to convert the html-like bodies to html. Is there a way for me to set it so that Wagtail uses my custom EmbedHandler over the built in default? Here's my code: from wagtail.core import blocks, hooks from messaging.utils import create_presigned_url class PrivateS3ImageEmbedHandler(EmbedHandler): identifier = "image" @staticmethod def get_model(): return get_user_model() @classmethod def get_instance(cls, attrs): model = cls.get_instance(attrs) print(model) return model.objects.get(id=attrs['id']) @classmethod def expand_db_attributes(cls, attrs): image = cls.get_instance(attrs) print(image) presigned_url = create_presigned_url('empirehealth-mso', image.file) print(presigned_url) return f'<img src="{presigned_url}" alt="it works!"/>' @hooks.register('register_rich_text_features') def register_private_images(features): features.register_embed_type(PrivateS3ImageEmbedHandler) -
primary key 135 has an invalid foreign key: imageApp_webpage.topic_id contains a value 5 that doesn't have a corresponding value in imageApp topic.id
**from django.db import models from django.contrib.auth.models import User class Details(models.Model): name = models.CharField(max_length=264, unique=True) email = models.EmailField(max_length=50, unique=True) url = models.URLField(unique=True) class UserInfo(models.Model): user = models.OneToOneField(User, on_delete=models.DO_NOTHING) # author information portfolio = models.URLField(blank=True) image = models.ImageField(upload_to='CollectionImage/image', blank=True) def __str__(self): return self.user.username** I DON'T UNDERSTAND WHY I'M FACING THIS KIND OF PROBLEM. LIKE: bad_value, referenced_table_name, referenced_column_name django.db.utils.IntegrityError: The row in table 'imageApp_webpage' with primary key '135' has an invalid foreign key: imageApp_webpage.topic_id contains a value ' 5' that does not have a corresponding value in imageApp_topic.id. -
Python warnings to exceptions in Django tests with ignore
I'm attempting to run Django unit tests using: python -We -W ignore:DeprecationWarning -W ignore:UserWarning manage.py test However, this doesn't successfully ignore these warning classes, and instead only respects the -We flag, raising all warnings to exceptions. This is not my desired behavior. How can I run Django tests such that all warnings except DeprecationWarning and UserWarning are raised as exceptions when encountered in a test? -
How can I construct a Django Template Tag condition statement to check the request method for POST?
First, what I'd like to work: {% if method == POST %} {% include "app/template_x.html"%} {% else %} {% include "app/template_y.html"%} {% endif %} I'm using class based views, inheriting from django.views.generic.edit.UpdateView I tried a few things, among them passing an HttpRespons.method object via extra context in the urls.py asview() function. Anyone have an idea how I should approach this problem? -
heartbeat between python desktop app installed at client and django server app
There is a python desktop app that is deployed at client end and a Django web based server app. What way can we possibly set up a heartbeat for each client's desktop location so that we get an alert in case desktop application is not working/off. -
OSError: [Errno 99] Address not available - sending e-mail from django docker app with gmail smtp
I'm trying to send an e-mail from my django application in docker and I'm getting following error: OSError at /accounts/mail/ [Errno 99] Address not available Request Method: GET Request URL: https://localhost:8000/accounts/mail/ Django Version: 2.2.5 Exception Type: OSError Exception Value: [Errno 99] Address not available Web server log: web_1 | OSError: [Errno 99] Address not available web_1 | [17/Sep/2019 19:21:35] "GET /accounts/mail/ HTTP/1.1" 500 108369 My environment: Ubuntu 18.04 Docker Django + Gunicorn Postfix I have no problem to send an e-mail outside docker, locally. I suppose that there might be a problem with smtp port inside docker, but I don't know how to fix that. I tried with postfix - same error. View code from django: from django.core.mail import EmailMessage # didn't work also with send_mail def email(request): mail_subject = 'Activate your account' message = 'test' to_email = 'mail@mail' email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return redirect('index') Part of my docker-compose file. version: '3.3' services: web: build: ./app command: python manage.py runsslserver 0.0.0.0:8000 ... ports: - 8000:8000 - 587:587 - 25:25 env_file: .envdev ... postfix: image: juanluisbaptiste/postfix:latest expose: - "25" env_file: - .envpostfix restart: always volumes: - "/etc/localtime:/etc/localtime:ro" ... Django settings: EMAIL_BACKEND=django.core.mail.backends.smtp.EmailBackend EMAIL_USE_TLS=True EMAIL_HOST=smtp.gmail.com EMAIL_HOST_USER=*** EMAIL_HOST_PASSWORD=*** EMAIL_PORT=587 My … -
Items getting disappeared when I put them for scrollreveal
I'm using scroll reveal in my site. When I put them for scroll reveal they are getting disappeared. But first 4 items(images, div) are responding to the scroll reveal(2 or 3 items working fine) rest of the items are not. I'm using https://unpkg.com/scrollreveal/dist/scrollreveal.min.js. they are provided with exact id and classes for reveal method. <section style="margin-top: 60px; text-align: justify;"> <div class="container"> <div class="row"> <div class="col-md-4 col-sm-4"> <div class="cardss" style=" border-radius: 10px 10px 10px 10px;-moz-border-radius: 10px 10px 10px 10px;-webkit-border-radius: 10px 10px 10px 10px;padding: 10px"> <img id="im1" class="card-img-top" src="static/learninganddev.png" style="height: 250px; width: 200px; margin-left: 70px" alt="Card image cap"> <div class="card-body"> <h5 class="card-title" style="font-weight: 2px solid #000000; font-size: 20px">Learning&Development</h5> <p class="card-text">Google Home voice-activated speaker.consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat</p> </div> <div class="card-body" style="margin-top: 50px"> <a href="#" class="card-link">Read more</a> </div> </div> </div> <script> window.sr = ScrollReveal({ reset: true }); sr.reveal('.navbar', { duration: 2000, origin:'bottom' }); sr.reveal('.who', { duration: 2000, origin:'top', distance:'300px', easing: 'cubic-bezier(0.5, 0, 0, 1)' , }); sr.reveal('.whowearetext', { //till here everything is fine. duration: 2000, origin:'right', }); sr.reveal('.cardss', { // this one onwards not working, getting disappeared. … -
How do I assign a Python variable from js code to send to the database without reloading the page?
There is a page for creating posts "aframe". There is field name office 'title', button choice background, terrain. Data from the 'title' field is saved to the database. But how to connect the background, relief buttons to the database via django without reloading the page? Is it possible to pass a value from javascript to python to save to a database var sceneEl = document.querySelector('a-scene'); AFRAME.registerComponent('foo', { init: function () { var skyEl = sceneEl.querySelector('a-sky'); //Changing color using JQuery here $(document).ready(function(){ let color, src,mtl, terrain, text1; $("#text1").click(function(e){ var x = document.getElementById("fname").value; //document.write(x); document.getElementById("output").innerText = x; return false; }); $("#color button").click(function(e){ color = e.currentTarget.className; skyEl.setAttribute('src', '#blank'); skyEl.setAttribute('color', color); {{ background }} = color; }); $("#picture button").click(function(e){ src = e.currentTarget.className; skyEl.removeAttribute('color'); skyEl.setAttribute('src', '#'+src); }); $("#terrain button").click(function(e){ var skob = sceneEl.querySelectorAll('.obj_model'); terrain = e.currentTarget.className; mtl = e.currentTarget.name; for (let index = 0; index <= skob.length; ++index) { //alert(mtl); //skyEl.setAttribute('color', '#1fa9e3'); skob[index].setAttribute('src', '#'+terrain+'-obj'); skob[index].setAttribute('mtl', '#'+mtl); if(terrain=='city'){ skob[index].setAttribute('scale', '30 120 35'); } else { skob[index].setAttribute('scale', '5 10 5') ; } } }); }); } }); sourceURL=pen.js <form method="post"> <div id="left" > <div id="select"> <div id="cssmenu"> {% csrf_token %} <input type="text" placeholder="title" name="title"> <input type="text" placeholder="body" name="body"> <input type="text" placeholder="background" name="background"> <ul> <li class='has-sub'><a href='index.html'><span>Terrain</span></a> <ul> … -
Django background task not running
I am trying to run a background task in django to run an sql query when the user clicks on a certain button. I created the function in tasks.pyand when I try and run it using the @background decorator, it does not run (Runs fine without @background). I am not getting any error, however the task is not running. Here is my tasks.py from background_task import background from django.db import connection @background(schedule=1) def delete_process_background(process_id): print("Start of background task") with connection.cursor() as cursor: cursor.callproc("delete_process",[process_id]) And my function in views.py that is triggered when user clicks the button: def db_revert_process(request): process_id = int(request.POST['text']) delete_process_background(process_id) print("Called background process") return HttpResponse() The print statement in the views.py function is executed but not the statement in the background task. -
django models: change the way value of a field gets rendered in admin panel
My model in django has uuid as its primary key: class User(models.Model): token = models.UUIDField(primary_key=True, default=uuid.uuid4) def __str__(self): return str(self.token).replace('-', '') and since uuid gets saved in the database without dashes(-), therefor I could able to render it without dashes using __str__ in the code above. The result looks like this: But how can I do the same thing for the way the value gets rendered in the admin panel (how to remove dashes): -
django form can not find the author in the post
Wanted to have every user already post with their post authorship but, the code I have with, they need to choose the author I have tried deleting author then error pop up: author_id is unknown class Post(models.Model): STATUS_CHOICES = { ("draft", "Draft"), ("published", "Published"), } author = models.ForeignKey(User, on_delete = models.CASCADE, default = 1 ) title = models.CharField(max_length= 100, null=True, blank=True, default="Başlık") class PostForm(forms.ModelForm): class Meta: model = Post fields = ["author", "title", "content", "image"] widgets = { "author": forms.Select(attrs={"class": "form-control"}), "title": forms.TextInput(attrs={"class": "form-control"}), I use django 2.2.5 and still have errors -
How to search by choice value
How to search by choice value and not the key as in the following: This model: CITY_CHOICES = ( ('Omran', 'عمران'), ('AlBayda ', 'البيضاء'), ('Hodeidah', 'الحديدة'), ) class Place(models.Model): city = models.CharField(choices=CITY_CHOICES, max_length=20) # Manager objects = PlaceManager() This search by city but looking for the key and I want it looking for value class PlaceQuerySet(models.QuerySet): def search(self, query): lookup = ( Q(city__icontains=query) ) return self.filter(lookup) class PlaceManager(models.Manager): def get_queryset(self): return PlaceQuerySet(self.model, using=self._db) def search(self, query=None): if query is None: return self.get_queryset().none() return self.get_queryset().search(query) -
How to retreive manyToMany field in django model serializer, with viewset?
Help, I am trying to understand since last hours, how to send a manytomany extra data with my Item modelSerializer. here is the definition of the fiel in the Item model, extra = models.ManyToManyField(SimpleExtraField, through='ExtraField') class ExtraField(models.Model): item = models.ForeignKey(Item, related_name="extra_fields") key = models.ForeignKey(SimpleExtraField) # add limit to not yet selected value = models.CharField(max_length=glLargeCharLen) here is my model serializer : class basic_itemSerial(serializers.ModelSerializer): medias = mediaSerial(many=True) extra = ExtraSerial(many=True, required=False) children = minItemSerial(many=True) class Meta: model = Item fields = '__all__' as a queryset, I am just trying to get a list, list this queryset = Item.objects.all() I tried adding extra data to get_serializer_context, like this, def get_serializer_context(self, *args, **kwargs): context = super(self.__class__, self).get_serializer_context(*args, **kwargs) qex= [] for q in self.queryset: qq = ExtraField.objects.all().filter(item=q.reference) for qqs in qq: qex.append(qqs) context['extra'] = qex return context I also tried to change the name in the serializer to extra_fields = ExtraSerial(many=True, required=False) But None of them worked for me, I think I am connecting bad the serializer to the queryset. also here are the extraModel and SimpleExtraField: class ExtraField(models.Model): item = models.ForeignKey(Item, related_name="extra_fields") key = models.ForeignKey(SimpleExtraField) # add limit to not yet selected value = models.CharField(max_length=glLargeCharLen) serializer.py class SimpleExtraField(models.Model): name = models.CharField(max_length=glMiddleCharLen, unique=True, primary_key=True) -
How to get values for a queryset for an model when the foreign key is not in the current model?
I have the following models: class Work_Music(models.Model): key = models.CharField(max_length=10, null=True, blank=True) tonality = models.CharField(max_length=20, null=True, blank=True) class Catalogue(models.Model): work_music = models.ForeignKey(Work_Music, verbose_name=_('work_music'), on_delete=models.PROTECT) name = models.CharField(max_length=100, null=True, blank=True) name_short = models.CharField(max_length=100, null=True, blank=True) no = models.CharField(max_length=100, null=True, blank=True) related_field() only works with the Foreign key is in Work_Music. Many catalogue/catalogue numbers can map to a piece of music (Work_Music). How can I construct a query set on Work_Music to pull all of the catalogues related to the piece of work? -
Multiple File Upload inside a inlineformset
Hi I would like to know if it's possible to have a multiple file upload field within a formset. The structure is as following: I have a parent model who get a one to one relationship with one of his possible child. The child have several inline formset with other specific models. And one of those formset need to contain a multiple file upload. They are all edited in the same view. The parent and the related child get created before going to that edit view. This is a capture of my database structure (there is a missing table on the right): Just to give you a vague idea I have: a Task model which have a 1to1 to a GeneralApplicationTask which have a many to one relationship with GeneralApplicationProperty(this is what is used in the inlineformset) So for each GeneralApplicationTask Form I have some fields and then several formset containing property information and each need to contain a multiplefile upload. The problem I am facing is, if I create a modelForm to manage the files and create a Mt1 from the GeneralApplicationProperty model, then I cant properly save the files because I need to know which form (and the … -
old javascript script code in chrome inspect than editor
I am making my personal portfolio using Django and I was writing a javascript for contact form and it is getting some old javascript code I don't know from where. The code I wrote in my script in the editor is new but when I am inspecting in chrome it's showing some old code for the same script file -
How to send data in POST fetch request from one domain and process request on server listening on different domain?
I will admit I don't understand this part of the web technologies. I have a python django app running on localhost:8000 and react client SPA running on localhost:3000. I have implemented REST APIs on the server using django rest framework and I am calling a couple of APIs from the client in browser. There is a issue of CORS which I have patched using django cors headers app. I am able to use GET APIs like this and that is working fine till now. fetch("http://localhost:8000/api/comments", { method: "get" }).then((response)=> { console.log("got response"); return response.json(); }).then((comments) => { console.log("got json", comments); this.setState({ comments: comments }) }).catch((error)=> { console.log("error", error); }); Second I have POST API where add commenter's name, I have tried different variations to call this API, but not with much success. All the variations have one issue and that is, the request body is empty, browser network tab and logs in views.py method agree on that. var headers = new Headers(); // Add a few headers headers.append('Content-Type', 'application/json'); headers.append('X-Requested-With', 'XMLHttpRequest') let payload = { "first_name": first_name.value, "last_name": last_name.value }; var data = new FormData(); data.append( "json", JSON.stringify( payload ) ); const request = new Request("http://localhost:8000/api/user", { method: 'POST', mode: … -
Where to learn advanced/beyond-basic Django web
Hi guys I’m new to web dev and Django but I’ve learnt all the basics and now want to develop my skills. I’ve created some web apps that aren’t too complex since I’m struggling to find follow-along content for advanced web Django dev. Where can I find some? -
clamav timing out when scanning stream for large file
Have a React/Django app that a small group of clients use to submit files to us. Using react-dropzone for the file upload, without any maxSize specified, so it should be react-dropzone causing the issue. The file I'm working with is an Excel file of about 160MB. When the files are uploaded, clamav (called from Django) scans the files in stream before writing to disk. I have run into issues in the past with clamav and default maximum file sizes being removed, so I have those either removed or set very high. Initially it was timing out after 30 seconds. I looked at the scan.conf for anything related to time and 30, which brought me to IdleTimeout which defaults to 30. I changed it to 360 and now it times out after about 90 seconds. Nothing in the scan.conf has a 90 associated with it, so I'm puzzled as to what else I could change to get this to work. These are settings I've changed and the value I have them at: LogFile /home/log/clamd.log LogTime yes LogSyslog yes LogVerbose yes LocalSocket /var/run/clamd.scan/clamd.sock StreamMaxLength 2048M ReadTimeout 360 IdleTimeout 360 MaxScanSize 0 MaxFileSize 0 OnAccessMaxFileSize 0 # 0 disables any limit Any suggestions … -
Invalid block tag on line 21: 'transaction'. Did you forget to register or load this tag?
I am getting the error on the transaction models, not sure what i am missing. See the error below i am on the view from django.db import models class Status(models.Model): description = models.TextField() created_at = models.DateTimeField() updated_at = models.DateTimeField() class Meta: db_table = "status" def __str__(self): return self.description class User(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.CharField(max_length=100) password = models.CharField(max_length=128) created_at = models.DateTimeField() updated_at = models.DateTimeField() signed_agreement = models.BooleanField() class Meta: db_table = "users" def __str__(self): return self.first_name + ' ' + self.last_name class Inventory(models.Model): status = models.ForeignKey(Status, on_delete=models.CASCADE) description = models.TextField() created_at = models.DateTimeField() updated_at = models.DateTimeField() class Meta: db_table = "inventory" def __str__(self): return self.description class Transaction(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user') inventory = models.ForeignKey(Inventory, on_delete=models.CASCADE,related_name='inventory') checkout_time = models.DateTimeField() scheduled_checkin_time = models.DateTimeField() actual_checkin_time = models.DateTimeField() created_at = models.DateTimeField() updated_at = models.DateTimeField() class Meta: db_table = "transactions" def __str__(self): return self.user.first_name + ' ' + self.inventory.description -
psycopg2 copy_from csv with null foreign key field
I'm downloading a CSV file from a URL then trying to load it into a PostgreSQL table using copy_from. On the Product model there's a foreign key field, nutrition, with null=True. class Product(models.Model): ... nutrition = models.ForeignKey( NutritionFact, blank=True, null=True, on_delete=models.SET_NULL, ) In the file a null nutrition field is represented by an empty string ("") which is causing an error: psycopg2.DataError: invalid input syntax for integer: "" CONTEXT: COPY product_product, line 1, column nutrition_id: "" def copy_from_csv(model, reader): opts = model._meta table = f'{opts.app_label}_{opts.model_name}' columns = next(reader) # first row of csv is columns buffer = io.StringIO() writer = csv.writer(buffer, delimiter='\t') for row in reader: writer.writerow(row) model.objects.all().delete() buffer.seek(0) with closing(connection.cursor()) as cursor: cursor.copy_from( buffer, table=table, sep='\t', columns=columns, ) I've tried csv.writer(buffer, delimiter='\t', escapechar='\\', quoting=csv.QUOTE_NONE) but the error persists. -
Can't convert Request to PhoneNumber. django rest custom token auth
I am trying to create custom token authentication end point which accepts phone number and token and status in request POST then response shoud ba as follows Successful response should create a status object linked to the user object Failing request can be either unauthorized request or bad request based on auth-token/phone number combination. to do that I wrote following snippets: serializers.py class TokenSerializer(serializers.Serializer): phone_number = serializers.CharField(required=True, allow_blank=False) def validate(self, attrs): phone_number = attrs.get('phone_number') user = authenticate(request=self.context.get('request'),phone_number=phone_number) if user is None: msg = ('Unable to log in with provided credentials.') raise serializers.ValidationError(msg, code='authorization') else: msg = ('Must include "phone_number.') raise serializers.ValidationError(msg, code='authorization') attrs['user'] = user return attrs views.py class TokenView(APIView): serializer_class=TokenSerializer authentication_classes = (CustomTokenAuthentication, ) def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) new_data = serializer.data user = serializer.validated_data login(request,user) token, created = Token.objects.get_or_create(user=user) return Response({ 'user':new_data, 'token':token.key }) authbackend.py: class CustomTokenAuthentication(TokenAuthentication): def authenticate_credentials(self, key,phone_number): try: user = UserProfile.objects.get(phone_number=username) return user except ObjectDoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a non-existing user (#20760). raise exceptions.AuthenticationFailed('Invalid phone ') try: token = self.model.objects.get(key=key) except self.model.DoesNotExist: raise exceptions.AuthenticationFailed('Invalid token') return (token.user, token) when try to login I got this …