Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When I include a template in another template how can I pass the path of a source file?
I have two templates that go together, one inside the other. The inner one has an icon that needs to change according to the content of the parent template. I've tried to pass the icon path using a variable: src="{% url 'main_bar_icon' %}"> and I added this line of code in the parent template: {% with main_bar_icon='../static/dist/img/logout-icon.svg' %} {% include 'main_bar.html' %} {% endwith %} So, this is my inner template: {% block main_bar %} <a href=""> <img class="app-main-bar-icon" src="{% url 'main_bar_icon' %}"> </a> {% endblock main_bar %} And this is my parent template: {% block content %} {% with main_bar_icon='/dist/img/logout-icon.svg' %} {% include 'main_bar.html' %} {% endwith %} {% endblock content%} In the browser I get this: <img class="app-main-bar-icon" src(unknown) alt="icon"> -
Django 2 Many to Many relationships
I'm working on a project using Python(3.7) and Django(2.1) in which I need to build a relationship between users and organizations. I'm using the default Django User model and a profile model to add extra information to users. Many users can join an organization and an Organization can have many members, a user can create an Organization, these behaviors I need to implement, according to my understanding we need to build a ManyToMany relationship for Organizations model, but don know how to use this relationship to display the information, e.g display a user's organizations on his profile page. Here are my models: class Organization(models.Model): name = models.CharField(max_length=255, blank=False) users = models.ManyToManyField(User, related_name='members', null=True) def __str__(self): return self.name class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='media/default.jpg', upload_to='profile_pics') goals = MultiSelectField(choices=goals_choices, default='') def __str__(self): return f'{self.user.username} Profile' -
How to build a shopify application with django
I have a homework : The objective is to create a Shopify app. The app will allow a customer to login to the shop using his Twitter account. Stack using : Django + DRF + Vanilla Js (for the front end). But i have never build an app for shopify apps store, and all tutorials found about django an shopify are very old and not updated. And others are only about Ruby... So i post here to hope find somebody to explain (not necessary in details) how can i setup my django app and make it reachable on shopify app store. Where an customer can try to login in his shop with a twitter account. Ps: I want just the step to follow and configure the entire app... Thank for reading and trying to help me ! -
login_required next not redirecting
I'm working through a tut in the book Django 2 By Example with PyCharm and Chrome. I'm using Django 2.0.8 as specified in the book. As it says, I have the following base.html template: {% load staticfiles %} <!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock %}</title> <link href="{% static 'css/base.css' %}" rel="stylesheet"> </head> <body> <div id="header"> <span class="logo">Bookmarks</span> {% if request.user.is_authenticated %} <ul class="menu"> <li {% if section == "dashboard" %} class="selected" {% endif %}> <a href="{% url 'dashboard' %}">My dashboard</a> </li> <li {% if section == "images" %} class="selected" {% endif %}> <a href="#">Images</a> </li> <li {% if section == "people" %} class="selected" {% endif %}> <a href="#">People</a> </li> </ul> {% endif %} <span class="user"> {% if request.user.is_authenticated %} Hello {{ request.user.first_name }}, <a href="{% url 'logout' %}">Logout</a> {% else %} <a href="{% url 'login' %}">Log-in</a> {% endif %} </span> </div> <div id="content"> {% block content %} {% endblock %} </div> </body> </html> This seems to log me in some of the time? It will work once, then I log out and it won't let me log in again. My views.py has a login_required view that redirects to a dashboard template and assigns a section context: @login_required … -
Cannot import BACKEND 'channels_redis.core.RedisChannelLayer' specified for default
Cannot import BACKEND 'channels_redis.core.RedisChannelLayer' specified for default WebSocket DISCONNECT /ws/chat/cvc/ [127.0.0.1:56904] -
Django: how to import a function
Python 3.6.7 Django 2.1.5 In PyCharm Community edition I created a new project called simple_pr. Then I organized a Django project: django-admin startproject simple_project Then an application: python manage.py startapp home My Pythonpath: /home/michael/PycharmProjects/simple_pr/simple_project /opt/pycharm-community-2018.3.2/helpers/pydev /home/michael/PycharmProjects/simple_pr /opt/pycharm-community-2018.3.2/helpers/third_party/thriftpy /opt/pycharm-community-2018.3.2/helpers/pydev /home/michael/.PyCharmCE2018.3/system/cythonExtensions /home/michael/PycharmProjects/simple_pr/simple_project /usr/lib/python36.zip /usr/lib/python3.6 /usr/lib/python3.6/lib-dynload /home/michael/PycharmProjects/simple_pr/venv/lib/python3.6/site-packages /home/michael/PycharmProjects/simple_pr/venv/lib/python3.6/site-packages/setuptools-39.1.0-py3.6.egg /home/michael/PycharmProjects/simple_pr/venv/lib/python3.6/site-packages/pip-10.0.1-py3.6.egg Project structure: (venv) michael@michael:~/PycharmProjects/simple_pr$ tree . ├── simple_project │ ├── home │ │ ├── admin.py │ │ ├── apps.py │ │ ├── __init__.py │ │ ├── migrations │ │ │ └── __init__.py │ │ ├── models.py │ │ ├── tests.py │ │ └── views.py │ ├── manage.py │ └── simple_project │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-36.pyc │ │ └── settings.cpython-36.pyc │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── venv urls.py from django.contrib import admin from django.urls import path from simple_project.home.views import current_datetime urlpatterns = [ path('admin/', admin.site.urls), ] home.views.py from django.http import HttpResponse import datetime def current_datetime(request): now = datetime.datetime.now() html = "<html><body>It is now %s.</body></html>" % now return HttpResponse(html) Traceback: /home/michael/PycharmProjects/simple_pr/venv/bin/python /opt/pycharm-community-2018.3.2/helpers/pydev/pydevd.py --multiproc --qt-support=auto --client 127.0.0.1 --port 37559 --file /home/michael/PycharmProjects/simple_pr/simple_project/manage.py runserver pydev debugger: process 5982 is connecting Connected to pydev debugger (build 183.4886.43) pydev debugger: process 5988 is connecting Performing system checks... Unhandled exception in thread started … -
can't validate imagefield with ajax function
i have a form with ModelForm and have a extra field (ImageField). I tried to validate this field in forms.py def clean_icono(self): icon = self.cleaned_data['icono'] if icon: w, h = get_image_dimensions(icon) if w != 127: raise forms.ValidationError("El icono debe ser de 127 pixeles de ancho") if h > 84: raise forms.ValidationError("El icono debe ser de 84 pixeles de largo") else: raise forms.ValidationError("No se encuentra un icono") return icon in the html i have a ajax function which display the error in the modal $('#bd_form').on('submit', function (e) { e.preventDefault(); var data = new FormData($('form').get(0)); $.ajax({ type: $(this).attr('method'), url: this.action, data: data, // recupera los datos del formulario para usarlos en caso de error, no funciona con imagenes y archivos cache: false, processData: false, contenType: false , success: function (data, status) { $('#popup').find('#bd_form').off('submit', '#bd_form'); $("#bd_form").load(" #bd_form"); $('#popup').modal('hide'); $("#bd_table").load(" #bd_table"); }, error: function (request, type, errorThrown) { var data = jQuery.parseJSON(request.responseText); $('#popup').find('#bd_form').off('submit', '#bd_form'); $('#popup').find('#errores').empty(); for (var key in data) { $('#popup').find('#errores').append(key + ': ' + data[key] + '<br>'); } $('#popup').find('#form-error').show(); } }); return false; }); but i always get "No se encuentra un icono" error, i cant save the imagefield. I tried send the data with serialize() but doesn't work. I read i … -
dynamic model creation using Django
I am trying to create dynamic model using below code in sqlite3 database. When I check the database, The table is not created in database name='task' attrs = { 'field1': models.CharField(max_length=40), 'field2': models.CharField(max_length=40), '__module__': 'core.models' } model = type(name, (models.Model,), attrs) m=model(field1='Switch on', field2='lights') m.save() Also when I try to create a record using below code errors out the table 'core_task' not found. Kindly let me know what am i missing here. Thanks, Subash Base search: Django: dynamic models disappear after creation -
How to add non-standard languages to Dango?
Tell me, how can I add a language to Dango, which is not supported by the standard? In the file settings.py identified: ... LANGUAGES = ( ('ru', 'Русский'), ('en', 'English'), ('ady', 'Адыгабзэ'), ) LOCALE_PATHS = ( (os.path.join(BASE_DIR, 'locale/'),) ) ... In the folder locale created directories with language codes and spelled commands: django-admin makemessages --all django-admin compilemessages Files .mo and .po were created in these directories. But when I opened the site, an error appeared "Unknown language code ady" File add_lang.html {% load i18n %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} <ul> {% for language in languages %} <li><a href="/{{ language.code }}/">{{ language.name_local }}</a></li> {% endfor %} </ul> -
What's the right way for a RESTful app to upload files?
I'm building a React application along with a Django REST API, and I wanna use Cloudinary for my image management/storage. My question is: What would be the right way to do it? 1) The react application through the React SDK provided by Cloudionary upload directly to Cloudionary and then the response is sent to my Django Rest app. 2) The react application uploads directly to my Django Rest App and then my Django Rest app uploads to Cloudionary through the Django SDK provided by Cloudionary. What's the right way to do it and what would be the benefits of one over the other? Or is it really indifferent? -
Disable atomic transaction in Django 1.11 change view
Django 1.11 has following piece of code @csrf_protect_m def changeform_view(self, request, object_id=None, form_url='', extra_context=None): with transaction.atomic(using=router.db_for_write(self.model)): return self._changeform_view(request, object_id, form_url, extra_context) in env/lib/python3.6/site-packages/django/contrib/admin/options.py As per doc Django 1.11 is supposed to be working in auto commit mode but the changeform_view does not seem to aligned to the documentation and I see that, form save is happening within a transaction. How can I enable autocommit mode for django form ? -
Scheduling a task at particular time using django-background-tasks
I am trying to use django-background-tasks to schedule a task at midnight and then repeat daily. I am able to achieve repeat feature but unable to get it to run at scheduled time. The timezone in my django project is UTC. Something i have tried so far: now = datetime.datetime.now() date = datetime.date(now.year, now.month, now.day) print(timezone.get_current_timezone()) time = datetime.time(9, 49, 0, tzinfo=timezone.get_current_timezone()) aware_datetime = datetime.datetime.combine(date, time) schedule_email_notification(schedule=aware_datetime, repeat=Task.DAILY) Documentation is not clear on how to do so. If someone can help? -
How to convert a lookup to an expression to use in `QuerySet.annotate`?
The subject may be a little bit obscure, so here is an example. Let's say I have a model: class TestModel(models.Model): user = models.ForeignKey(User, ...) I want a QuerySet containing a has_user field that would basically map to the following SQL query select id, user_id is not null as has_user from app_testmodel How can I explain this user_id field to Django when using QuerySet.annotate? I am aware that Django has concepts like models.F, models.Q, models.lookups, models.expressions etc., but I am unable to understand how to apply them in my case. To the best of my knowledge, this is a question of converting a "lookup" to a boolean "expression" where A "lookup" is something like 'user_id__isnull' or lookups.IsNull(models.F('user_id')) in Django ORM language. An "expression" is something like expressions.ExpressionWrapper(?, output_field=models.BooleanField()). So far I only managed to convert the user_id is not null expression to case when user_id is not null then true else false end, which maps to Python code like this: from django.db import models from django.db.models import expressions # ... qs = TestModel.objects.all().annotate(has_user= expressions.Case( expressions.When( user__isnull=False, then=expressions.Value(True), ), default=expressions.Value(False), # # Tell Django the expected type of the field, see `output_field` in # https://docs.djangoproject.com/en/2.1/ref/models/expressions/ # output_field=models.BooleanField())) But it is an … -
How to handle Django through_fields with non-fixed direction
Django's ManyToManyField through_fields attribute takes a tuple of the format(foreign_key_to_intermediate_model, foreign_key_from_intermediate_to_target_model) I have a data-structure that essentially looks like this (simplified for the example) class Person(models.Model): name = models.CharField() relations = models.ManyToManyField( Person, through='Relationship', through_fields=(???)) class Relationship(models.Model): child = models.ForeignKey(Person) parent = models.ForeignKey(Person) holiday_card_sent = models.BooleanField() I need to annotate the relationship (did they send a card), but a single person will be both a child and a parent in different relationships. The relationship has a directionality, but not the person. A person will also have multiple children and multiple parents. It feels like I'm missing something obvious here. Should I just be creating my own __init__ method to handle this? Will that lose out on lookup performance that Django would normally give? -
How to import a function
Python 3.6.7 Project structure: . └── simple_project ├── simple_project │ ├── db.sqlite3 │ ├── home │ │ ├── admin.py │ │ ├── apps.py │ │ ├── __init__.py │ │ ├── migrations │ │ ├── models.py │ │ ├── tests.py │ │ └── views.py │ ├── manage.py │ └── simple_project │ ├── __init__.py │ ├── __pycache__ │ ├── settings.py │ ├── urls.py │ └── wsgi.py Pythonpath: /home/michael/PycharmProjects/simple_project/simple_project/opt/pycharm-community-2018.3.2/helpers/pydev/home/michael/PycharmProjects/simple_project/opt/pycharm-community-2018.3.2/helpers/third_party/thriftpy/opt/pycharm-community-2018.3.2/helpers/pydev/home/michael/.PyCharmCE2018.3/system/cythonExtensions/home/michael/PycharmProjects/simple_project/simple_project/usr/lib/python36.zip/usr/lib/python3.6/usr/lib/python3.6/lib-dynload/home/michael/PycharmProjects/simple_project/venv/lib/python3.6/site-packages/home/michael/PycharmProjects/simple_project/venv/lib/python3.6/site-packages/setuptools-39.1.0-py3.6.egg/home/michael/PycharmProjects/simple_project/venv/lib/python3.6/site-packages/pip-10.0.1-py3.6.egg /home/michael/PycharmProjects/simple_project/simple_project /opt/pycharm-community-2018.3.2/helpers/pydev /home/michael/PycharmProjects/simple_project /opt/pycharm-community-2018.3.2/helpers/third_party/thriftpy /opt/pycharm-community-2018.3.2/helpers/pydev /home/michael/.PyCharmCE2018.3/system/cythonExtensions /home/michael/PycharmProjects/simple_project/simple_project /usr/lib/python36.zip /usr/lib/python3.6 /usr/lib/python3.6/lib-dynload /home/michael/PycharmProjects/simple_project/venv/lib/python3.6/site-packages /home/michael/PycharmProjects/simple_project/venv/lib/python3.6/site-packages/setuptools-39.1.0-py3.6.egg /home/michael/PycharmProjects/simple_project/venv/lib/python3.6/site-packages/pip-10.0.1-py3.6.egg urls.py from django.contrib import admin from django.urls import path, re_path from simple_project.home.views import current_datetime # Line 19 urlpatterns = [ path('admin/', admin.site.urls), # re_path(r'^$', current_datetime) ] Traceback: /home/michael/PycharmProjects/simple_project/venv/bin/python /opt/pycharm-community-2018.3.2/helpers/pydev/pydevd.py --multiproc --qt-support=auto --client 127.0.0.1 --port 44221 --file /home/michael/PycharmProjects/simple_project/simple_project/manage.py runserver pydev debugger: process 5277 is connecting Connected to pydev debugger (build 183.4886.43) pydev debugger: process 5283 is connecting Performing system checks... Unhandled exception in thread started by <_pydev_bundle.pydev_monkey._NewThreadStartupWithTrace object at 0x7f76c14fd668> Traceback (most recent call last): File "/opt/pycharm-community-2018.3.2/helpers/pydev/_pydev_bundle/pydev_monkey.py", line 632, in __call__ return self.original_func(*self.args, **self.kwargs) File "/home/michael/PycharmProjects/simple_project/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/michael/PycharmProjects/simple_project/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/home/michael/PycharmProjects/simple_project/venv/lib/python3.6/site-packages/django/core/management/base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "/home/michael/PycharmProjects/simple_project/venv/lib/python3.6/site-packages/django/core/management/base.py", line 366, in _run_checks return checks.run_checks(**kwargs) File "/home/michael/PycharmProjects/simple_project/venv/lib/python3.6/site-packages/django/core/checks/registry.py", line 71, in run_checks new_errors = … -
Django how to pass choices list to a custom select widget
I need to override select widget.`class TooltipSelectWidget(Select) : def __init__(self, *args, **kwargs) : super().__init__(*args, **kwargs) `Then I call it in a form. But I do not see in the docs how to pass the choices list to this customed widget. -
How to mock the get function from requests.session?
I am trying to mock the get function from requests.session and somehow it does not end up happening. I have the following code: #main.py import requests def function_with_get(): c = requests.session() c.get('https://awesome_url.com') # do some other stuff return c def second_function_with_get(client): c.get('https://awesome_url.com') # do some other stuff #test.py from unittest import mock from django.test import TestCase class Testing(TestCase): @mock.patch('main.requests.session.get) @mock.patch('main.requests.session) def test_which_fails_because_of_get(mock_sess, mock_get): client = function_with_get() second_function_with_get(client) assertEqual(mock_requests_session_get.call_count, 2) The test throws an assertion error that mock_get is called 0 times (0 != 2) How should the get function of requests.session() be mocked? -
django:TypeError: expected str, bytes or os.PathLike object, not NoneType
I did a git add in django, and then I gave an error to the runserver. I tried to cancel the add, but I still get an error. django2.0 and python 3.7,I tried to pull, but still can't, it feels like the database is out of order. `System check identified no issues (0 silenced). Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x00000212F544C7B8> Traceback (most recent call last): File "C:\edu_env\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\edu_env\lib\site-packages\django\core\management\commands\runserver.py", line 123, in inner_run self.check_migrations() File "C:\edu_env\lib\site-packages\django\core\management\base.py", line 427, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\edu_env\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\edu_env\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__ self.build_graph() File "C:\edu_env\lib\site-packages\django\db\migrations\loader.py", line 200, in build_graph self.load_disk() File "C:\edu_env\lib\site-packages\django\db\migrations\loader.py", line 99, in load_disk directory = os.path.dirname(module.__file__) File "C:\edu_env\lib\ntpath.py", line 232, in dirname return split(p)[0] File "C:\edu_env\lib\ntpath.py", line 190, in split p = os.fspath(p) TypeError: expected str, bytes or os.PathLike object, not NoneType` -
Signal receiver works in shell but not in frontend
I've been following these instructions to associate a profile to each user upon user creation. When I instantiate and save a user in the shell, the associated profile get saved as well. However, when I sign up a user in the front end, then no associated profile gets created. Furthermore, the console does not execute a print statement embedded in the receiver. I verified that a new user is indeed added to the database. Debug-toolbar does list "post_save" under the sent signals, and also lists desired receiver "create_user_profile" under the corresonding receivers. What could be going on here? The relevant portion of my signals.py is from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from people.models import Profile @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): print(f"create_user_profile: this was called with instance={instance}") if created: Profile.objects.create(user=instance) The contents of the associated apps.py file are from django.apps import AppConfig class PeopleConfig(AppConfig): name = 'people' verbose_name = ('people') def ready(self): import people.signals # noqa and my init.py file has default_app_config = 'people.apps.PeopleConfig' -
Pass parameters to post method in Django Class based views
I am unable to pass parameters from urls.py to my HomeView class view to it's post() method but able to pass parameters to get() method. I am quite unsure why this is happening. What I am trying to accomplish is to make post() method work in 2 different ways by using the parameter that it gets passed along from urls. Here's my views.py class HomeView(TemplateView): template_name = 'new_home.html' section_heading = "" type = "" sub_type = None post_method_type = None def post(self, request): ''' Allows user login, This was added to allow user login from the modal ''' print("Here is :"+self.post_method_type) # <---- Prints Nothing if self.post_method_type == "login": #do login stuff elif self.post_method_type == "navigator": #do navigating stuff def get(self, request, filter=None): ''' Fetches all the posts from the Post model by comparing the tag from the urls.py to the Tag model. ''' print("HERE GET :"+ self.type) # <----- prints value properly # filtering from here on And here's my urls.py # for post path('login/', HomeView.as_view(post_method_type='login'), name="login"), path('navigator/', HomeView.as_view(post_method_type='navigator'), name="navigator"), # for get path('python/', HomeView.as_view(type='py'), name='home_python'), When I use this class as a get method, It's successfully printing py as sent from urls.py but is not able to print … -
Server responded with a status of 415 (Unsupported Media Type) - vue.js and python django
{"errors":[{"detail":"Unsupported media type \"application/json;charset=UTF-8\" in request.","source":{"pointer":"/data"},"status":"415"}]} -
Django Sitemap protocol attribute
I built a blog and I created a class inheriting from django.contrib.sitemaps.Sitemap like this: from django.contrib.sitemaps import Sitemap from .models import Post class PostSitemap(Sitemap): changefreq = 'daily' priority = 0.9 protocol = 'https' def items(self): return Post.published.all() def lastmod(self, obj): return obj.publish Despite the fact that I assigned https to the protocol attribute, I keep getting links to blog posts with http protocol instead of https in my sitemap.xml. Here's what I mean: <item> <title>THE TITLE</title> <link>http://www.shelteratyourcrossroads.com/2019/01/06/fluidity-grace/</link> <description>&lt;p&gt;Good morning Engraced One.&amp;nbsp;&lt;/p&gt; &lt;p&gt;It&amp;#39;s a beautiful day, I woke up this morning quite engrossed with my study of medicine and how difficult it is sometimes to appreciate visible progress, ...</description> <guid>http://www.blahblahblah.com/YYYY/MM/DD/sluggity-slug/</guid> </item> I want the urls in the <link> and <guid> tags to use the https protocol. How do I do that? I created feeds for the blog posts like: from django.contrib.syndication.views import Feed from django.template.defaultfilters import truncatewords from .models import Post class LatestPostsFeed(Feed): title = 'Some Title' link = 'https://www.blahblahblah.com/blog/' description = 'This is a blog about life. New posts every week' def items(self): return Post.published.all()[:7] def item_title(self, item): return item.title def item_description(self, item): return truncatewords(item.body, 30) -
Get '_set' for a many-to-many relationship with a through
I've got a user model like this: class Person(AbstractUser): id = models.AutoField(primary_key=True) ...(additional attributes taken out for brevity)... kids = models.ManyToManyField( 'Person', through='Relationship', related_name='parents') and a Relationship model that looks like this: class Relationship(models.Model): parent_id = models.IntegerField() kid_id = models.IntegerField() class Meta: unique_together = ('parent_id', 'kid_id') I'm trying to figure out the best way to get a set of the kids related to a particular parent (who would be the ones logged in). I've got something like this: user = Person.objects.get(id=request.user.id) print(user.relationship_set.all()) But that gives me an error 'Person' object has no attribute 'relationship_set' How best would I accomplish this? -
Django: Frequent use of include template tag - how much is too much?
I noticed that I started using include template a lot. One of my template files has 20+ include tags. Some of them are for modal dialogs that in turn have include for different form field sets. I am also using basically the same buttons with different data attributes so these are also done with include tags. Some my "fragments" that I use with include have around only five lines of HTML code. I worry if this is too much and can negatively affect performance (since Django loads another files, etc..) For example whis is markup of one of my HTML fragments I am using with include: <div class="form-group"> <input type="url" class="form-control" id="video-link-input" name="video_link" placeholder="YouTube link"> </div> <input type="hidden" id="video_id" name="video_id" value=""> <img class="img-fluid img-thumbnail" id="video-img-preview"> Hope the question is not too broad. I would just like to avoid possible bad practice. -
Django how to serialize and validate external xml data
i have "problems" validating external xml. What i want is to fetch data from an external rss site, validate if all fields are present and save it to the database then. The problem i am having is that i am not sure how can i send the xml data to my validator. I tried in different ways but it was not working. https://api.foxsports.com/v1/rss?partnerKey=zBaFxRyGKCfxBagJG9b8pqLyndmvo7UU&tag=nba This is an example of the rss i am trying to parse. Here is my code: import json import requests import xml.etree.ElementTree as ET from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status, generics class Test(APIView): def get(self, request, format=None): response = requests.get( channel.url ) print(response.status_code) if response.status_code == 200: xml = response.text.encode("utf-8") tree = ET.fromstring(xml) for child in tree.iter("item"): serializer = RssSerializer(data=child) if serializer.is_valid(): serializer.save(parsed_xml) The problem here is that my serializer is always not valid, no matter what i do. I kind of got around this problem when i wrote a small helper function that is manually extracting fields from the request. It looks like this: def parse_xml(self, node): parsed_json = { "title": node.find("title").text, "description": node.find("description").text, "link": node.find("link").text, "pub_date": node.find("pubDate").text, "guid": node.find("guid").text, } return parsed_json Basically i just added this line parsed_xml …