Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reliably accessing request.user in Django custom LoginView
I have a custom LoginView and I'd like to take the shopping cart of a LazyUser pre-login and consolidate it with the cart of the user after login: class LoginView(FormView): ... def form_valid(self, form): request_user = self.request.user user = authenticate(email=form.cleaned_data['email'], password=form.cleaned_data['password']) if user is not None: login(self.request, user) try: user.consolidate_carts(request_user) except Exception as e: print('error in consolidate_carts: ', e) return HttpResponseRedirect(self.success_url) else: return render(self.request, 'users/login.html') This seems to work some of the time, but it is unreliable - I believe that is because I am simply referencing self.request.user and it is a SimpleLazyObject. What would be the pythonic/optimal way to store the user pre-login? -
Can not deserialize instance of io.vavr.collection.Seq out of VALUE_STRING
I was trying to build a python request module passing API tokens, however I am running into below issue every time. Sharing my entire code : import requests import json def bitbucketFunction(): variables = {"test":"1234"} callBitBucketAPI(variables) def callBitBucketAPI(variables): try: headers = { 'Content-Type': 'application/json' } url = "https:xyz/pipelines/" data = { "target": { "type": "pipeline_ref_target", "ref_type": "branch", "ref_name": "master", "selector": { "type": "custom", "pattern": "create-aws-account" } },"variables":json.dumps(variables, indent=2)} response = requests.request("POST",url, auth=('token-key', 'token-value'), data=json.dumps(data),headers=headers) print(response.text) except Exception as e: print("Exception occured in callBitBucketAPI method: ", e) bitbucketFunction() Error: {"error": {"message": "An invalid field was found in the JSON payload.", "fields": ["variables"], "detail": "Can not deserialize instance of io.vavr.collection.Seq out of VALUE_STRING token\n at [Source: (org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream); line: 1, column: 167] (through reference chain: com.atlassian.pipelines.rest.model.v1.pipeline.ImmutablePipelineModel$Builder[\"variables\"])", "data": {"key": "rest-service.request.invalid-json"}}} -
Django: I need to supersede a particular Python module in a no-longer-maintained package
Well, I think that the "Pinax" package is no longer maintained ... Anyway, it refers to a now-deprecated django.utils.tzinfo package. I need to make a one-line change to one source module, and then cause that version of the package to be loaded instead of the one in the module directory. Is there a generic way in Django to do that sort of thing? (I know that some packages such as the Machina forum software can do this.) -
djago-gis: Can't serialize dictionary with GeoFeatureModelSerializer: KeyError: 'id', even with .is_valid=True and excluding id
I'm trying to prototype a view receiving some geojson. I'm using a jupyter notebook, with (https://gist.github.com/codingforentrepreneurs/76e570d759f83d690bf36a8a8fa4cfbe)[the init_django script in this link). Trying to serialize this geojson (that has been transformed into a dict) {'id': '0', 'type': 'Feature', 'properties': {'area': 0.74, 'gloc1': sensitive, 'gloc2': sensitive, 'gloc3': sensitive, 'gloc4': sensitive, 'gloc5': sensitive}, 'geometry': {'type': 'MultiPolygon', 'coordinates': [some_coordinates]}} Is giving me problems with some id field. Here is the model serializer using the rest_framework_gis library. class Local(GeoFeatureModelSerializer): # cliente = PrimaryKeyRelatedField(queryset=ClienteModel.objects.all()) class Meta: model = LocalModel fields = "__all__" geo_field = "geom" Here is the model i'm using from django.contrib.gis.db.models import Model class Local(Model): status_choice = TextChoices('status', 'ATIVO INATIVO PONTUAL') gloc1 = TextField(null=False) gloc2 = TextField(null=False) gloc3 = TextField(null=False) gloc4 = TextField(null=False) gloc5 = TextField(null=False) latitude = FloatField(null=True, blank=True) longitude = FloatField(null=True, blank=True) altimetria = FloatField(null=True, blank=True) capacidade_retencao_agua = FloatField(null=True, blank=True) coef_textura_agua_solo = FloatField(null=True, blank=True) coef_potencia_agua_solo = FloatField(null=True, blank=True) sk1m = FloatField(null=True, blank=True, default=0) sk2m = FloatField(null=True, blank=True, default=1) smaw = FloatField(null=True, blank=True, default=0) sfer = FloatField(null=True, blank=True, default=1) profundidade_efetiva_maxima = FloatField(null=True, blank=True) cti = FloatField(null=True, blank=True) slo = FloatField(null=True, blank=True) geom = GeometryField(srid=4326, null=False) data_criacao = DateField(auto_now=True) data_atualizacao = DateField(auto_now_add=True) #null-False here cena_s2 = TextField(null=True, blank=True) area = FloatField(null=True, blank=True) grupo = … -
CKEditor RichTextUploadingWidget preventing page scroll
I'm using a fullpage.js frontend with a Django backend. In the Django models, I defined some fields with the RichTextUploadingField. The fullPage.js page does not work with scrolloverflow if I do this. I cannot scroll down to the next page. If I change the RichTextUploadingField back to a normal TextField everything works fine. Any ideas? -
Django/Apache authentication successful but does not return @loginrequired view instead redirects to index
I have a Django application with token-based auth. I served this app on AWS before without problem. Now I want to serve it via Apache2 but it fails to open a 'login required' page after successful login. Here is my code: views.py def index(request): print('Access to page "home"') return render(request, 'index.html') @login_required(login_url='/') def memory(request): print('Access to page "memory"') return render(request, 'memory.html') user_api.py @api_view(["POST"]) @permission_classes((AllowAny,)) @csrf_exempt def doLogin(request): body_unicode = request.body.decode('utf-8') user = json.loads(body_unicode) dbUser = User.objects.filter(username=user['username']) if not dbUser: return HttpResponse(status=404) authenticatedUser = authenticate(username=user['username'], password=user['password']) if authenticatedUser: login(request, authenticatedUser) token, _ = Token.objects.get_or_create(user=authenticatedUser) return Response({'token': token.key}, status=HTTP_200_OK) else: return Response(status=401) LoginModal.vue login() { if (!this.user.username || this.user.username == '' || !this.user.password || this.user.password == '') { this.warningText = 'All fields must be filled.' return } axios.post(this.backendAddress + 'api/user/login', this.user) .then((response) => { sessionStorage.setItem('token', response.data.token) document.cookie = 'apitoken=' + response.data.token window.location.href = 'memory' }, function (err) { printError(err) }) } After I entered my username/password and hit login, it makes the request and redirects to index with ?next=memory, meaning that it doesn't recognized user as logged in. After successfull login I store my token as 'apitoken' parameter in the cookie. What's wrong with my method? Thanks. -
django form not showing in template to add data
the goal of my code is to make a school management system where the admin can log in and add teachers to their respective classes that they are leading and be able to add students to their respective classes and then take the attendance of those students present on any given day. however, I am having an issue where the form to add the student to the class isn't rendering when I click on the add student button. I have been searching but can't seem to find the error in my code, I am new to Django so any help will be appreciated. the closest I got was to make the modal show up but the fields to select the student from to add to the class wasn't showing models class Teacher(models.Model): first_name = models.CharField(max_length=60, blank=False, null=False) last_name = models.CharField(max_length=80, blank=False, null=False) address = models.CharField(max_length=120, blank=True, null=True) contact = models.CharField(max_length=10, blank=True, null=True) email = models.EmailField(blank=True, null=True) birth = models.CharField(max_length=20, blank=True, null=True) gender = models.CharField(max_length=100, choices=[('Male', 'Male'), ('Female', 'Female')], blank=True, null=True) comment = models.TextField(max_length=10000, blank=True, null=True) def __str__(self): return f"{self.first_name + ' ' + self.last_name}" class Student(models.Model): student_code = models.CharField(max_length=250, blank=True, null=True) first_name = models.CharField(max_length=20, blank=False, null=False) last_name = models.CharField(max_length=20, blank=False, … -
Django way to make a chat app without django-channels
how can I make a chat app without django-channels. I want to do it with something like socketio. I found in Google a module named django-socketio. Should I do it with this? Please write me the code to do this or write a link of a tutorial. Should I do it with something different? Thanks. -
Can't connect with my django rest framework API with axios in react native
I'm developing an application with React Native and I can't connect to my own API. I made a database with django rest framework and I'm trying to connect to it with axios. I'm receiving an error with "Network Error" message with the name "AxiosError". Here is the error (with error.toJSON()): Object { "code": "ERR_NETWORK", "columnNumber": undefined, "config": Object { "adapter": [Function xhrAdapter], "data": undefined, "env": Object { "FormData": null, }, "headers": Object { "Accept": "application/json, text/plain, /", }, "maxBodyLength": -1, "maxContentLength": -1, "method": "get", "timeout": 0, "transformRequest": Array [ [Function transformRequest], ], "transformResponse": Array [ [Function transformResponse], ], "transitional": Object { "clarifyTimeoutError": false, "forcedJSONParsing": true, "silentJSONParsing": true, }, "url": "http://127.0.0.1:8000/api/usuario", "validateStatus": [Function validateStatus], "withCredentials": false, "xsrfCookieName": "XSRF-TOKEN", "xsrfHeaderName": "X-XSRF-TOKEN", }, "description": undefined, "fileName": undefined, "lineNumber": undefined, "message": "Network Error", "name": "AxiosError", "number": undefined, "stack": undefined, "status": null, } Currently I'm doing it without authentification needed because i thought I should have less errores (tried it also with authentification earlier a lot and same error). This is my axios function: try { const axios = require('axios'); const students = await axios.get('http://127.0.0.1:8000/api/usuario', {withCredentials: false}); //const students = await axios.get('https://jsonplaceholder.typicode.com/todos/1'); setPrueba(JSON.stringify(students.data)); The line commented is a API that gives a placeholder json, and … -
mod_wsgi: "No module named 'django'"
Maybe some needed context: I installed python3.9 into a directory /opt/python39/. I compiled mod_wsgi with this version of python and was able to conduct a test to make sure that it was working correctly. I am not using a virtual environment. I am trying to move my django project to production, so naturally, I am following the django docs. When I use the default file configurations at the very beginning, i.e.: WSGIScriptAlias / /path/to/mysite.com/mysite/wsgi.py WSGIPythonHome /opt/python39/bin/python3.9 WSGIPythonPath /path/to/mysite.com <Directory /path/to/mysite.com/mysite> <Files wsgi.py> Require all granted </Files> </Directory> It works (for the most part - there are resources missing on the page, but thats for another SO post) like a charm. So I continue through the docs (which is now telling me that I should move it to "Daemon mode"): “Daemon mode” is the recommended mode for running mod_wsgi (on non-Windows platforms). To create the required daemon process group and delegate the Django instance to run in it, you will need to add appropriate WSGIDaemonProcess and WSGIProcessGroup directives. A further change required to the above configuration if you use daemon mode is that you can’t use WSGIPythonPath; instead you should use the python-path option to WSGIDaemonProcess, for example: So I change … -
How can I get Django to send error emails on status codes above 500?
I have migrated an old codebase to a new server and am now running Django 4.0.5. I can send emails from the shell as follows: from django.core.mail import mail_admins mail_admins(subject='test', message='test') But I don't receive any emails on 500 or higher errors. My settings are: DEBUG = env('DEBUG') ADMINS = [('My Name', 'me@provider.com'),] MANAGERS = ADMINS ADMIN_EMAIL = ['me@provider.com',] DEFAULT_FROM_EMAIL = 'admin@provider.com' SERVER_EMAIL = 'admin@provider.com' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'admin@provider.com' EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD') EMAIL_USE_TLS = True And i have tried adding: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' But they are still not sent. I am using django-environ, but debug is set to false. Any ideas what the problem could be? -
Django celery error while adding tasks to RabbitMQ message queue : AttributeError: 'ChannelPromise' object has no attribute '__value__'
I have setup celery, rabbitmq and django web server on digitalocean. RabbitMQ runs on another server where my Django app is not running. When I am trying to add the tasks to the queue using delay I am getting an error AttributeError: 'ChannelPromise' object has no attribute 'value' From django shell I am adding the task to my message queue. python3 manage.py shell Python 3.8.10 (default, Mar 15 2022, 12:22:08) [GCC 9.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from app1.tasks import add >>> add.delay(5, 6) But getting error Traceback (most recent call last): File "/etc/myprojectenv/lib/python3.8/site-packages/kombu/utils/functional.py", line 30, in __call__ return self.__value__ AttributeError: 'ChannelPromise' object has no attribute '__value__' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/etc/myprojectenv/lib/python3.8/site-packages/kombu/connection.py", line 446, in _reraise_as_library_errors yield File "/etc/myprojectenv/lib/python3.8/site-packages/kombu/connection.py", line 433, in _ensure_connection return retry_over_time( File "/etc/myprojectenv/lib/python3.8/site-packages/kombu/utils/functional.py", line 312, in retry_over_time return fun(*args, **kwargs) File "/etc/myprojectenv/lib/python3.8/site-packages/kombu/connection.py", line 877, in _connection_factory self._connection = self._establish_connection() File "/etc/myprojectenv/lib/python3.8/site-packages/kombu/connection.py", line 812, in _establish_connection conn = self.transport.establish_connection() File "/etc/myprojectenv/lib/python3.8/site-packages/kombu/transport/pyamqp.py", line 201, in establish_connection conn.connect() File "/etc/myprojectenv/lib/python3.8/site-packages/amqp/connection.py", line 323, in connect self.transport.connect() File "/etc/myprojectenv/lib/python3.8/site-packages/amqp/transport.py", line 129, in connect self._connect(self.host, self.port, self.connect_timeout) File "/etc/myprojectenv/lib/python3.8/site-packages/amqp/transport.py", line 184, in _connect … -
Django: create many-to-Many relationship without creating intermediary table
I have a set of tables that Ive turned into django models. The tables weren't architected very well and i can't change them, and it is causing problems for this one many to many relationship I'm trying to set up in my code. Models class Owner(models.Model): owner_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, unique=True) # Field name made lowercase. email = models.TextField(max_length=200, unique=True) is_active = models.BooleanField( blank=True, null=True) # Field name made lowercase. owned_apps_whistic = models.ManyToManyField("Applications", through="ApplicationOwnerXRef", related_name="owners_whistic") #owned_apps_group = models.ManyToManyField("Applications", through="BusinessUnitOwnerXref", related_name="owners_group") class Applications(models.Model): application_id = models.UUIDField(primary_key=True) url = models.TextField(blank=True, null=True) name = models.TextField(blank=True, null=True) service = models.TextField(blank=True, null=True) status = models.TextField(blank=True, null=True) created_date = models.TextField(blank=True, null=True) description = models.TextField(blank=True, null=True) business_unit_name = models.TextField(blank=True, null=True) class BusinessUnitOwnerXref(models.Model): id = models.AutoField(primary_key=True) owner_uuid = models.ForeignKey(ApplicationOwner, models.DO_NOTHING, to_field="owner_uuid", db_column = "owner_uuid") business_unit_name = models.TextField(max_length=100, null=True) Owners can own applications by owning the group that owns the application, indicated in the BusinessUnitOwnerXref table. The Application table and the BusinessUnitOwnerXref both have the business_unit_name column , and can be directly joined I cant use a foreign key because the BusinessUnitOwnerXref.business_unit_name column isn't unique. TLDR, Is there a way to create the many-to-many relationship between Applications and Owners, through BusinessUnitOwnerXref, without altering the existing tables or letting django … -
How to install python packages on shared host
When I upload my Django app, I have problem when I setup the python app configuration files. After adding requirements.txt gives me an error these libraries are not accepted: matplotlib==3.5.1 pandas==1.3.5 Pillow==9.0.0 psycopg2==2.9.1 scipy==1.7.3 seaborn==0.11.2 Is there a solution? -
"Bot domain invalid" error in web telegram login. Django
When integrating the login via telegram for Django, I received the following error (despite the fact that all actions were done correctly) Bot domain invalid error I've been tinkering with this for a couple of days and just want to share a solution. The solution is simple and pretty funny. Just remove "django.middleware.security.SecurityMiddleware" from MIDDLEWARE -
getting dynamic data from views to javascript
Just like we can set a context variable for the default users in a django template, var user = "{{request.user}}" How do I do the same thing for a custom Model? views def test(request): news = News.objects.all() context = {"news ": news} template <script> var text = "{{request.news}}"; </script> -
Is it possible to take in input from django, and output that to a word document using python docx
I want to take in user input through text boxes on websites created with Django. After gathering the user input I want to automatically generate a word document with the inputs, and output a word document. Is this possible? -
django error : 'the current database router prevents this relation.'
I have 2 models(customer, order) in 2 different sqlite3 databases(custdb and orddb) apart from the default database. Settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'custdb': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'custdb.sqlite3', }, 'orddb': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'orddb.sqlite3', } } DATABASE_ROUTERS = ['customer.router.custrouter', 'order.router.ordrouter'] Under 'customer' App, in the models.py, below customer model class is defined(only class definition shown here) class customer(models.Model): name = models.CharField(max_length=50) phone = models.IntegerField() Under order App, in the models.py, below order model is defined(only class definition shown here) class order(models.Model): ordername = models.CharField(max_length=50) customer = models.ForeignKey(cust, default=None, null=True, on_delete = models.SET_NULL) Under 'customer' App, in the router.py, I have defined one router class class custrouter: route_app_labels = {'customer'} def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'custdb' return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'custdb' return None def allow_relations(self, obj1, obj2, **hints): if ( obj1.meta.app_label in self.route_app_labels or obj2.meta.app_label in self.route_app_labels ): return True return True def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return db == 'custdb' return None Under 'order' App, in the router.py, I have defined another router class class ordrouter: route_app_labels = {'order', 'customer'} def … -
Django service only works when the image is deleted and pulled again (in Swarm)
I have a swarm cluster with 2 workers and one manager. I built a Django image, pushed it to Docker Hub. I make migrations before pushing the image so it contains them. I pull the image for it to be used for the Swarm services, using docker-compose, I deploy the stack, everything works. But if I remove the stack and try to start it again from the old image (which should be immutable) i get psycopg2.OperationalError: could not translate host name "db" to address: Name or service not known. If I delete the image and just run the stack again (so basically I get the same image from Docker Hub) the service is deployed without any errors. So i cant delete the stack and use the same image to deploy it again.. My compose is: version: "3.3" services: web: image: x command: > bash -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" env_file: - .env.dev volumes: - migrations-volume:/stack_name/api/migrations/ deploy: replicas: 3 restart_policy: condition: on-failure networks: - web_network - data_network secrets: - firebase_secret - google_cloud_secret healthcheck: test: wget --tries=1 --spider http://localhost:8000/app/ || exit 1 interval: 180s retries: 5 timeout: 10s db: image: postgres:11 command: "-c logging_collector=on" volumes: - database:/var/lib/postgresql/database/ env_file: … -
Django How to make a chat app without django-channrls
Hello how can I make a chat app without django-channels. I want to do it with something like socketio. I found in Google a module named django-socketio. Should I do it with this? Please write me the code to do this or write a link of a tutorial. -
Django REST Framework: Strange behaviour in unit tests
Good evening, at the moment I'm creating the unit tests for a pretty basic model in combination with the authentification of a json web token. Also I'm using a custom user model. Notice: a few lines of code will be cut off for a better overview - there unimportant for my question. models.py: USER = get_user_model() class MainTask(models.Model): id = models.BigAutoField(primary_key=True, unique=True) title = models.CharField(max_length=50, null=False, blank=False, unique=True) active = models.BooleanField(default=True) slug = models.SlugField(null=False, blank=False, unique=True) created_by = models.ForeignKey(USER, null=False, blank=False, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) views.py: class MainTaskListCreateView(ListCreateAPIView): queryset = MainTask.objects.all() serializer_class = MainTaskSerializer pagination_class = PageNumberPagination urls.py: urlpatterns = [ path('maintask/', MainTaskListCreateView.as_view(), name='maintask-list'), path('token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'), ] settings.py: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAdminUser', 'rest_framework.permissions.IsAuthenticated', ], } test_views.py: USER = get_user_model() class MainTaskTest(APITestCase): url_verification = reverse('token_obtain_pair') url_maintasks = reverse('maintask-list') def setUp(self): self.email = 'johndoe@email.com' self.password = 'johndoepassword' self.data = { 'email': self.email, 'password': self.password } USER.objects.create_user(email=self.email, password=self.password) def test_auth_user(self): response = self.client.post(self.url_verification, self.data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertTrue('access' in response.data) self.assertTrue('refresh' in response.data) def test_get_obj(self): response_verification = self.client.post(self.url_verification, self.data, format='json') token = response_verification.data['access'] self.client.credentials(HTTP_AUTHORIZATION=f"JWT {token}") response = self.client.get(self.url_maintasks, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertNotEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) self.assertNotEqual(response.status_code, status.HTTP_403_FORBIDDEN) Problem: When running the test above, I get an error 403, the … -
TwilloRestfullException on inbound call in django_two_factor_auth
I am using django_two_factor_auth version 1.13.1 with python 3.6, and when I try to get OTP via phone call it returns TwilloRestfullExeption on URL. HTTP 400 error: Unable to create a record: Url is not a valid URL: http://localhost:8000/twilio/inbound/two_factor/206039/?locale=en in my URLS.py I have added the URLs paths url('', include(tf_urls)), url('', include(tf_twilio_urls)), one more thing when I try to hit that URL via postman or web browser I got 200 success response <?xml version="1.0" encoding="UTF-8" ?> <Response> <Say language="en">Your token is 1. 7. 3. 8. 4. 7. Repeat: 1. 7. 3. 8. 4. 7. Good bye.</Say> </Response> -
wagtail api : my pages dont appear in /api/cms/pages/
I ve configured my wagtail to use the api and to serve the pages on /api/cms/pages/ endpoint. But I only have the default page being served on this endpoint : "meta": { "total_count": 1 }, "items": [ { "id": 2, "meta": { "type": "wagtailcore.Page", "detail_url": "http://localhost/api/cms/pages/2/", "html_url": "http://localhost/", "slug": "home", "first_published_at": null }, "title": "Welcome to your new Wagtail site!" } ] } I have created a few BlogPages and PostPages but they dont appear there. How can i configure my django/wagtail files so they appear? The documentation here : https://docs.wagtail.org/en/stable/advanced_topics/api/v2/usage.html is not very detailed... Here is my models.py : import urllib.parse from django.http.response import JsonResponse, HttpResponseRedirect from django.conf import settings from django.db import models from django.utils.module_loading import import_string from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from modelcluster.fields import ParentalKey from modelcluster.tags import ClusterTaggableManager from taggit.models import Tag as TaggitTag from taggit.models import TaggedItemBase from wagtail.admin.edit_handlers import ( FieldPanel, FieldRowPanel, InlinePanel, MultiFieldPanel, PageChooserPanel, StreamFieldPanel, ) from wagtail.core.models import Page from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.snippets.edit_handlers import SnippetChooserPanel from wagtail.snippets.models import register_snippet from wagtail.core.fields import StreamField from wagtail.contrib.routable_page.models import RoutablePageMixin, route from wagtail.search import index from wagtail_headless_preview.models import HeadlessPreviewMixin from .blocks import BodyBlock from wagtail.api import APIField from .fields import TagField, CategoryField, … -
{detail: Unsupported media type "text/plain; charset=utf-8" in request.}
I am using Flutter and Django and have this error when try to call the backend Back end error : {detail: Unsupported media type "text/plain; charset=utf-8" in request.} Flutter code : Future<void> addAlbum(Album album) async { print('5'); final url = Uri.parse('http://127.0.0.1:8000/list-create/'); try { print('6'); final response = await http.post(url, headers: { 'Authorization': 'Token dc7e96ed776bc44d013b44fdfe560a616c64646f', }, body: json.encode({ 'title': album.title, 'cover': album.cover, // => this is an int 'photos_number': album.photos_number, // => this is an int })); print('6 ed'); final responseData = json.decode(response.body); print(responseData.toString()); final newAlbum = Album( title: album.title, cover: album.cover, photos_number: album.photos_number, ); print('6 edddgg'); _items.add(newAlbum); print('6 f'); notifyListeners(); } catch (error) { print('7'); print(error); throw error; } } } -
Django API call from extern Website via AJAX Javascript
i am working for the first time with Django Framework. A service provider is using django i can see the data only with an active Cookie on their API Docs. We received now an API Token to call for the data on the framework. I am trying to call the data with the Token via AJAX but i receive everytime the same console log "401 (Unauthorized)". $.ajax({ type: 'POST', headers: { 'X-CSRFTOKEN': "XXXXXXXXXXXXXXX", 'Content-Type': 'application/json' }, url: 'www.service-provider.url/api/...', success: function () { console.log("ok"); }, error: function () { console.log("error"); } }); Sorry i'm a beginner at this point and have no idea where to begin with. I've searched for solution on the inet but couldn't find anything that would work.