Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Coverage is showing different for full pytest and single app in django using pytest
I have created a project in Django, and I'm writting testcases in pytest. Now, to use coverage I generally use cmd coverage run -m pytest. And to check coverage for specific app, i report/create html files with coverage html , so this will create html files with red and green markers. Recently, I am experementing with different combinations of configurations of coverage and pytest, and found that when run full pytest with coverage like coverage run -m pytest it will not cover all lines, and mark some lines as missing which is actually running while pytest. But when I use pytest with some argument with coverage like coverage run -m pytest accounts , it is covering all perfectly and not showing missing file as I expected. I have tried running whole project with coverage run -m pytest and then run coverage html to see in browser. I got all file's coverage, and to see coverage of specific app for example restaurant , i searched in top right search box and its showing as below. Full Pytest Coverage Full pytest coverage with searched result Now, I have to run coverage for specific app so i can do it like coverage run … -
Trying to run a app in vs code in ubuntu using django, and getting connection error at / (newbie here)
made a app and project using django in vs code and used the covid9api also i am using ubuntu in oracle vm ConnectionError at / HTTPSConnectionPool(host='api.covid9api.com', port=443): Max retries exceeded with url: /countries (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f306d7cca90>: Failed to establish a new connection: [Errno -2] Name or service not known')) Request Method: GET Request URL: http://127.0.0.1:6000/ Django Version: 4.1.4 Exception Type: ConnectionError Exception Value: HTTPSConnectionPool(host='api.covid9api.com', port=443): Max retries exceeded with url: /countries (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f306d7cca90>: Failed to establish a new connection: [Errno -2] Name or service not known')) Exception Location: /usr/lib/python3/dist-packages/requests/adapters.py, line 516, in send Raised during: newapp.views.home Python Executable: /usr/bin/python3 Python Version: 3.10.6 Python Path: ['/home/void/python/newproject/sports', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/home/void/.local/lib/python3.10/site-packages', '/usr/local/lib/python3.10/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Mon, 19 Dec 2022 07:16:23 +0000 [this is the error](https://i.stack.imgur.com/yNWHs.png) -
how to successfully start the server in django?
Whenever I put the command "python manage.py runserver" it through an error. from django.utils.encoding import python_2_unicode_compatible ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding' (C:\JavaScript\DR_BRO\backend\venv\Lib\site-packages\django\utils\encoding.py) I was trying to run the server in Django. But it's thorough an error like from django.utils.encoding import python_2_unicode_compatible ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding' (C:\JavaScript\DR_BRO\backend\venv\Lib\site-packages\django\utils\encoding.py) -
Django is asking to delete column, which does not even exists
I tried applying migrations, but django ask me to delete a column which does not exist. Please help The error which i get is - OperationalError at /admin/location/location/ (1054, "Unknown column 'location_location.id' in 'field list'") models.py class Location(models.Model): city = models.CharField(max_length=255) state = models.CharField(max_length=255) country = models.CharField(max_length=255) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) views.py def add_location(request): if request.method == 'POST': form = LocationForm(request.POST) if form.is_valid(): form.save() return redirect('/') else: form = LocationForm() return render(request, 'add_location.html', {'form': form}) admin.py from django.contrib import admin from .models import Location # Register your models here. admin.site.register(Location) I tried using migrations --fake but it made it even worse. Please help me out. this is urgent :( -
cfnbootstrap.construction_errors.ToolError: Command 01_migrate failed on Amazon Linux 2
I am trying to upload my project on AWS and while deploying it via ElasticBeanStalk I get the follwing error: cfnbootstrap.construction_errors.ToolError: Command 01_migrate failed The project was already deployed on AWS and is working without any problem, there are no changes in .ebextensions files as well db-migrate.config: container_commands: 01_migrate: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate" leader_only: true Error stack: 2022-12-19 06:16:50,685 [INFO] Running configSets: Infra-EmbeddedPostBuild 2022-12-19 06:16:50,688 [INFO] Running configSet Infra-EmbeddedPostBuild 2022-12-19 06:16:50,691 [INFO] Running config postbuild_0_Trakkia_al2 2022-12-19 06:16:53,613 [ERROR] Command 01_migrate (source /var/app/venv/*/bin/activate && python3 manage.py migrate) failed 2022-12-19 06:16:53,614 [ERROR] Error encountered during build of postbuild_0_Trakkia_al2: Command 01_migrate failed Traceback (most recent call last): File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 576, in run_config CloudFormationCarpenter(config, self._auth_config).build(worklog) File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 276, in build self._config.commands) File "/usr/lib/python3.7/site-packages/cfnbootstrap/command_tool.py", line 127, in apply raise ToolError(u"Command %s failed" % name) cfnbootstrap.construction_errors.ToolError: Command 01_migrate failed 2022-12-19 06:16:53,617 [ERROR] -----------------------BUILD FAILED!------------------------ 2022-12-19 06:16:53,617 [ERROR] Unhandled exception during build: Command 01_migrate failed Traceback (most recent call last): File "/opt/aws/bin/cfn-init", line 176, in <module> worklog.build(metadata, configSets) File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 137, in build Contractor(metadata).build(configSets, self) File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 564, in build self.run_config(config, worklog) File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 576, in run_config CloudFormationCarpenter(config, self._auth_config).build(worklog) File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 276, in build self._config.commands) File "/usr/lib/python3.7/site-packages/cfnbootstrap/command_tool.py", line … -
Hello Please Help Me. I cannot change my company
here is my view please help me # VIEWING THE TABLE def display_companies (request): items = Paginator(Companies.objects.all(),10) page = request.GET.get('page') items = items.get_page(page) nums = "a" * items.paginator.num_pages context = { 'items' : items, 'header' : 'Tashkilotlarni', 'nums' : nums } return render (request, 'home.html', context) # CHANGING THE COMPANY def change_company(request,pk): item = get_object_or_404(Companies, pk=pk) form = CompaniesForm(instance=item) if request.method == "POST": form = CompaniesForm(request.POST, instance=item) if form.is_valid(): form.save() return redirect('display_companies') return render(request, 'change_company.html', {'form':form}) HERE IS MY HTML DOCUMENT {% extends 'base.html' %} {% block content %} <div class="container"> <form method="POST"> {% csrf_token %} {% for field in form %} <div class="form-group row"> <label for="id_{{field.STIR}}" class="col-2 col-form-label">{{ field.label }}</label> <div class="col-10"> {{ field }} </div> </div> {% endfor %} <button type="submit" class="btn btn-outline-primary" name="button">O'zgartirish</button> </form> </div> {% endblock %} i click on change company button but nothing changes it renders me to my form not to my home.html page PLEASE HELP ME GUYS. TY VERY MUCH. -
How to make column appear when condition satisfied in jinja2 templating
I have a table, where some column are condition specific. I want if the condition is satisfied only then show the column, otherwise, remove the column. How can i do that with jinja2 templating? -
how to take average of every 10 minutes of a model django
I am using multiple APIs and save them to the database. I have one model called Station(it has datetime field and some other fields ) and every API is for one station. these APIs come from devices that measure some variables and they get updated every 3 minutes. so I wrote a backend task that calls a saveToDB function and stores them in database. for example: station A "some variables" 2022/10/1 13:10 station B "some variables" 2022/10/1 13:10 station A "some variables" 2022/10/1 13:13 station B "some variables" 2022/10/1 13:13 now I need to take average of every station every 10 minutes,2 hours,week, month, year. there are 30 stations. how can i do this? -
Multiple same requests in django rest class based view
I recently began using class-based views in the development of Django rest APIs. While discussing this with a friend, he inquired, "What if I have the same type of request multiple times in the same class?" because, as stated in the rest documentation, I created post functions for POST requests and get functions for GET requests. So, how to write two GET or other types of requests within the same class? -
How can I Deploy a Django App as a .war file or in any other packaged way?
I have a Django Project for which I am trying to find a way to deploy as a .war file. My objective is to not reveal the source code during deployment to De-Couple Django App from Database and deploy as a .war file. This will help me to update the app without re-initializing database. As Jython is not supported for Python3, is there an alternative? I also tried to create an exe through PyIntsaller but it acts as a malicious executable. -
Django crontab can’t connect database(Postgresql) with docker; no such table err
I am using django and postgresql. I am using django-crontab to change the data. It runs well in the local environment, but we use docker to deploy and watch, and I confirmed that when cron runs, we refer to sqlite3. I also made a separate cron container in docker composite and ran it, I am using it incorrectly because I am a beginner. Help me #goods/cron.py from goods.models import Goods def test(): print(Goods.objects.all()) ./docker-compose.yml version: '3.8' volumes: postgres: {} django_media: {} django_static: {} static_volume: {} services: postgres: container_name: postgres image: postgres:14.5 volumes: - postgres:/var/lib/postgresql/data/ environment: - POSTGRES_USER - POSTGRES_PASSWORD - POSTGRES_DB restart: always nginx: container_name: nginx image: nginx:1.23.2 ports: - "80:80" - "443:443" volumes: - ./nginx/default.conf:/etc/nginx/conf.d/default.conf - django_media:/media/ - django_static:/static/ depends_on: - asgiserver - backend restart: always django_backend:/app/media backend: host:container container_name: django_backend build: . entrypoint: sh -c "python manage.py migrate && gunicorn handsup.wsgi --workers=5 -b 0.0.0.0:8000" restart: always volumes: - ./:/app/ - /etc/localtime:/etc/localtime:ro - django_media:/app/media/ - django_static:/app/static/ environment: # - DEBUG - POSTGRES_DB - POSTGRES_USER - POSTGRES_PASSWORD - POSTGRES_HOST - POSTGRES_PORT depends_on: - postgres redis: image: redis:5 asgiserver: build: . command: daphne -b 0.0.0.0 -p 8080 handsup.asgi:application volumes: - ./:/app/ restart: always environment: - DEBUG - POSTGRES_DB - POSTGRES_USER - … -
what is the quickest way to style django model form fields one by one
I have ModelForm which renders successfully. this is my forms.py form class UploadPostsForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'description', 'date', 'file'] this is how it looks in templates I want it to look like below using bootstrap5 what is the fastest and easiest way to do it? I have found three ways. adding custom template tags defining styles in each form fields or all at once overriding __init__ method what is the best way to do this? -
Redirect after saving site setting
I'm trying to redirect the user to a custom HTML page after saving a BaseSiteSetting model in Wagtail 4.1.1 I'm not sure how to accomplish this, the BaseSiteSetting inherits from django models.Model which means it's possible to override the save() function but how would I do the actual redirect without having access to the request? Another acceptable solution would be to add an extra button in the CMS by overriding the default BaseSiteSetting HTML template but I can't seem to get that working either, except for ModelAdmin templates. I've opened a stackoverflow question about that here. My view with the custom HTML page: def sync(request): return render(request, "import.html", {"WS_PROTOCOL": settings.WS_PROTOCOL}) My BaseSiteSetting model: @register_setting class AnonymousSuccessStoryImportSetting(BaseSiteSetting): """ Setting for importing anonymous success stories. """ file = models.FileField( upload_to="success_story_imports/%Y/%m/%d/", validators=[validate_file_extension], help_text="Upload a CSV file, then click 'Save' afterwards", blank=True, null=True, ) date = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = "Importer" I've looked around for possible solutions, and found some wagtail hooks but these only apply to the Wagtail Page model, for example: after_publish_page. It's unfortunate that there's no hook for standard django models. -
How to set the queryset in forms.Form(ModelChoiceField) for Drop Down city List?
I have set a ForeignKey() for class Town in the models file. Ideally, when I select a state, all towns belonging to this state will be listed in town. #models.py class State(models.Model): state = models.CharField(max_length=50) code = models.CharField(max_length=3) def __str__(self): return self.state class Town(models.Model): town = models.CharField(max_length=50) code = models.CharField(max_length=4) state = models.ForeignKey(State, on_delete=models.CASCADE) def __str__(self): return self.town Now I can only use all() in queryset to display all towns. I feel like I should use filter(), but I can't find a way to do it。 #forms.py class Location(forms.Form): state = forms.ModelChoiceField( required = True, label = "State", queryset = State.objects.all(), widget = forms.Select(attrs = { "class": "form-list-field"} )) town = forms.ModelChoiceField( required = True, label = "Town", queryset = Town.objects.filter( ??? ).order_by('town'), widget = forms.Select(attrs = { "class": "form-list-field"} )) -
Trying to find a way to pass a list to an item in request.POST. How do I do it?
This is my html code in django project: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> {% load static %} <script src="{% static 'jquery-3.6.2.min.js' %}" ></script> </head> <body> <form action="{% url 'index' %}" method="post"> {% csrf_token %} <button id="button1" name="action" value="">button2</button> <script> $("#button1").click( function(){ arr = ["one", "two"] $("#button1").attr('value',arr) } ) </script> </form> </body> </html> By clicking the button I run JQuery that assigns an array: arr to button1's value. This is request.POST afterwards: <QueryDict: {'csrfmiddlewaretoken': ['Rws3PVVBVOGsoXm720M5YbuZNTYMin6CxklI78in2PWdrxAYKxw3XqV7cba2xt7P'], 'action': ['one,two']}> Instead of 'action': ['one,two'] I want to get 'action': ['one', 'two'], or 'action': [['one', 'two']] How do I do it? -
Why is Django's client.post nesting arg values in lists?
I'm unit testing my api with Django like this: result = self.client.post( reverse(path), { "arg1":"value" }) Inside the view, I breakpoint. @api_view(["POST"]) def post_arg(request): breakpoint() But when I print the POST data, the values have been added to lists. (Pdb) request.POST { 'arg1': ['value'] } This example only has one arg, but if I add more they are each added to a list. I don't think this happens when my frontend posts data, so why does it here? And is there a way to not have the values added to a list? -
telebot register_next_step_handler_by_chat_id not works in celery shared task
I have a small tg bot django project and the bot needs to send a message to users that have been inactive for over an hour and then wait for input from the user using tg_nick_or_phone_input_handler and write it to TelegramBotClientModel instance, sending more messages to chat def tg_nick_or_phone_input_handler(message): chat_id = message.chat.id bot_client = TelegramBotClientModel.objects.get(chat_id=chat_id) bot_client.phone_or_nickname = message.text bot_client.request_sent = True bot_client.save() bot.send_message( chat_id=chat_id, text='REQUEST SENT' ) bot.send_message( chat_id=chat_id, text='some message' ) import django.utils.timezone as tz from celery import shared_task from tg_funnel_bot.bot import bot from .views import tg_nick_or_phone_input_handler from .models import TelegramBotClientModel, BotMessagesSettingsModel # celery task where should register next step handler @shared_task(name='send_message_for_interrupted_dialog_after_one_hour') def send_message_for_interrupted_dialog_after_one_hour(): bot_messages_settings = BotMessagesSettingsModel.objects.all().first() inactive_for_hour_clients = TelegramBotClientModel.objects.filter( updated_at__lte=tz.now() - tz.timedelta(minutes=5), request_sent=False, message_for_one_hour_inactive_sent=False ) for inactive_client in inactive_for_hour_clients: chat_id = inactive_client.chat_id bot.send_message( chat_id=chat_id, text=bot_messages_settings.user_inactive_for_hour_message_text_first_part ) bot.send_message( chat_id=chat_id, text=bot_messages_settings.user_inactive_for_hour_message_text_second_part, reply_markup=bot_messages_settings.get_inactive_message_second_part_markup() ) bot.register_next_step_handler_by_chat_id( chat_id=chat_id, callback=tg_nick_or_phone_input_handler ) inactive_client = TelegramBotClientModel.objects.get(pk=inactive_client.pk) inactive_client.message_for_one_hour_inactive_sent = True inactive_client.save() return tz.now() bot.register_next_step_handler_by_chat_id not register handler and follow input in bot chat not processing. Maybe i cannot use bot instance in another processes, but i can send messages, so strange. Give me a hand please -
Django autogenerated models and relationships doesn't show up in model meta
I have the below code to create a Vote model for any given other model that I want to attach this relation to. from functools import lru_cache from django.contrib.auth import get_user_model from django.db import models from django.utils.translation import gettext_lazy as _ from apps.common.models.base import BaseModel from apps.common.utils import camel_to_snake @lru_cache(maxsize=None) def create_vote_class(klass): class Vote(BaseModel): class VoteType(models.IntegerChoices): UPVOTE = 1, _("Upvote") DOWNVOTE = -1, _("Downvote") user = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, related_name=f"{camel_to_snake(klass.__name__)}_votes", verbose_name=_("User"), help_text=_("The voter."), ) post = models.ForeignKey( klass, on_delete=models.CASCADE, related_name=f"{camel_to_snake(klass.__name__)}_votes", verbose_name=_("Post"), help_text=_("The post this vote is for."), ) body = models.IntegerField( choices=VoteType.choices, verbose_name=_("Body"), help_text=_("The actual vote. -1 or +1"), ) def type(self): return self.get_body_display() class Meta: abstract = True app_label = klass._meta.app_label # NOQA klass_name = f"{klass.__name__}Vote" bases = (Vote,) class Meta: app_label = klass._meta.app_label # NOQA verbose_name = _(klass_name) verbose_name_plural = _(f"{klass_name}s") klass_dict = {"__module__": klass.__module__, "Meta": Meta} vote_class = (type(klass_name, bases, klass_dict) # NOQA return vote_class class VoteMaker: is_relation = True many_to_many = True def __init__(self, **kwargs): self.related_name = kwargs.get("related_name") self.vote_class_attribute_name = kwargs.get("vote_class_attribute_name") def contribute_to_class(self, cls, name): setattr(cls, self.vote_class_attribute_name, create_vote_class(cls)) setattr(cls, name, self.get_votes_field(cls)) def get_votes_field(self, cls): field = models.ManyToManyField( get_user_model(), through=create_vote_class(cls), related_name=self.related_name or f"voted_{camel_to_snake(cls.__name__)}s", verbose_name=_("Votes"), help_text=_("Votes for this post."), ) return field def votes(related_name=None, vote_class_attribute_name="vote_class"): vote_maker = VoteMaker( … -
Connecting my MySQL database ran with docker-compose to Django
I can't figure out how to get it connected. When I run the command - python manage.py check --database default I get the error below. **ERROR: django.db.utils.OperationalError: (1049, "Unknown database 'bears-local-db'") ** When I log into mysql with the CL I don't see the database when I run show databases; DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'bears-local-db', 'USER': 'user', 'PASSWORD': 'pass', 'HOST': '127.0.0.1', 'PORT': '3306' } } services: local-db: image: mysql:8.0 container_name: local-db ports: - 3308:3306 # - ${MYSQL_OUTER_PORT}:${MYSQL_INNER_PORT} network_mode: host environment: MYSQL_ROOT_PASSWORD: 'password' MYSQL_USER: 'user1' MYSQL_DATABASE: bears-local-db volumes: - ./mysql:/var/lib/mysql It took me 5 errors to get to this point so I haven't tried a whole lot but messing with the django settings. -
Django Fetch API JSON Parse Unexpected Character
I'm trying to update an upvote downvote counter with fetch api on my Django App about poop. I'm new to fetch and using this project to learn about it. It is returning the JsonResponse, but it kicks out an Error which I'm not sure how to troubleshoot. I've Followed the Basic Structure of the Fetch Tutorials, but I'm getting this strange error. I don't see what's wrong with my syntax, please help! .html this is the div counter I'm trying to replace <div class="voteCount{{poopfact.id}}">{{ poopfact.total_votes }}</div> .script here's my basic javascript, kicking out the error fetch(url, { headers:{ method: 'POST', 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'poopfact_id':poopfact_id } }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.log('error')) .views this is what I'm returning, it seems successful def vote(request, poopfact_id): ... data = { "total_votes": total_votes, "value":poopfact_id } return JsonResponse(data, safe=False) console.log error I'm not sure how to troubleshoot it. Can anybody point me in the right direction? -
Django Cellery stuck as Pending
I am attempting to use celery within my django app to speed up processing time of a function and I can't get it to work correctly. I am using RabbitMQ. my tasks.py from celery import Celery from celery import shared_task,current_task from myapp.celery import app @app.task def add(x,y): for i in range(25000000): a = x+y return x+y my python code def test_multi_func(): x = 5 y = 10 i = 15 print(f"start = {time.perf_counter()}") while i > 0: g = add.delay(x,y) result = add.AsyncResult(g) i -= 1 print(result.backend) print(result.status) print(f"end = {time.perf_counter()}") print(f"g = {g.get()}") print(f"x = {x} ; y = {y}") my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_select2', 'chartjs', 'django_material_icons', 'material', 'django_celery_results', 'celery_progress', 'django_apscheduler' ] BROKER_URL = 'django://' result_backend = 'django-db' CELERY_RESULT_BACKEND = 'django-db' result_persistent = True task_result_expires = None send_events = True CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_BROKER_URL = 'amqp://localhost' CELERY_CACHE_BACKEND = 'django-cache' CELERY_IGNORE_RESULT = False my celery.py import os from celery import Celery # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') app = Celery('myapp', backend='amqp://guest@localhost:15672/', broker='amqp://guest@localhost:15672/', include=['myapp.tasks']) app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') What am I doing wrong? I am have a … -
<link rel="stylesheet" type="text/css" href="{% static 'css/admin.css' %}"> Not working
When I make the website outside of Django it works perfectly fine. However, when I integrate everything in and put the CSS file in static files, it fails to load. The JavaScript file in the same folder loads perfectly fine. The files being used are: base.html, adminDash.html, admin.js, main.css, and admin.css. The admin.css file is the one specific to adminDash.html and is the one failing to load. Attached are images of all files, what the site should look like, and what it currently looks like. admin.js main.css admin.css adminDash.html base.html what it looks like outside django what it looks like inside django I have tried running it outside of the django project, changing the file location, got some friends to have a go at it, and got chatGPT to try rewriting it it. -
Django - ModelForm Change with ChoiceField
I have a ModelForm and i want to hide some fields and add help text according to values getting from the choiceField ex: if value_getting_from_the_choiceField == '1' hide_some fields in ModelForm elif value_getting_from_the_choiceField == '2' add help text to some fields -
Django Rest Framework web service - `Unsupported Media Type: /api/function_name`
I'm working on building a React (Next.js) application that will communicate with a DRF web service. The application will not be interacting with a database very much but instead sending in data to crunch with the DRF app which will return derived values for display in the React app. On a form submission, I have the following function run on the React side: (values) => { fetch(http://localhost:8000/api/testing_post/", { mode: 'no-cors', method: "POST", headers: {'Content-Type': 'application/json'}, body: JSON.stringify(values, null, 2) }).then(res => { console.log("Request complete! response:", res); }); } This posts the form data to the following view function in the DRF app: @api_view(["POST"]) @parser_classes([JSONParser]) def testing_post(request): print(dir(request)) print(request.data) return Response(status=status.HTTP_200_OK) When I run without print(request.data), everything works as expected. However, when I include this line, I get a 415 error Unsupported Media Type: /api/testing_post/ I'm confused as to why I'm receiving this message - I'm clearly setting the content type in the request; and, on the server side, am using a JSON parser. Does anyone know where the issue is stemming from? Thanks in advance! -
How to add data from an API to Django's database when i click on a button
My question is going to be split into two halves for a better understanding. First half: I'm trying to add a bunch of data that I rendered on a page from an API endpoint, to my database when I click "Add to my records", as can be seen in the image below, keeping in my mind that there are a lot more cards such as for other countries and I'm only trying to store "Date and Country" into the database: enter image description here and the second half, is after adding to the database I want to render them on another page, and if the database is empty aka the user hasn't added any data to the database yet, i want the page to show "now data to display" but if the user did, i want to render what's in the database. enter image description here Here's what I've tried so far: models.py from django.db import models class CountryData(models.Model): country = models.CharField(max_length=100) date = models.DateTimeField() def __str__(self): return self.country views.py def all_countries(request): first_response = requests.get('https://api.covid19api.com/summary').json() results = len(first_response['Countries']) my_new_list = [] for i in range(0, results): my_new_list.append(first_response['Countries'][i]) # print(my_new_list) if request.method == "POST": if request.POST.get('country') and request.POST.get('date'): added_record = CountryData() …