Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I choice data is put to model or one is not do to it?
I wanna parse excel and put data in the model(User). views.py is #coding:utf-8 from django.shortcuts import render import xlrd from .models import User book = xlrd.open_workbook('../data/data.xlsx') sheet = book.sheet_by_index(1) for row_index in range(sheet.nrows): rows = sheet.row(row_index) print(rows[1]) for row in rows: user = User(user_id=row[1], name_id=row[2], age=row[3], name=rows[4]) user.save() Excel is excel I do not want to put data of row whose user_id & name column is empty.In this case,I do not want to put data of line 5 & 6 .But now, my code is to put all excel data to User model.I cannot understand how to extract excel data and put to model.What should I do to do so?I thought if content of list is empty, the data should be skipped.But list is not separate each content, for example [1,1,40,Tom] can be counted 1 list. -
Django request with user criteria
I would like to get some help about my future process. I would like that users could create his own django request and then get the result. Up to now, I created django requests in my script but there are static requests : request1 = Test.objects.all() or query_lastname_ID = request.GET.get('q1ID') query_firstname_ID = request.GET.get('q1bisID') query_naissance_ID = request.GET.get('q1terID') if query_firstname_ID and query_lastname_ID and query_naissance_ID : query_ID_list = Individu.objects.filter( Nom__icontains=query_lastname_ID, Prenom__icontains=query_firstname_ID, VilleNaissance__icontains=query_naissance_ID) if len(query_ID_list) != 0 : messages.success(request, 'Miracle .. Vous avez un résultat !') else : messages.error(request, "Oh non .. Vous n'avez aucun résultat !") All of these requests are static. Now I would like to let the choice to the user between criteria or mathematic operator. I won't write table fields in my request but the user could have the choice to get what he wants : one field two fields x fields the mathematic operator (=, >, <, not egal, ...) comparison between fields ... User could get a result thanks to a dynamic request. He could create himself Django request. Is it possible ? I don't find example or documentations about this kind of process :/ -
Django table is not created in postgresql
i have a app name homepage and i added new classes Movie and Songs in homepage/models.py but when i tried to add data using django admin it says relation "homepage_movie" does not exist. i did 1.delete homepage migration folder 2. manage.py makemigrations homepage 3.manage.py migrate no error occurred during migration but in database table is not created homepage/models.py class Movie(models.Model): name= models.CharField(max_length = 100) movie_poster = models.FileField() def __str__(self): return self.name class Songs(models.Model): song = models.ForeignKey(Movie,default=1) song_name = models.CharField(max_length=20) song_url = models.FileField(upload_to='songs/') -
unable to create superuser in python Django
I have read questions in Stackoverflow and googled, but no luck. I am trying to create a superuser in pycharm(manage.py createsuperuser ) but got below error: cassandra.protocol.SyntaxException: what am I doing wrong? I am using Cassandra 3.0, Python Django 1.11.4, and pycharm. -
Django: non-nullable field without a default
In Django I use manage.py makemigrations and manage.py migrate on the following models.py file: class Family(models.Model): comment1 = models.CharField(max_length=80) #comment2 = models.CharField(max_length=80) After this succesful initialization I change models.py to (I just uncomment the new model field which is basically a copy of the other model field): class Family(models.Model): comment1 = models.CharField(max_length=80) comment2 = models.CharField(max_length=80) Now when I try to makemigrations again I get the following error: You are trying to add a non-nullable field 'comment' to family without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option: Why didn't I get this error upon intialization in the first place? -
Django raw sql with datetime
I use postgres for my django project, and for complicated queries to db i use connection.cursor(). Today I have a problem with raw sql query with datetime in filter: with connection.cursor() as cursor: cursor.execute( "SELECT * from orders_orderstatus WHERE datetime > '2017-09-05 16:07:16'" ) row = [item[0] for item in cursor.fetchall()] return row As result we have empty list. But if I query this from psql console, I see that result is not empty: SELECT * FROM orders_orderstatus WHERE datetime > '2017-09-05 16:07:16'; id | status | datetime ----+--------------------+-------------------------------+ 256 | created | 2017-09-05 16:10:59.602091+07 257 | delivered | 2017-09-05 16:11:00.834547+07 258 | created | 2017-09-05 16:11:03.499364+07 Why django doesn't receive this results? -
Django Wagtail Searching PDF file contents
Is there a simple tool that I can integrate to a class that inherits from the Page class that allows me to search actual text in pdf files? i.e. i have a class which has the following fields class involvedItemBlock(blocks.StructBlock): title = blocks.CharBlock(required=True, max_length=255, min_length=1) info = blocks.RichTextBlock(required=True, max_length=255, min_length=1) image = ImageChooserBlock(required=False) external_link = blocks.CharBlock(required=False) class News(Page): description = StreamField([("agenda",genericItemBlock())], null=True, blank=True) docs_en = StreamField([("documents",involvedItemBlock())], null=True, blank=True) Now having said all that each News item is an instance of the News class. I can easly search through test in the description but how do i search for text within each document of each instance as well as the documents of all instances. To reiterate i have to News items: 1) Title: 2017-01-01 movement report (this has 5 documents in it's streamfield field titled doc_en) 2) Title: 2017-01-08 government report (this has 2 documents streamfield field titled doc_en) I would like to search a total of 7 documents, what library or tool could do this efficiently and hopefully can be integrated with Django/Wagtail. -
Math Between 2 Columns and Group By
I am trying to do a complex query via Django ORM: SELECT SUM(((BUY_UNITS*BUY_NAV)-(SELL_UNITS*SELL_NAV))) AS NET_CAP, PRODUCT FROM TRADING_DB.OPEN_MUTUAL_FUND_POSITIONS GROUP BY PRODUCT; So i initially i did something like this: MutualFundPositions.objects.filter(client_id=X1234).annotate(net_cap=Sum(("buy_units" * "buy_nav") - ("sell_units" * "sell_nav"))).values('product', 'net_cap') Didn't work, so I tried to do it using F in django, MutualFundPositions.objects.filter(client_id=X1234).annotate(net_cap = F(F('buy_units') * F('buy_nav')) - F('sell_units') * F('sell_nav')).values('product', 'net_cap') AttributeError at /client/details/capital/ 'CombinedExpression' object has no attribute 'split' Models.py: class MutualFundPositions(models.Model): client_id = models.CharField(db_column='CLIENT_ID', max_length=45, primary_key=True) mf_name = models.CharField(db_column='MF_NAME', max_length=100) buy_units = models.DecimalField(db_column='BUY_UNITS', max_digits=10, decimal_places=5) buy_nav = models.DecimalField(db_column='BUY_NAV', max_digits=10, decimal_places=5) sell_units = models.DecimalField(db_column='SELL_UNITS', max_digits=10, decimal_places=5) sell_nav = models.DecimalField(db_column='SELL_NAV', max_digits=10, decimal_places=5) current_nav = models.DecimalField(db_column='CURRENT_NAV', max_digits=10, decimal_places=5) product = models.CharField(db_column='PRODUCT', max_length=45, blank=True, null=True) date = models.DateField(db_column='DATE', blank=True, null=True) class Meta: db_table = 'OPEN_MUTUAL_FUND_POSITIONS' serializer.py: class MutualFundSerializer(serializers.ModelSerializer): pandl = serializers.SerializerMethodField() class Meta: model = MutualFundPositions fields = ['mf_name', 'product', 'buy_units', 'buy_nav', 'sell_units', 'sell_nav', 'pandl','current_nav', 'date'] def get_pandl(self, instance): net_qty = abs(instance.buy_units - instance.sell_units) net_nav = instance.current_nav - instance.buy_nav return net_qty * net_nav What am i doing wrong here ? -
Django if image was not uploaded from admin add default image
I have a problem with Django image field. I should do image optional. If admin did not uploaded image django should add default image. How can do this? Here is my code: class News(models.Model): news_title = models.CharField(max_length=255) news_text = models.TextField(max_length=5000) news_short_text = models.CharField(max_length=255) news_logo = models.ImageField(upload_to='uimages', blank=True, null=True, default='') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Thanks in advance -
Delete method on Django Rest Framework ModelViewSet
i have tried to delete a single ManuscriptItem instance using Postman to perform my API requests on against the view below: class ManuscriptViewSet(viewsets.ModelViewSet): """Handles creating, reading and updating items.""" authentication_classes = (TokenAuthentication,) serializer_class = serializers.ManuscriptItemSerializer permission_classes = (permissions.PostOwnManuscript, IsAuthenticated,) def perform_create(self, serializer): """Sets the user profile to the logged in user.""" serializer.save(author=self.request.user) def get_queryset(self): """ This view should return a list of all the manuscripts for the currently authenticated user. """ user = self.request.user return models.ManuscriptItem.objects.filter(author=user) def destroy(self, request, *args, **kwargs): instance = self.get_object() self.perform_destroy(instance) return Response(status=status.HTTP_204_NO_CONTENT) def perform_destroy(self, instance): instance.delete() The destroy and perform destroy functions are what I have attempted without success. This is what it returns when i tried: { "detail": "Method \"DELETE\" not allowed." } This is how my URLs are currently registered: router = DefaultRouter() router.register('manuscripts', views.ManuscriptViewSet, base_name="manuscripts") # auto basename for models router.register('manuscriptlibrary', views.ManuscriptLibraryViewSet, base_name="manuscript_library") router.register('manuscriptsettings', views.ManuscriptSettingsViewSet) urlpatterns = [ url(r'', include(router.urls)) ] I'm i modifying the ModelViewSet wrong do i need to use another approach because of the nature of ModelViewSet? i expected it to work on Postman when i used an Authorized user to Delete a ManuscriptItem instance. In the docs it said Destroy() method can be used. -
Django Rest Swagger -> No Authentication + multiple apps
We are looking to use django swagger for generating REST API docs. Our app consists of many sub apps and all views use JWT authentication. Document seems very lacking and just mentions the adding of url. This shows me error 400 : ["The schema generator did not return a schema Document"] http://10.0.0.61:8001/API/?format=openapi from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title="HashCove REST API") urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'info/', BackendVersion.as_view()), url(r'^transaction/', include('kyc_rest_services.kyc_connect_transaction_manager.urls')), url(r'^drive/', include('kyc_rest_services.carbon_drive.urls')), url(r'^channels/', include('kyc_rest_services.channels.urls')), url(r'^accounts/', include('kyc_rest_services.kyc_connect_accounts.urls')), url(r'^API/', schema_view, name="docs") ] Can it show all the APIs in the other apps and no authentication required. -
Django model fields from constants?
How to define a Django model field in constant and use everywhere. For example, if I have a model like:- class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) email = models.EmailField() And what I want to do is define constant for fields in Author model and provide the constant instead of field name in model like:- KEY_FIRST_NAME = 'first_name' KEY_LAST_NAME = 'last_name' KEY_EMAIL = 'email' And Author model should use the constant instead of exact key like:- class Author(models.Model): KEY_FIRST_NAME = models.CharField(max_length=30) KEY_LAST_NAME = models.CharField(max_length=40) KEY_EMAIL = models.EmailField() How to do something like this, direct assignment to constant won't work here. The purpose of doing this is If there is any change in filed name in future version then I want to only change at one place and it should reflect on all the places. -
I have added admin interface to my app , but under django login interface I am not able to see my created app
**Below are mentioned files under** In the admin interface - is it possible to set a field to readonly, but also set the value? For example, I am building a CRM and a organization will have a program. I want the user who is creating a program to always use the organization that they belong to. example: Program name helloapp User name helloapp I mentioned it as admin.py : from django.contrib import admin from .models import Msisdn admin.site.register(Msisdn) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.admin', 'django.contrib.staticfiles', 'helloapp', ) created simple form to add numbers along with creation date and other fields models.py class Msisdn(models.Model): msisdn=models.CharField(max_length=50) created_by=models.CharField(max_length=30) created_on=models.DateTimeField() updated_by=models.CharField(max_length=30) updated_on=models.DateTimeField() status=models.CharField(max_length=30) def __unicode__(self): return '%s' %self.msisdn -
Django: Gmail SMTP error: please run connect() first
I am trying to send mail when a certain query is executed. But I am getting error in the connection. I have tried the following settings in my settings.py file server = smtplib.SMTP('smtp.gmail.com') server.starttls() EMAIL_HOST_USER = "email@gmail.com" EMAIL_HOST_PASSWORD = "password" server.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD) I have executed the following command to send the email: emailFrom = [settings.EMAIL_HOST_USER] html_content = render_to_string('template.html', {'greeting_text': greeting_text}) text_content = strip_tags(html_content) email_subject = "Subject" msg = EmailMultiAlternatives(email_subject,text_content,emailFrom,[email],) msg.attach_alternative(html_content, "text/html") msg.send() But whenever I run the above code I get 'please run connect() first' error. What is the error Exactly about and how do I solve this? -
Cannot see info messages in Sentry Dashboard (using heroku + django)
I have successfully installed sentry addon on heroku in a django app. I managed to track all errors and 404, following the instructions from the official docs. https://docs.sentry.io/clients/python/integrations/django/ The problem is that i cannot see log info messages, that i have manually added in my code, in the sentry dashboard. The code in my view is the following import logging logger = logging.getLogger(__name__) #somewhere in my code logger.debug('There was some crazy error') And in the settings.py (I used all levels INFO, DEBUG etc) LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'root': { 'level': 'WARNING', 'handlers': ['sentry'], }, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s ' '%(process)d %(thread)d %(message)s' }, }, 'handlers': { 'sentry': { 'level': 'DEBUG', # To capture more than ERROR, change to WARNING, INFO, etc. 'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler', 'tags': {'custom-tag': 'x'}, }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose' } }, 'loggers': { 'django': { 'level': 'DEBUG', 'handlers': ['sentry'], 'propagate': True, }, 'raven': { 'level': 'DEBUG', 'handlers': ['sentry'], 'propagate': False, }, 'sentry.errors': { 'level': 'DEBUG', 'handlers': ['sentry'], 'propagate': False, }, }, } -
AttributeError: 'module' object has no attribute 'connect_signals' in django
Working on a django project, I started getting this error all on a sudden. No code change was made or packages modified. What could be the reason for this issue? -
how tovattach text and pdf file in email in django
i want to attach text/pdf file in mail...but its not working..its giving -'bytes' object has no attribute 'encode'error..whats wrong in my code? www.txt is file saved in dictionary class mail(APIView): def get(self, request, *args, **kwargs): msg = EmailMultiAlternatives("hello", "test mail", "xxx@com",["yy@com"]) attachment = open("www.txt", 'rb') msg.attach('www.txt', attachment.read(), 'text/plain') msg.send() return Response("Sent") -
Django Channels: Can someone provide a very simple working example of data binding?
I'm learning how to implement djnago channels into my website but I have problems understand the documentation (http://channels.readthedocs.io/en/latest/binding.html). There are not many examples on the internet. Can someone provide me working source code of data binding with decent commenting? -
Django model calculated field from one to many relationship
I have inherited some code with a django API and am trying to understand / get to grips with how to modify it appropriately.. I have a Model class called Asset and a Model class called Calibration. A Calibration has a many to one relationship with Asset so: class Calibration(Record): ... asset = models.ForeignKey(Asset, relatedName = "calibrationRecords") ... And when I look at an individual Asset I can see the Calibration records as one would expect. On another section of the API I can list all the Assets for a given Customer, however on this page, the calibrationRecords link is not shown. This is kind of OK as I don't actually want to see all the Calibration records on this view, but I would like to see the last (most recent) Calibration record here, so in essence adding a calculated field onto this Model? Where should this calculation go, and how is the best way to do it? -
Passing Django data to Highcharts via JSON
I've been trying to replicate the method used in this solution thread to display a Highcharts graph via Django, but in vain. I'm passing data from a python script to my views.py file, but the graph doesn't show up - all I can see on my web page is the block heading 'Analysis'. What am I doing wrong here? my my-app/views.py file from __future__ import unicode_literals import datetime from django.shortcuts import render from . import python_script def plot(request, chartID = 'chart_ID', chart_type = 'bar', chart_height = 500): data = python_script.chart_function() categories = python_script.chart_categories() chart = {"renderTo": chartID, "type": chart_type, "height": chart_height,} title = {"text": 'my title here'} xAxis = {"title": {"text": 'axis title here'}, "categories": categories} yAxis = {"title": {"text": 'axis title here'}} series = [ {"name": 'Asia Pacific', "data": data['Asia Pacific']}, {"name": 'CIS', "data": data['Commonwealth of Independent States']}, {"name": 'Europe', "data": data['Europe']}, {"name": 'Latin America', "data": data['Latin America']}, {"name": 'MENA', "data": data['Middle East and North Africa']}, {"name": 'Northern America', "data": data['Northern America']}, {"name": 'SSA', "data": data['Sub-Saharan Africa']} ] return render(request, 'my-app/chart.html', {'chartID': chartID, 'chart': chart, 'series': series, 'title': title, 'xAxis': xAxis, 'yAxis': yAxis}) In my views.py file: the format of data is a dictionary: {'Asia Pacific':[1,2,3,4],'Europe':[1,2,3...], ...} the format … -
Django QuerySet annotation. How to make aware datetime with user's timezone from F expression?
I've created a Django 1.11. application. I have a model to store periods of time for users WeeklySchedule(models.Model): """Model representing a weekly schedule of user""" user_profile = models.ForeignKey(UserProfile) DAY_OF_WEEK =( (1,'Monday'), (2, 'Tuesday'), (3, 'Wednesday'), (4, 'Thursday'), (5, 'Friday'), (6, 'Saturday'), (7, 'Sunday'), ) day_of_week = models.IntegerField(choices=DAY_OF_WEEK) time_from = models.TimeField() time_to = models.TimeField() and I have a model for user's profile class UserProfile(models.Model): # This line is required. Links UserProfile to a User model instance. user = models.OneToOneField(User, related_name='profile') # The additional attributes we wish to include. timezone = models.CharField( max_length=255, choices=[(t,t) for t in pytz.common_timezones], blank=True, null=True) First of all, I try to get aware datetime according user's timezone and to convert all date times in utc later, but I've got an error using make_aware method with F expression: from django.utils import timezone WeeklySchedule.objects.only("user_profile__user__id","time_from","time_to","day_of_week").annotate(dt_from_aware=timezone.make_aware(datetime.date.today() + F('time_from'))).values() Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python3.6/site-packages/django/utils/timezone.py", line 285, in make_aware return timezone.localize(value, is_dst=is_dst) File "/usr/local/lib/python3.6/site-packages/pytz/init.py", line 226, in localize if dt.tzinfo is not None: AttributeError: 'CombinedExpression' object has no attribute 'tzinfo' -
I have problems rendering my comment form on my template in Django
Hi guys i have been looking at trying to integrate a simple comment form on my blog project using Django but the form never shows on my template. Please take a look at my code and tell me whats wrong COMMENT FORM(forms.py) from django import forms from .models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('comment',) VIEWS.PY from django.views.generic import (ListView, DetailView,FormView) from .import models from django.shortcuts import render from django.template import RequestContext from .forms import CommentForm class EntryDetail(DetailView): model = models.EntryPost form_class = CommentForm template_name = "post.html" def comment_valid(request, form): if request.method == "POST": comment_form = form_class(request.POST or None) if comment_form.is_valid(): comment = comment_form.cleaned_data['comment'] comment.save() return super(EntryDetail).comment_valid(form) else: form = CommentForm() return render(request,'post.html',{"form":comment_form,}) FORM TEMPLATE {% extends "base.html" %} {# {% load django_markdown %} #} {% block entry_posts %} <div class="post"> <h2><a href="{% url "entry" slug=object.slug %}">{{ object.title }}</a></h2> <p class="meta"> {{ object.created }} | Tagged under {{ object.tags.all|join:", " }} </p> {{ object.body }} </div> <form method="POST" action="">{% csrf_token %} {{comment_form}} <input type="submit" value="Post Comment" class="btn btn-default"> </form> <div class="post"> <strong>COMMENTS</strong> <hr/> {% for comment in entrypost.comments.all %} {% if comment.approve %} <div class="comment"> <strong>{{ comment.name}}| created:{{comment.created}}</strong> <p>{{comment.comment|linebreaks}}</p> </div> {% endif %} {% empty … -
Django, Mongoengine and TastyPie error: object of type 'NoneType' has no len()
I am using Django, mongoengine and tastypie in my application but I am getting this error in my resource whenever I send a request to the API. The error says: "Error when calling the metaclass bases object of type 'NoneType' has no len()". My resource file looks like this: import logging from django.core import serializers from tastypie.resources import * from tastypie.authorization import Authorization from tastypie_mongoengine.resources import MongoEngineResource from api.models import User logger = logging.getLogger(__name__) class UserResource(MongoEngineResource): class Meta: queryset = User.objects.all() resource_name = 'user' collection = "user" authorization = Authorization() excludes = ['password'] #allowed_methods = ['get'] def dehydrate(self, bundle): # bundle.data['name'] = 'hydrate1' print type(bundle) bundle.data.save() logger.info(serializers.serialize("xml", bundle.data)) return bundle Any idea whats wrong here? -------EDIT------- Here's the full traceback: Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 119, in get_response resolver_match = resolver.resolve(request.path_info) File "/usr/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 366, in resolve for pattern in self.url_patterns: File "/usr/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 402, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 396, in urlconf_module self._urlconf_module = import_module(self.urlconf_name) File "/usr/local/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/userCentral/userCentral/urls.py", line 2, in <module> from api.resources import UserResource File "/userCentral/api/resources.py", line 6, in <module> from tastypie_mongoengine.resources import MongoEngineResource File "/usr/local/lib/python2.7/site-packages/tastypie_mongoengine/resources.py", line 271, in <module> class MongoEngineResource(resources.ModelResource): File … -
Auto-generation of table connections on instance creation in Django
In the following simple system, where a user can collect any number of badges of any type: __________ _____________ _______ | User | | BadgeDone | | Badge | | -------- | <------ | ----------- | ------> | ----- | | username | | count = 0 | | name | |__________| | FK user_id | |_______| | FK badge_id | |_____________| models.py: class BadgeDone(models.Model): count = models.IntegerField(default = 0) user = models.ForeignKey( 'auth.User', on_delete = models.CASCADE, ) badge = models.ForeignKey( 'Badge', on_delete = models.CASCADE, ) def __str__(self): return self.user.username + '_' + self.badge.name class Badge(models.Model): name = models.CharField(max_length = 50) def __str__(self): return self.name I am trying to automatically create connections between a newly created User and every existing Badge, and vice versa (i.e. between newly created Badge and every existing User). To give an example of the desired behaviour: Badges.objects.all() <QuerySet [<Badge: Bronze>, <Badge: Silver>, <Badge: Gold>]> BadgesDone.objects.all() <QuerySet []> User.object.all() <QuerySet []> u = User(username='John') u.save() Badges.objects.all() <QuerySet [<Badge: Bronze>, <Badge: Silver>, <Badge: Gold>]> BadgesDone.objects.all() <QuerySet [<BadgeDone: John_Bronze>, <BadgeDone: John_Silver>, <BadgeDone: John_Gold>]> User.object.all() <QuerySet [User: John]> b = Badge(name='BlackGold') b.save() Badges.objects.all() <QuerySet [<Badge: Bronze>, <Badge: Silver>, <Badge: Gold>, <Badge: BlackGold>]> BadgesDone.objects.all() <QuerySet [<BadgeDone: John_Bronze>, <BadgeDone: John_Silver>, <BadgeDone: … -
CSRF - Referer when performing ajax request from chrome extension with Django Backend
I am using the latest versions of Django and Django Rest Framework. My web application provide an API that is used currently by the front end only. I am on the process to create a chrome extension using the same API routes. When I use the local server runserver command, I have no issue. When the server is runned behind HTTPS I consistently have 403 errors. {"detail":"CSRF Failed: Referer checking failed - no Referer."} The view I used is the following: @method_decorator(csrf_exempt, name='dispatch') class ObtainAuthToken(APIView): permission_classes = (AllowAny,) #maybe not needed in your case def post(self, request): username = request.POST['username'].lower() password = request.POST['password'] user = authenticate(username=username, password=password) payload = dict() if user is not None: token, created = Token.objects.get_or_create(user=user) payload['token'] = token.key payload ["success"] = True else: payload['error'] = "Credentials not valid or user inactive" payload ["success"] = False payload["operation"] = "Obtain Authentication Token" payload ["timestamp"] = get_timestamp() return Response(payload) The AJAX Call is the following: $.ajax({ url: endpoint + "api/1.0/get_auth_token/", type: 'POST', // Fetch the stored token from localStorage and set in the header data: formData, dataType: "json", mimeType: "multipart/form-data", contentType: false, cache: false, processData:false, xhrFields: { withCredentials: false }, headers: { 'Cache-Control': 'no-cache' }, beforeSend: function(xhr) { xhr.setRequestHeader('X-CSRFToken', …