Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: redirect http to https safely for Heroku app
I am trying to redirect my Django + Heroku app from http to https, but I am surprised that I did not find any safe and straightforward way. According to Heroku: Issue You have configured an SSL endpoint and now you want your application to use https for all requests. Resolution Redirects need to be performed at the application level as the Heroku router does not provide this functionality. You should code the redirect logic into your application. Under the hood, Heroku router (over)writes the X-Forwarded-Proto and the X-Forwarded-Port request headers. The app checks X-Forwarded-Proto and respond with a redirect response when it is not https but http. ... Django Set SECURE_SSL_REDIRECT to True. So it must be done at Django. This is the most complete answer I found, and this one is also similar. Django 1.8 will have core support for non-HTTPS redirect (integrated from django-secure): SECURE_SSL_REDIRECT = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') In order for SECURE_SSL_REDIRECT to be handled you have to use the SecurityMiddleware: MIDDLEWARE = [ ... 'django.middleware.security.SecurityMiddleware', ] Note that both use SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') It seems that without this setting, it is not working on Heroku. And now comes the interesting/scary part. As … -
Django get a list of related id's linked to each parent record id in a query set?
I have a relationship client has many projects. I want to create a dictionary of the form: { 'client_id': ['project_id1', 'project_id2'], 'client_id2': ['project_id7', 'project_id8'], } what I tried was; clients_projects = Client.objects.values_list('id', 'project__id') which gave me: <QuerySet [(3, 4), (3, 5), (3, 11), (3, 12), (2, 3), (2, 13), (4, 7), (4, 8), (4, 9), (1, 1), (1, 2), (1, 6), (1, 10)]> which I can cast to a list with list(clients_projects): [(3, 4), (3, 5), (3, 11), (3, 12), (2, 3), (2, 13), (4, 7), (4, 8), (4, 9), (1, 1), (1, 2), (1, 6), (1, 10)] -
Django Rest Framework "A valid integer is required."?
I want to default an empty string to a 0 or null during deserialization. JSON { 'civilians': '', } However, I keep getting this error: "A valid integer is required." models.py from django.db import models class Strike(models.Model): location = models.ForeignKey('Location', on_delete=models.CASCADE) civilians = models.PositiveIntegerField(blank=True, null=True) serializers.py from rest_framework import serializers from .models import Strike class StrikeSerializer(serializers.ModelSerializer): civilians = serializers.IntegerField(default=0, required=False) class Meta: model = Strike fields = '__all__' def create(self, validated_data): return Strike.objects.create(**validated_data) main serializer = StrikeSerializer(data=strike) I tried manipulating data in create method, but the error gets raised before that. Where in the DRF structure can I override this, specifically convert '' to 0 or None? -
When does Boto3 set the url? 'location' for runtime storage
I need dynamic storages at runtime because I have different users and I want an S3 'folder' for each of them. This works fine with using: img = Image.objects.create(**raw_data['Image']) img.image.storage = S3Boto3Storage(location='media/%s/stuff/' % user_name) img.save() And it does display the file under the url with the file_name even tough it left out the locations. Now the problem is when I call: S3Boto3Storage(location='media/%s/stuff/' % user_name, file_overwrite=False) It does add a random string at the end of the file and not overwrite, but the url in the template that I call with: <img src="{{ user_image.image.url }}"> Is only having the file name, but lacking the additional "folders" of the location and it is not working at all unless I add the "folders". -
ImportError: No module named 'mysite' in wsgi.py file
I am using Django 2.0.3 version with python 3.4 and I am getting following error in wsgi file. I didn't make any changes in the file.errors wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") application = get_wsgi_application() -
Change selected color in django material library
I would like to change selected color on bottom border and text when select form field. example can be looked at : http://materializecss.com/forms.html#select When selecting form filed it colored green(ish) I am using http://forms.viewflow.io/ library, and I try several thinks, but without any luck... I try to apply theme : inside INSTALLED_APPS : in settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'material.theme.green', 'material', 'material.frontend', ..., ] change css I try to change css to make it work .input-field > label:active { color: green; } .input-field > label { color: green; } It change the label but now when it is selected. (And it paint black bottom border (line) when it is selected over) Is there a way to do this? It should be, right,... -
ModelChoiceField in conjuction with ModelForm
I want the user to be able to select a Solar Collector type from a dropdownlist. At this point the user is able to select two collector types from the dropdownlist in the SystemUpdateView() but however this value is apparently not stored into the database. The system.collector variable stays empty and the dropdownlist does not remember the chosen value. The simplified example has two models, the solar Collector model and the solar System model, i.e.: class Collector(models.Model): system = models.ForeignKey('system.System', related_name='collectors', on_delete=models.CASCADE) collector_name = models.CharField(default='', max_length=200) collector_area = models.FloatField(default=2.31) @classmethod def create( cls, system, collector_name, collector_area): collector = cls(system = system, collector_name = collector_name, collector_area = collector_area) return collector class System(models.Model): system_name = models.CharField(default='default_name', max_length=200) @classmethod def create( cls, system_name): system = cls(system_name = system_name) system.save() # Create the collector objects Collector.objects.all().delete() collectors = [] collectors.append( Collector.create(system=system, collector_name = "Solarus PVT collector 11s", collector_area = 2.2)) collectors.append( Collector.create(system=system, collector_name = "Solarus PVT collector 1.0", collector_area = 2.31)) collectors_objects = Collector.objects.bulk_create(collectors) collector_objects.save() return system The SystemForm is given as: class SystemForm(forms.ModelForm): collector = forms.ModelChoiceField(required=False, queryset=Collector.objects.all(), label='Collector') # required=True, class Meta: model = System fields = [ 'collector', 'system_name' ] The create and update views are given by: class SystemUpdateView(LoginRequiredMixin, UpdateView): model … -
django rest framework how to close Self describing APIs browsable
Like the image, i want close The browsable API that REST framework provides . click to visit directly json data. self describing -
Why my mock is not called?
I'm trying to mock a call to a Stripe API (create_stripe_charge) I don't understand why the mock is not called in my unit test. I was always told we need to patch the method where it is called, not where it is defined. I think it's what I did, but still bad, Stripe is called. What I did wrong? Here is the simplified code below. finances/stripe.py def create_stripe_charge(...): # ... finances/models.py from .stripe import create_stripe_charge class MoneyTransaction(models.Model): def create(...) create_stripe_charge() # ... finances/tests.py with patch('finances.models.create_stripe_charge') as mock: stripe_transaction = MoneyTransaction.create(...) # ... -
Is it possible to work with temp dirs in celery tasks?
I am getting files in view, I would like to put them into temp dir and then transfer dir name to celery task where I'll be able to handle that files. The issue is that directory is already deleted when celery task starts -
Django __str__ returned non-string (type DeferredAttribute)
I am having a little problem with Django. When I try to access a particular view I get the error of the title __ str__ returned non-string (type DeferredAttribute). I believe it has something to do with a form that I render in the view but I can't find the problem by myself. Here is my model: class ItemElements(models.Model): itemid = models.ForeignKey(Items, on_delete = models.CASCADE) elementid = models.ForeignKey(Elements, on_delete = models.CASCADE) percentage = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) The form: class ItemElementsForm(forms.ModelForm): class Meta: model = ItemElements fields = ['itemid', 'elementid', 'percentage'] labels = { 'itemid' : 'Item', 'elementid' : 'Element', 'percentage' : 'Percentage' } I can't really see the problem. If I need to post something else, please let me know! -
using a field of one class in another class in forms.py
I have 2 classes in forms.py, I want to access one of those classes inside another class. class A(forms.ModelForm): filename = forms.FileField(label='Select a file') class Meta: model = File fields = ('filename',) class B(forms.ModelForm): filename = A class Meta: model = Rack fields = ('rack',) Both of the classes are using different models (I cannot modify models.py). I want a field filename in class B that is sort of creating a widget from class A, basically want the same filename atrribute from class A in class B. How to achieve this? -
Can't change/redirect page via AJAX
So I start on the post_ad() view. When I submit boost_form, the view successfully changes to options() - where the template changes to advertising/options.html. However the page URL stays the same (/advertise/post/). When I perform my ajax function, it successfully fires the first ajax call (if request.POST.get('position'):) and prints the relevant variables. I then have another ajax call (an onsubmit for a form) which then calls the 2nd ajax in my options() view: if request.POST.get('confirmed') == 'confirmed'. This succesfully fires, and the print statements in my pay() view fire, however my terminal doesn't show the POST request for pay(): Position: 8 Duration: 106 Total price: 63 [10/Apr/2018 10:46:38] "POST /advertise/options/ HTTP/1.1" 200 13484 the final view Pay Pay ajax [10/Apr/2018 10:46:40] "POST /advertise/options/ HTTP/1.1" 200 11615 and subsequently doesn't load the pay.html template. Can somebody tell me why this is? Here's my code: def post_ad(request): boost_form = AdvertisePostForm(request.POST or None, request.FILES or None) if boost_form.is_valid(): instance = boost_form.save(commit=False) if Post.objects.filter(hash=instance.hash).exists(): instance.hash = random_string() instance.ad = True instance.save() return options(request) context = { 'boost_form': boost_form } return render(request, 'advertising/post_ad.html', context) def options(request): latest = AdvertisePost.objects.order_by('-id')[0] ad = get_object_or_404(AdvertisePost, hash=latest.hash) if request.is_ajax(): if request.POST.get('position'): position = request.POST.get('position') duration = request.POST.get('duration') total_price = … -
usinig Django urls in react, is_authenticated in react, displaying context in react
So, I've got 3 questions How to use Django's URLs in react EXAMPLE: index.js (in react) <Router> <div> <nav className="navbar navbar-inverse bg-inverse"> <div className="container"> <Link to="/" className="navbar-brand">PetFinder</Link> <Link to="/storage" className="navbar-brand">Storage </Link> <a href="{% url 'signup' %}">Sign-Up</a> <== like this </div> </nav> <Route exact path={"/"} component={PetRegistration} /> <Route path={"/storage"} render={() => <Storage ids={checkingName} />} /> </div> </Router> urls.py urlpatterns = [ path('admin/', admin.site.urls), #path('api-auth/', include('rest_framework.urls', namespace="rest_framework")), path('api/animals/', include('petsite.urls', namespace='petsite')), path('api/user_info', core_views.UserInfo.as_view()), path('signup/', core_views.signup, name='signup'), path('', csrf_exempt(core_views.index), name='index'), path(r'^login/$', auth_views.login, name='login'), ] is_authenticated in react How I did it: In index.html I wrote this ******. I am ashamed of this. Don't judge me, okay just a bit... <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="theme-color" content="#000000"> <!-- manifest.json provides metadata used when your web app is added to the homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/ --> <link rel="manifest" href="%PUBLIC_URL%/manifest.json"> <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> <!-- Notice the use of %PUBLIC_URL% in the tags above. It will be replaced with the URL of the `public` folder during the build. Only files inside the `public` folder can be referenced from the HTML. Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will work correctly both with client-side routing and a non-root public URL. Learn … -
Django 2, How to instance Form in FormView with POST request
I have a form made with html, I'm using a formview to take advantage of the POST method, the form has information on several html related select (interactive with Javascript), so the best option for me was to create an html form. In summary I want to instance a forms.Form with the POST information, process the form, return the error messages or save (save is not the problem) Code Form View class ServiceOrderForm(forms.Form): TYPE = ( ('preventivo', 'Preventivo'), ('correctivo', 'Correctivo'), ) STATUS = ( ('abierta','Abierta'), #amarillo ('aprobada','Aprobada'), #verde ('modificada','Modificada'), #rojo ('realizada','Realizada'), #azul ('rechazada','Rechazada'), #naranja ('Cerrada','Cerrada'), #Azul con check ) id_orden_servicio = forms.IntegerField() id_establecimiento = forms.IntegerField() id_equipo_establecimiento = forms.IntegerField() hora_entrada = forms.DateField() hora_salida = forms.DateField() tipo = forms.ChoiceField(choices=TYPE) id_tecnico = forms.IntegerField() fecha_panificada= forms.DateField() hora_planificada = forms.DateField() fecha = forms.DateField() estado = forms.ChoiceField(choices=STATUS) observaciones = forms.TextInput() View class ServiceOrderTemplateView(FormView): ''' Presenta el formulario del evento y sus detalles ''' template_name = 'serviceorders/service-order.html' form_class = ServiceOrderForm def get(self, request, **kwargs): context = super(ServiceOrderTemplateView, self).get_context_data \ (**kwargs) if request.user.is_authenticated and self.request.user.is_active: customer_group = CustomerGroupData(request.user.id).get() context_data_event = ContextDataEvent(customer_group) event_service = ServiceEvent(kwargs['id_order_service']) event_data = event_service.getEvent() estado_equipo = { 'garantia': { 'label': 'danger', 'icon': 'fa-ban', }, 'vida_util' : { 'label': 'success', 'icon': 'fa-check', } } data = … -
Setting up a home server to retrieve mp3 urls
I am developing an amazon Alexa skill to stream our music from the web. I would like to have a database of mp3s that is accessible by my app but the mp3s should not be public for download but only for streaming. Thus spotify or soundcloud don't seem to me like good options. I was thinking to set up a home server where to physically store the mp3s thus having easy access to their urls to pass to the Alexa's AudioPlayer, but I have little experience in setting up servers. Do you have any alternative workaround suggestions for my issue? In case the home server might seem a reasonable option to you, where can I start to understand how to do that? (I code mainly in Python and I know very little of Django) -
Filtering query inside ForeignKey
Let's say I have 100 players and 10 teams how can I remove any player from FroreignKey drop-down chooser that is already was chosen for another team? inside SpielerTeamRelationshipModel I have player = models.ForeignKey(Spieler) and I would like it not to show players who have already been selected for another teams. Is this possible? class Spieler(models.Model): name = models.CharField(max_length=128) vorname = models.CharField(max_length=128) panels = [ FieldPanel('name', classname="col6"), FieldPanel('vorname', classname="col6"), ] class SpielerTeamRelationshipModel(models.Model): player = models.ForeignKey(Spieler) in_team_seit = models.DateField() page = ParentalKey('TeamRooster', related_name='spieler_in_team') panels = [ FieldPanel('player', classname="col6"), FieldPanel('in_team_seit', classname="col6") ] class TeamRooster(Page): content_panels = [ FieldPanel('title'), InlinePanel( 'spieler_in_team', label="Spieler", panels=None) ] One Player can be only in one Team. One Team can have one or more players. Very convenient for this is InlinePanel, but every time to choose one player from 100, it's excruciating. Or maybe I'm not doing the right thing and there's a smarter way to solve this problem? -
Override unique_together error message
I am trying to use unique_together for two fields (email and type) for Meta for a model, but the the error message is always "The fields email, type must make a unique set." What is the best way to override the unique_together error message? -
Heruko Django application error- Website not being loaded
Hey guys i have created my first django website! and i want to upload it through Heroku, So i followed everything they said to me and i am still getting application error when i am trying to do heruko open I get an application error and as i am beginner to heruko i am frustrated to get errors! I found that i am getting error here while i do git push heruko master I get all things ready but a small error after deploying is done and the error is: Counting objects: 30, done. Delta compression using up to 2 threads. Compressing objects: 100% (30/30), done. Writing objects: 100% (30/30), 13.62 KiB | 422.00 KiB/s, done. Total 30 (delta 2), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing pip remote: -----> Installing requirements with pip remote: remote: -----> $ python manage.py collectstatic --noinput remote: 118 static files copied to '/tmp/build_d2ad5fb0675c6c8305a3ad0fb5 819fe4/static', 131 post-processed. remote: remote: -----> Discovering process types remote: Procfile declares types -> (none) remote: remote: -----> Compressing... remote: Done: 54.3M remote: -----> Launching... remote: Released v9 remote: https://kiran-portfolio.herokuapp.com/ deployed to Heroku remote: remote: Verifying deploy... … -
Getting 'TooBig' Memcachier exception on a Django Rest Framework response on Heroku
I have a Django site on Heroku, which uses Memcachier's free tier as a basic cache across the whole site. It works fine. I've just started trying out Django Rest Framework to create a read-only JSON API, and that works fine too, except... one or more API URLs generate 'TooBig' exceptions from Memcachier, even though the response isn't very large (e.g. 20-30 KB): MemcachedError: TooBig No exception message supplied I'm puzzled as to why this is happening, given the small size, and not sure how to fix it. Maybe I've misunderstood something about how memcached works. -
Django migrations - AddField is actually removing it
I have a django blog project, and recently made changes to my local environment and so am now manually migrating to my production server. I've managed to nearly complete this, however when in psql / postgres I use the command: \d posts_post The foreign key field: "Category" ( models.ForeignKey('Category', null=True, blank=True)) Is nowhere to be seen as per the terminal. I've made another migration file as such: from __future__ import unicode_literals from django.db import migrations, models import mptt.fields import django.utils.timezone import mptt from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('posts', '0016_remove_post_category'), ] operations = [ migrations.AddField( model_name="Post", name = "Category", field = models.ForeignKey('Category', null=True, blank=True) ), ] However when I run the migrate command it actually removes the field. a) Why does the manager remove my field instead of adding it? b) Why is it doing this despite apparently not existing in the first place? -
Multiples get_or_create in loop with inner loop, database performance issue
I have the following Django models: class Property(models.Model): name = models.TextField(unique=True, db_index=True) class AirtableProduct(models.Model): internal_id = models.IntegerField(unique=True, db_index=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class AirtableProductPropertyValue(models.Model): airtable_product = models.ForeignKey(AirtableProduct, on_delete=models.CASCADE, related_name='properties') property = models.ForeignKey(Property, on_delete=models.CASCADE) value = models.TextField() class Meta: unique_together = (('airtable_product', 'property'),) index_together = [ 'airtable_product', 'property' ] They represent an object (AirtableProduct) identified by an internal_id and with a variable number of properties that I represent with the Property and AirtableProductPropertyValue tables. The problem comes with the following piece of code, when creating/updating a product and its properties: // products is an array of dictionary with the properties as key/value def insert_all_airtable_products(products): logger.info('Inserting Airtable products into the database') for product in products: internal_id = product.pop('Internal ID') ap, created = AirtableProduct.objects.get_or_create(internal_id=internal_id) for field in product: property, created = Property.objects.get_or_create( name=strip_spaces(field) ) ap_pv, created = AirtableProductPropertyValue.objects.get_or_create(airtable_product=ap, property=property) ap_pv.value = strip_spaces(product[field]) ap_pv.save() I have 10,000 products, each one with 20+ properties, given that I have to loop through each product and update/create old/new properties the cost of this operation is being high for the database. How can make it better? -
Best python framework for rasanlu
I have created a chatbot using rasanlu. In UI and request processing which one is the best framework in python. -
uWSGI segmentation fault when using Django and python requests
I am running Django 2.0 app with uWSGI 2.0.17 and python 3.4 on an openSUSE Leap 42.3 x86-64 server and it's working fine the problem is when trying to send http request using python requests librarys uWSGI segmentation fault occures here is the log from uwsgi 2018-04-10 06:46:15,136 | DEBUG | Starting new HTTPS connection (1): www.googleapis.com !!! uWSGI process 30352 got Segmentation Fault !!! *** backtrace of 30352 *** /usr/bin/uwsgi(uwsgi_backtrace+0x2e) [0x46b92e] /usr/bin/uwsgi(uwsgi_segfault+0x21) [0x46bcc1] /lib64/libc.so.6(+0x34940) [0x7fb169878940] /home/pw/venv/lib64/python3.4/lib-dynload/_ssl.cpython-34m.so(+0xb2aa) [0x7fb1661542aa] /home/pw/venv/lib64/python3.4/lib-dynload/_ssl.cpython-34m.so(+0xcd0f) [0x7fb166155d0f] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalFrameEx+0x413c) [0x7fb169f1673c] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalCodeEx+0x619) [0x7fb169f1c3b9] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalFrameEx+0x3a36) [0x7fb169f16036] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalFrameEx+0x3fe5) [0x7fb169f165e5] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalCodeEx+0x619) [0x7fb169f1c3b9] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalFrameEx+0x3a36) [0x7fb169f16036] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalCodeEx+0x619) [0x7fb169f1c3b9] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalFrameEx+0x3a36) [0x7fb169f16036] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalCodeEx+0x619) [0x7fb169f1c3b9] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalFrameEx+0x3a36) [0x7fb169f16036] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalCodeEx+0x619) [0x7fb169f1c3b9] /usr/lib64/libpython3.4m.so.1.0(+0xd7854) [0x7fb169ef7854] /usr/lib64/libpython3.4m.so.1.0(PyObject_Call+0x4a) [0x7fb169ef2eca] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalFrameEx+0x2364) [0x7fb169f14964] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalCodeEx+0x2b0) [0x7fb169f1c050] /usr/lib64/libpython3.4m.so.1.0(+0xd7854) [0x7fb169ef7854] /usr/lib64/libpython3.4m.so.1.0(PyObject_Call+0x4a) [0x7fb169ef2eca] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalFrameEx+0x2364) [0x7fb169f14964] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalCodeEx+0x619) [0x7fb169f1c3b9] /usr/lib64/libpython3.4m.so.1.0(+0xd7854) [0x7fb169ef7854] /usr/lib64/libpython3.4m.so.1.0(PyObject_Call+0x4a) [0x7fb169ef2eca] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalFrameEx+0x2364) [0x7fb169f14964] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalCodeEx+0x2b0) [0x7fb169f1c050] /usr/lib64/libpython3.4m.so.1.0(+0xd7854) [0x7fb169ef7854] /usr/lib64/libpython3.4m.so.1.0(PyObject_Call+0x4a) [0x7fb169ef2eca] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalFrameEx+0x2364) [0x7fb169f14964] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalCodeEx+0x619) [0x7fb169f1c3b9] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalFrameEx+0x3a36) [0x7fb169f16036] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalFrameEx+0x3fe5) [0x7fb169f165e5] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalFrameEx+0x3fe5) [0x7fb169f165e5] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalFrameEx+0x3fe5) [0x7fb169f165e5] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalCodeEx+0x2b0) [0x7fb169f1c050] /usr/lib64/libpython3.4m.so.1.0(+0xd7854) [0x7fb169ef7854] /usr/lib64/libpython3.4m.so.1.0(PyObject_Call+0x4a) [0x7fb169ef2eca] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalFrameEx+0x2364) [0x7fb169f14964] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalCodeEx+0x619) [0x7fb169f1c3b9] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalFrameEx+0x3a36) [0x7fb169f16036] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalCodeEx+0x619) [0x7fb169f1c3b9] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalFrameEx+0x3a36) [0x7fb169f16036] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalCodeEx+0x619) [0x7fb169f1c3b9] /usr/lib64/libpython3.4m.so.1.0(+0xd7854) [0x7fb169ef7854] /usr/lib64/libpython3.4m.so.1.0(PyObject_Call+0x4a) [0x7fb169ef2eca] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalFrameEx+0x2364) [0x7fb169f14964] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalCodeEx+0x619) [0x7fb169f1c3b9] /usr/lib64/libpython3.4m.so.1.0(+0xd7854) [0x7fb169ef7854] /usr/lib64/libpython3.4m.so.1.0(PyObject_Call+0x4a) [0x7fb169ef2eca] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalFrameEx+0x2364) [0x7fb169f14964] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalFrameEx+0x3fe5) [0x7fb169f165e5] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalCodeEx+0x619) [0x7fb169f1c3b9] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalFrameEx+0x3a36) [0x7fb169f16036] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalCodeEx+0x2b0) [0x7fb169f1c050] /usr/lib64/libpython3.4m.so.1.0(+0xd75c8) [0x7fb169ef75c8] /usr/lib64/libpython3.4m.so.1.0(PyObject_Call+0x4a) [0x7fb169ef2eca] /usr/lib64/libpython3.4m.so.1.0(+0xd431a) [0x7fb169ef431a] /usr/lib64/libpython3.4m.so.1.0(PyObject_Call+0x4a) [0x7fb169ef2eca] /usr/lib64/libpython3.4m.so.1.0(+0x7d09a) [0x7fb169e9d09a] /usr/lib64/libpython3.4m.so.1.0(PyObject_Call+0x4a) [0x7fb169ef2eca] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalFrameEx+0x3ea8) [0x7fb169f164a8] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalCodeEx+0x619) [0x7fb169f1c3b9] *** end … -
Django RestFrameWork Post Request without csrf exempt
I am a newbie to django/django-rest-framework. I am experimenting with React for the frontend and Django-rest-framework for the backend. The client and server are on different domains. I was able to make a GET request, for POST request I also manage to do it but only with the csrf_exempt decorator, which is not ideally. The django documentation recommended me to use CSRF_TRUSTED_ORIGINS to avoid csrf verification but that also doesn't work for me. Here's my settings.py INSTALLED_APPS = [ 'api.apps.ApiConfig', 'rest_framework', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_WHITELIST = ( 'localhost:3000', ) CSRF_TRUSTED_ORIGINS = [ 'localhost:3000' ] Should I start implementing jwt-authentication to avoid this situation ? What is the best approach to this problem?