Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
From where this models.Model coming from in django?
As I was creating Django project want to create Models for storing in database later. But in the video the person types : from django.db import models class Post(models.Model): title = models.CharField(max_length=20) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User) Okay, I understand that we are inheriting models class so we can use its properties like CharField, TextField but why we are writing models.Model while inheriting. Can't we just write models? Why he is importing the class method -> Model? Am I missing something in OOPS? -
Error deploying app on google app engine - can't find information on error
I have a Django app which works just fine on my local server. I am now trying to deploy it on GAE, and I'm getting this error ERROR: (gcloud.app.deploy) Your application does not satisfy all of the requirements for a runtime of type [python3]. Please correct the errors and try again. Unfortunately I can't find much information on what the error message is referring to, or whether there is a log that I can look at? Any help would be MUCH appreciated! -
How to include validate_email package into django UserCreationForm?
I downloaded a email validator package from PyPI, link is: https://pypi.org/project/validate_email/ and using pip install validate email and pip install py3dns (since my python is version 3.6.7) into my django project. The problem is I cant seem to get the validate_email function to work on my django project, just wondering what code should I be writing on my django's forms.py and views.py. (not using models.py yet). Please tell me what did I do wrong and what changes should be made to my current code in forms.py. I included "from django.core.validators import validate_email" as seen in forms.py below to try to validate the email entered by any user but it seems that the validate_email works differently from the validate_email from "from validate_email import validate_email". The validation that I need is from PyPI as it is more accurate in validation (e.g. can check if an email is existent or not) whereas the validate_email form django.validators only checks for invalid format and thats it. /* forms.py */ from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.core.validators import validate_email from validate_email import validate_email class UserRegisterForm(UserCreationForm): email = forms.EmailField() phone_number = forms.IntegerField(required=True) class Meta: model = User fields = ['username', … -
App Crashed on my Django app using Heroku
These are all of the error messages: 2019-09-17T01:27:59.832820+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=fast-bayou-25474.herokuapp.com request_id=ab1e197e-ab72-4d03-bec2-8ba06c3db870 fwd="146.115.146.105" dyno= connect= service= status=503 bytes= protocol=https 2019-09-17T01:28:00.339514+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=fast-bayou-25474.herokuapp.com request_id=cad19ccd-31d0-46d1-a31a-891068cc7c87 fwd="146.115.146.105" dyno= connect= service= status=503 bytes= protocol=https 2019-09-17T01:30:44.241612+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=fast-bayou-25474.herokuapp.com request_id=43785608-8070-4b01-8543-fb7bc84c985e fwd="146.115.146.105" dyno= connect= service= status=503 bytes= protocol=https 2019-09-17T01:30:44.744082+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=fast-bayou-25474.herokuapp.com request_id=70e0e3a6-fe27-41fb-924d-c99960303953 fwd="146.115.146.105" dyno= connect= service= status=503 bytes= protocol=https 2019-09-17T01:30:46.607921+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=fast-bayou-25474.herokuapp.com request_id=52842cc3-1869-411a-936c-92b3cae86329 fwd="146.115.146.105" dyno= connect= service= status=503 bytes= protocol=https 2019-09-17T01:30:47.003348+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=fast-bayou-25474.herokuapp.com request_id=1253c722-5c0e-42f3-8679-f51dad8622e9 fwd="146.115.146.105" dyno= connect= service= status=503 bytes= protocol=https Could Somebody please help me? -
In my django app, how to show all posts of similar category if that category is selected?
I'm new to Django so bear with me please. I'm creating an app for posting jobs, and it's based on Corey Schafer's social media tutorial. Each post/job in my app has a category field (NGO, Engineering, Oil&Gas, etc...) My goal is if I select a category, then all jobs of the same category are listed. Corey did the same with the "all posts of a selected author " approach, but I couldn't do similar thing with my category goal. I appreciate all help for guidance. If the pics aren't enough, a general guidance is fine, thanks! urls.py views.py model.py -
Rewriting a Django application from ground-up, is it possible to migrate user model?
I have a web app that I developed while learning back-end web development. I deployed it a while back and ended up getting some real users registered. Unfortunately, I wrote some smelly code and it is becoming very difficult to implement any new features without having to refactor large portions of the code base, so I am planning to rewrite the back-end. The main issue I'm facing is whether there is a way to migrate the CustomUser model I've created to a new PostgreSQL database. Is this possible by simply recreating the same model in the new backend, then doing a pg_dump and restore? -
How to use ajax to link views to form? Django
views.py def contact_form(request): if request.is_ajax(): form = ContactForm(request.POST or request.GET) if form.is_valid(): data = { 'success': True, } status = 200 else: data = { 'success': False, 'errors': form.errors.get_json_data(), } status = 400 return JsonResponse(data, status=status) urls.py urlpatterns = [ path("admin/", admin.site.urls), path("", include("django.contrib.staticfiles.urls")), path("single-post/", single_post, name="single-post"), path("contact-form/", contact_form, name="contact-form"), path("", index), ] index.html <form id="contactForm" method="get" action="{% url 'contact-form' %}"> <input type="text" class="form-control" id="name" name="name" placeholder="Name"> <input type="text" placeholder="Subject" id="msg_subject" class="form-control" name="subject"> <input type="text" class="form-control" id="email" name="email" placeholder="Email"> ... <button class="btn btn-common" id="submit" type="submit">Submit</button> </form> When I submit my form I get: The view app.views.contact_form didn't return an HttpResponse object. It returned None instead. How do I use ajax to link the form to contact_form? -
Improve performance of the an Django MPTT tree
I have implemented the follow model to capture the structure of a classical piece of music. I'm using the MPTT to implement movements, opera acts and arias. model.py: TreeForeignKey(Work, blank=True, null=True, db_index=True, on_delete=models.PROTECT).contribute_to_class(Work, 'parent') mptt.register(Work, order_insertion_by=['id']) class Work(models.Model): attributed_to = models.NullBooleanField() name = models.CharField(max_length=400, null=True, blank=True) lang = models.CharField(max_length=2, null=True, blank=True) name_original = models.CharField(max_length=200, null=True, blank=True) lang_original = models.CharField(max_length=2, null=True, blank=True) name_common = models.CharField(max_length=200, null=True, blank=True) name_common_orig = models.CharField(max_length=200, null=True, blank=True) dedicated_to = models.CharField(max_length=200, null=True, blank=True) pic = models.ImageField(upload_to = 'pic_folder/', default = '/pic_folder/None/no-img.jpg') piece_type = models.CharField(max_length=100, null=True, blank=True) category = models.CharField(max_length=100, null=True, blank=True) date_start = models.CharField(max_length=100, null=True, blank=True) date_start_gran = models.CharField(max_length=5, choices=DATE_TYPES, default='Year') date_signature = models.CharField(max_length=100, null=True, blank=True) date_signature_gran = models.CharField(max_length=10, choices=DATE_TYPES, default='Year') around = models.BooleanField(null=True) date_published = models.CharField(max_length=100, null=True, blank=True) date_published_gran = models.CharField(max_length=10, choices=DATE_TYPES, default='Year') desc = models.TextField(max_length=8000, null=True, blank=True) order = models.CharField(max_length=100, null=True, blank=True) class Work_Music(Work): composer = models.ForeignKey(Composer, verbose_name=_('composer'), null=True, blank=True, on_delete=models.PROTECT) key = models.CharField(max_length=10, null=True, blank=True) tonality = models.CharField(max_length=20, null=True, blank=True) Here is the view.py: class ComposerOverviewView(TemplateView): template_name = 'composers/overview/catalogue.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) opus = Work_Music.objects.filter(composer=self.kwargs['pk'], level=0) context.update({ 'composer': Composer.objects.get(pk=self.kwargs['pk']), 'opus': opus, }) return context When I try to run a query for all of the works for a composer (in the … -
Deploy django with apache and mod_wsgi get internal server error
I try to deploy django on a debian 10 server with apache2 and mod_wsgi. I follow and combine several guides. Now i have installed the following packages: apache2, libapache2-mod-wsgi-py3, apache2-dev an in python3: django, mod-wsgi My apache config file in /etc/apache2/sites-available looks like: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined ServerName 127.0.0.1 ServerAlias localhost Alias /static /home/djangouser/django-project/static WSGIScriptAlias / /home/djangouser/django-project/django-project/wsgi.py <Directory /home/djangouser/django-project/static> Require all granted </Directory> <Directory /home/djangouser/django-project/django-project> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /home/djangouser/django-project/> Order allow,deny Allow from all </Directory> DocumentRoot /home/djangouser/django-project/ </VirtualHost> I use ufw. Now if i go to the website in a browser i get an Internal Server Error. I think my config do this because before i edit the 000-default.conf apache shows the default page. But what is wrong with my config? -
django how to sum item * quantity for each items in cart
How to sum each items in cart * quantity, example first item 10 *- quantity = total, The second one item x * quantity = total, this suma give me the total all items in cart not for each items. def add_produktshitje(request, shitje_id): shitje = get_object_or_404(Shitje, id=shitje_id) suma= Produ.objects.filter(shitje_id=shitje.pk).aggregate(totals=Sum(F('sasia')*F('cmimi'), output_field=FloatField())) return render(request, 'polls/add_produktshitje.html', {'shitje':shitje,'suma':suma}) -
Can I remove verbose name from a django-generated migration?
Simple question. Can I remove verbose name from the 'id' field in this migration below. This migration was generated by manage.py makemigrations # Generated by Django 2.1.5 on 2019-09-16 15:53 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('uatu', '0035_auto_20190703_0849'), ] operations = [ migrations.CreateModel( name='StageExecutionParent', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=150)), model changes here: class StageExecutionParentManager(models.Manager): def get_or_create(self, **kwargs): return self.get_queryset().get_or_create(**kwargs) class StageExecutionParent(JsonableModel): name = models.CharField(max_length=150) manager = StageExecutionParentManager() def reprJSON(self): try: return dict( name=self.name, ) except: return dict() I try to stay away from altering any django created migration, but was instructed to remove the use of verbose name, so just want to make sure before I introduce a corrupted migration. -
django wkhtmltopdf rendered table and common header overlap
Creating pdf by wkhtmltopdf long table overlap with common header. Table rendered successfully and if I remove header it shows data. page break always is not fixing the issue. -
Is it possible to get access to PC system via web app using modules like pyautogui and win32gui/pywin32?
As a training project i have made activity tracker using python (no GUI, only command-line). Script checks with win32gui/pywin32 and pyautogui what program is currently used, and if it is web browser what web site is in use. Name of window, date, and amount of time spent on program/website is stored in sqlite3 database.Then with help of pandas module same names are grouped and time is summed up. I want to convert this script into web app using django but i am beginner in creating web apps, so i am wondering : is it possible to use this modules within django and is it even possible to create web app that works same as script mentioned earlier? Sorry if the question is trivial. I will be grateful for every tip where and what exactly to look for in this topic. -
syntax error trying to run django app with django channels
I am following tutorial at https://realpython.com/getting-started-with-django-channels/ to use django channels. It is using django==1.10.5 channels==1.0.2 asgi_redis==1.0.0 There are few parts main_app/routing.py: from channels.routing import route from example.consumers import ws_connect, ws_disconnect channel_routing = [ route('websocket.connect', ws_connect), route('websocket.disconnect', ws_disconnect), ] example/views.py: def user_list(request): return render(request, 'example/user_list.html') example/consumers.py: from channels import Group def ws_connect(message): Group('users').add(message.reply_channel) def ws_disconnect(message): Group('users').discard(message.reply_channel) The app is very small, but when I try to runserver I get the following error: Unhandled exception in thread started by <function wrapper at 0x0000000004566518> Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 116, in inner_run autoreload.raise_last_exception() File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python27\lib\site-packages\django\apps\registry.py", line 116, in populate app_config.ready() File "C:\Python27\lib\site-packages\channels\apps.py", line 22, in ready monkeypatch_django() File "C:\Python27\lib\site-packages\channels\hacks.py", line 10, in monkeypatch_django from .management.commands.runserver import Command as RunserverCommand File "C:\Python27\lib\site-packages\channels\management\commands\runserver.py", line 5, in <module> from daphne.server import Server, build_endpoint_description_strings File "C:\Python27\lib\site-packages\daphne\server.py", line 213 async def handle_reply(self, protocol, message): When I hit the main page, localhost:8000, it says "connection refused". How can I remove this error and get the app running? Thank you -
Django scheduler with aws-lambda
I have Django Postgres Database with DateField which is date of sending some message (SMS and email). I would like to schedule delivering somehow (so basically run function with parameters at this date). Everything is running on aws-lambda. I read Django - Set Up A Scheduled Job? but I wondering if there isn't some strictly aws solution (I'm not so familiar with AWS). Thanks! -
Error in Django while accessing external python script
I am writing a button click HTML code with multiple of them calling external python script and if my external python script is not using any call or open functions it is working fine. If my external python script has open ("another python script") then in django it is showing the file error as i didn't mention the path for the call.py script file in views.py file -
error on execute import django in python3 shell and script
when i want do an import django i get an error ubuntu 18.04 with a reverse proxy (nginx) and uwsgi (mode emperor actived) in virtual env with python 3.6.3 and latest django 2.2.5 test.py : import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproject.settings") import django print("test") when i run python3 test.py i get : (venv) :~/testproject/testproject/testproject$ python3.6 test.py Traceback (most recent call last): File "test.py", line 3, in from django.http import HttpResponse File "/home/lukas/testproject/venv/lib/python3.6/site-packages/django/init.py", line 1, in from django.utils.version import get_version File "/home/lukas/testproject/venv/lib/python3.6/site-packages/django/utils/version.py", line 4, in import subprocess File "/usr/lib/python3.6/subprocess.py", line 140, in import threading File "/usr/lib/python3.6/threading.py", line 7, in from traceback import format_exc as _format_exc File "/usr/lib/python3.6/traceback.py", line 5, in import linecache File "/home/lukas/testproject/venv/lib/python3.6/linecache.py", line 11, in import tokenize File "/home/lukas/testproject/venv/lib/python3.6/tokenize.py", line 35, in from token import * File "/home/lukas/testproject/testproject/testproject/token.py", line 1, in from django.contrib.auth.tokens import PasswordResetTokenGenerator File "/home/lukas/testproject/venv/lib/python3.6/site-packages/django/contrib/auth/init.py", line 4, in from django.apps import apps as django_apps File "/home/lukas/testproject/venv/lib/python3.6/site-packages/django/apps/init.py", line 2, in from .registry import apps File "/home/lukas/testproject/venv/lib/python3.6/site-packages/django/apps/registry.py", line 426, in apps = Apps(installed_apps=None) File "/home/lukas/testproject/venv/lib/python3.6/site-packages/django/apps/registry.py", line 46, in init self.ready_event = threading.Event() AttributeError: module 'threading' has no attribute 'Event' i have the same error on python3 shell when i do "import django" whereas django have been installed with pip3 install and … -
Django Custom Validation
I am new bie in Django, I used MultiModelForm in my application and change selectbox field as textbox. When I try to save form, I am getting validation error (Select a valid choice. That choice is not one of the available choices.) because validation requires equipment_id instead of equipment_tagname. Please help me to find the way Models.py from django.db import models from core.models import MyUser from django.db.models import Max from datetime import datetime class System(models.Model): system_tagname = models.CharField(max_length=20, blank=False, verbose_name="Etiket", unique=True) system_content = models.CharField(max_length=50, blank=False, verbose_name="Açıklama", unique=True) def __str__(self): return "%s %s" % (self.system_tagname, self.system_content) class SubSystem(models.Model): system = models.ForeignKey(System, on_delete=models.CASCADE, verbose_name="Ana Sistem", related_name="systems") subsystem_tagname = models.CharField(max_length=20, blank=False, verbose_name="Etiket", unique=True) subsystem_content = models.CharField(max_length=50, blank=False, verbose_name="Açıklama", unique=True) def __str__(self): return "%s %s" % (self.subsystem_tagname, self.subsystem_content) class Equipment(models.Model): subsystem = models.ForeignKey(SubSystem, on_delete=models.CASCADE, verbose_name="Alt Sistem", related_name="equipments") equipment_tagname = models.CharField(max_length=20, blank=False, verbose_name="Etiket", unique=True) equipment_content = models.CharField(max_length=50, blank=False, verbose_name="Açıklama", unique=True) def __str__(self): return "%s" % (self.equipment_tagname) class WorkStatus(models.Model): status_name = models.CharField(max_length=20) class WorkRequest(models.Model): work = models.CharField(max_length=200, blank=False, verbose_name="Açıklama") equipment = models.ForeignKey(Equipment, on_delete=models.SET_NULL, null=True, verbose_name="Ekipman", blank=False, related_name="equipment", ) reported_user = models.ForeignKey(MyUser, on_delete=models.SET_NULL, null=True, verbose_name="Raporlayan", related_name="reported_users", blank=True) created_date = models.DateTimeField(auto_now_add=True, verbose_name="Açılma Tarihi") modified_date = models.DateTimeField(auto_now=True, verbose_name="Son Güncelleme") closing_comment = models.CharField(max_length=300, verbose_name="Kapanış Yorumu", blank=True) status=models.ForeignKey(WorkStatus,on_delete=models.SET_NULL,null=True, blank=True, verbose_name="İşin Durumu",related_name="status") … -
How do I add an image file from windows to a WSL django project directory?
I have a jpeg image on windows and I would like to use it in my Django project. I am using WSL Ubuntu and when I drop the image into my project directory it does not work. I'm having the same issue with a pdf file I'm trying to drop into the directory. If anyone can help that would be great. Thanks, T -
Django running long sql process in background
I have a web page where I need to run a long sql process (up to 20 mins or so) when the user clicks on a certain button. The script runs, but the user is then unable to continue browsing the rest of the website. I would like to have it so that when the button is clicked, it goes into a queue that runs in the background. I have looked inth django-background-tasks, but the problem is that it does not seem to be possible to start the queued tasks without running python manage.py process_tasks. I have heard of Celery, but I am using a Windows system and it does not seem to be suitable. I am new to django and website infrastructures, and am not sure if this is feasible. I have also seen in older response that the threading package can work to do this, but I am unsure if it is outdated. -
How to Configure django_plotly_dash to serve assets from custom url
I have an hybrid app with most pages being on vuejs but some legacy code pages are still being served through dash-django app. previously it was wholly a dash app. on the production environment this is being served through an nginx with dedicated static directory and a reverse proxy. The app is being served on a subdomain. So the url looks like : abd.com/subdom/route_to_app_endpoints where abd.com is set to serve nginx files from base directory and abd.com/subdom is reverse proxy to serve files from port 8000 on which the django application is running. The problem I'm facing is when the app loads the base url i tries to load the components and the layout from is hitting the root directory : eg for abd.com/.django_plotly_dash/app/FileUpload/_dash-layout and it gives 404 not found. This is what it tries by default . whereas if i request abd.com/subdom/django_plotly_dash/app/FileUpload/_dash-layout my browser gives a nice output .. I tried setting : PLOTLY_DASH = { "requests_pathname_prefix" :"/subdom/" } in the settings.py but still it is unable to route properly. -
Django and the moment of instance creation
I was a bit surprised by this bit of code: class DeliveryItem(models.Model): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._original_product = self.product ... def save(): print(self.product) print(self._original_product) super().save(*args, **kwargs) The purpose of this code was to see, whenever a change to the related product was made. The output is as follows: On creation of a DeliveryItem instance with the name "unicorn" --> unicorn --> unicorn On update of a DeliveryItem instance with the name "unicorn" to "voldemort"* --> unicorn --> voldemort This confused me ... the expected behaviour would be: On creation of a DeliveryItem instance with the name "unicorn" --> None(!) --> unicorn On update of a DeliveryItem instance with the name "unicorn" to "voldemort"* --> unicorn --> voldemort Why is the instance created before the save() method is executed? -
Django Template - Bootstrap table numbers in accounting format
I am using Django templates for populating following bootstrap table in UI. I want numbers in the table to be more readable (by using ',' between digits) - for example: if a number is one million, then it should be shown as 1,000,000 and not 1000000 (notice commas ',' between digits). Code <tr id="port_row_{{row.stock}}_{{index}}"> {% if row.stock == 'TOTAL'%} <td> {{row.stock}}</td> {% else %} <td> <a target="_blank" style="color:blue;" href="https://www.google.com/finance?q=NSE:{{ row.stock }}">{{row.stock}}</a></td> {% endif %} <td>{{row.name}}</td> <td>{{row.monday_open_price}}</td> <td>{{row.previous_close}}</td> <td> {% if row.price >= row.previous_close %} <div style="color:green"> {{row.price}} </div> {% else %} <div style="color:red"> {{row.price}} </div> {% endif %} </td> <td>{{row.investment_amount}}</td> <td> {% if row.weekly_gain >= 0 %} <div style="color:green"> +{{row.weekly_gain}} <i class="fa fa-arrow-up"></i> </div> {% else %} <div style="color:tomato"> {{row.weekly_gain}} <i class="fa fa-arrow-down"></i> </div> {% endif %} </td> <td> {% if row.daily_gain >= 0 %} <div style="color:green"> +{{row.daily_gain}} <i class="fa fa-arrow-up"></i> </div> {% else %} <div style="color:tomato"> {{row.daily_gain}} <i class="fa fa-arrow-down"></i> </div> {% endif %} </td> </tr> -
Django yarn collected files 404 error on server
I used yarn to collect several libraries used in my Django project and yarn put them in the node-modules folder. Before pushing to the server, I used python manage.py collectstatic command to collect all my custom css, js and these libraries into the public folder which works fine locally on my computer. but when I try to open my project on the server it gives my 404 error on every file collected using yarn. Console errors screenshot These files are not loaded but I see them with the correct path in my public folder The last two errors were due to jquery not loaded my base.html includes these: {% block stylesheets %} <!-- BootStrap CSS --> <link rel="stylesheet" type="text/css" href="{% static "bootstrap/dist/css/bootstrap.css" %}"> <link rel="stylesheet" type="text/css" href="{% static "@fortawesome/fontawesome-free/css/all.css" %}"> <link rel="stylesheet" type="text/css" href="{% static "academicons/css/academicons.css" %}"> <link rel="stylesheet" type="text/css" href="{% static "fullpage.js/dist/fullpage.css" %}"> <link rel="stylesheet" type="text/css" href="{% static "resume/css/global.css" %}"> {% endblock %} and in my public folder: public folder my settings.py file: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'public') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), os.path.join(BASE_DIR, "node_modules"), os.path.join(BASE_DIR, "media"), ] What I have tried so far: delete the STATIC_ROOT setting, didn't work. Change permission on public folder with chmod … -
Can't submit a post request using Django rest framework ("detail": "CSRF Failed: CSRF token missing or incorrect.")
I am into a weird situation I am login into site and when try to send a post request I didnt get user. its anonymous user instead. And if I use permission_classes = [AllowAny] or isAuthenticate classes I get error CSRF Failed: CSRF token missing or incorrect . And if I use like this in class serializer_class = ReviewSerializer authentication_classes = (BasicAuthentication,) It gives a popup to enter password and user name . My full class is like class AddReview(APIView): serializer_class = ReviewSerializer authentication_classes = (BasicAuthentication,) def post(self, request): rest = request.POST.get('restaurant') dish = request.POST.get('dish') And my settings.py is REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', # 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', # django-oauth-toolkit >= 1.0.0 # 'rest_framework_social_oauth2.authentication.SocialAuthentication', ), } I just want to submit a post custom form to submit data. Any help or suggestion to make question good would be highly appericiated.