Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Image Compression
I'm trying to compress Image before Uploading it to the database. Here's what I tried, from PIL import Image as Img from PIL import Image try: from StringIO import StringIO except ImportError: from io import StringIO class Profile(models.Model): profile = models.ImageField(upload_to='user_image', blank=True) def save(self, *args, **kwargs): if self.profile: img = Img.open(StringIO.StringIO(self.profile.read())) if img.mode != 'RGB': img = img.convert('RGB') img.thumbnail((self.profile.width / 1.5, self.profile.height / 1.5), Img.ANTIALIAS) output = StringIO.StringIO() img.save(output, format='JPEG', quality=70) output.seek(0) self.profile = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.profile.name.split('.')[0], 'image/jpeg', output.len, None) super(Profile, self).save(*args, **kwargs) Problem is, whenever I try to upload an image it's raising an error, img = Img.open(StringIO.StringIO(self.profile.read())) type object '_io.StringIO' has no attribute 'StringIO' How can we fix that? Thank You very much . . . -
django 2.0 url.py include namespace="xyz"
I've a problem with the routing django.conf.urls include() - main project folder - urls.py Line 22 of urls.py (pip freeze and urls.py - see below) throws the error in the console: Quit the server with CONTROL-C. [02/Jan/2018 14:22:49] "GET /api/compositions/ HTTP/1.1" 200 30058 [02/Jan/2018 14:22:53] "GET /api/compositions/1/ HTTP/1.1" 200 6195 Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f17ee06e400> Traceback (most recent call last): File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/urls/resolvers.py", line 397, in check for pattern in self.url_patterns: File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/urls/resolvers.py", line 529, in urlconf_module return import_module(self.urlconf_name) File "/home/ernst/django_virtualenv/lib/python3.4/importlib/__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 2254, in _gcd_import File "<frozen importlib._bootstrap>", line 2237, in _find_and_load File "<frozen … -
ListView and a form in single page
I have a blog.html which I will list all blog posts in my model using a generic class-based view ListView and it will point to www.example.com/blog. I also want to add a form not by pointing to a new page/url but all the list of blog posts plus that form. This post has a similar situation like me and the answer says add the form to TEMPLATE_CONTEXT_PROCESSORS. So after doing this, how can I use the form in my blog.html? -
Django refering to same model instances in Abstract Model
I have an abstract model from which a couple of my main models are inherited. Main difficulty in this case is that I have a need in reference to the same model, like a ForeignKey to self. I have read that the ForeignKey is not possible in abstract models and GenericForeignKey can help, however I can`t really make it work. As I understand structure should be somethig like following: class BaseModel(models.Model): versions = GenericRelation('self') date_created = models.DateTimeField(default=datetime.datetime.now) is_deleted = models.BooleanField(default=False) content_type = models.ForeignKey(ContentType, blank=True, null=True) object_id = models.PositiveIntegerField(blank=True, null=True) content_object = GenericForeignKey('content_type', 'object_id') class FirstModel(BaseModel): some_fields... class AnotherModel(BaseModel): another_fields... But with this approach I get an error: >>> item1 = FirstModel.objects.get(id=1) >>> item2 = FirstModel.objects.get(id=2) >>> item2.content_object = item1 Traceback (most recent call last): File "<input>", line 1, in <module> File "/home/michael/.virtualenvs/diagspecgen/lib/python3.6/site-packages/django/contrib/contenttypes/fields.py", line 245, in __set__ ct = self.get_content_type(obj=value) File "/home/michael/.virtualenvs/diagspecgen/lib/python3.6/site-packages/django/contrib/contenttypes/fields.py", line 163, in get_content_type return ContentType.objects.db_manager(obj._state.db).get_for_model( AttributeError: 'ReverseGenericRelatedObjectsDescriptor' object has no attribute '_state' Is that I am trying to reach is absolutly impossible and the only solution is to explicitly create needed fields in existing models? Thanks in advanse for your suggestions. -
AttributeError: model object has no attribute 'rel'
In django 1.9 I used this custom MultilingualCharField, then I upgrade to django 2.0 and it give error: class MultilingualCharField(models.CharField): def __init__(self, verbose_name=None, **kwargs): self._blank = kwargs.get("blank", False) self._editable = kwargs.get("editable", True) #super(MultilingualCharField, self).__init__(verbose_name, **kwargs) super().__init__(verbose_name, **kwargs) def contribute_to_class(self, cls, name, virtual_only=False): # generate language specific fields dynamically if not cls._meta.abstract: for lang_code, lang_name in settings.LANGUAGES: if lang_code == settings.LANGUAGE_CODE: _blank = self._blank else: _blank = True localized_field = models.CharField(string_concat( self.verbose_name, " (%s)" % lang_code), name=self.name, primary_key=self.primary_key, max_length=self.max_length, unique=self.unique, blank=_blank, null=False, # we ignore the null argument! db_index=self.db_index, rel=self.rel, default=self.default or "", editable=self._editable, serialize=self.serialize, choices=self.choices, help_text=self.help_text, db_column=None, db_tablespace=self.db_tablespace ) localized_field.contribute_to_class(cls, "%s_%s" % (name, lang_code),) def translated_value(self): language = get_language() val = self.__dict__["%s_%s" % (name, language)] if not val: val = self.__dict__["%s_%s" % (name, settings.LANGUAGE_CODE)] return val setattr(cls, name, property(translated_value)) def name(self): name_translated='name'+settings.LANGUAGE_CODE return name_translated Here's the error: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x03BCB8E8> Traceback (most recent call last): File "D:\Python\Envs\possedimenti\lib\site-packages\django\utils\autoreload.py ", line 225, in wrapper fn(*args, **kwargs) File "D:\Python\Envs\possedimenti\lib\site-packages\django\core\management\com mands\runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "D:\Python\Envs\possedimenti\lib\site-packages\django\utils\autoreload.py ", line 248, in raise_last_exception raise _exception[1] File "D:\Python\Envs\possedimenti\lib\site-packages\django\core\management\__i nit__.py", line 327, in execute autoreload.check_errors(django.setup)() File "D:\Python\Envs\possedimenti\lib\site-packages\django\utils\autoreload.py ", line 225, in wrapper fn(*args, **kwargs) File "D:\Python\Envs\possedimenti\lib\site-packages\django\__init__.py", line 24, in … -
Django - Why PATCH returns in response correct data which I would like to save but it doesn't save this data in database?
Any ideas why PATCH returns in response correct data which I would like to save but it doesn't save this data in database? def patch(self, request, portfolio_id): try: object = Object.objects.get(id=object_id) except Object.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = ObjectSerializer(object, data=request.data, partial=True) if serializer.is_valid(): serializer.save(object=object) return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Django display an image while rendering request
I want a simple loading screen to be displayed while my django function is done. I read that Ajax might be able to do this, but non of the explanations are clear. So basically i have a small index view: def index(request): return render(request, 'index.html', {'form': forms.AnalysisType()}) This index page has a Submit button, and when it is pressed a plot view is rendered. The plot view takes some time to load, an i would like to display a loading GIF in my page while it loads. The plot view is long and complicated, but in the end it should return a render(request) call. I tried adding something like this to my index.html template, but it did not work: <script> $(document).ready(function () { //Attach the ajaxStart and ajaxComplete event to the div $('#prgs').ajaxStart(function() { $(this).show(); }); $('#prgs').ajaxComplete(function() { $(this).hide(); }); //Perform the AJAX get $.get('/plot/', function(data) { //Do whatever you want with the data here }); }); </script> -
Passing context to django-registration's views
I'm utilizing django-registration with a set of premade templates I found on Github for doing a two-step (registration-activation) workflow using HMAC. I want to pass variables like my website's name to the emails sent by django-registration. the activation email sent to a new registrant, for example, or the password change one. The "problem" is I don't directly have access to those views. That's kinda the point of django-registration, you include its path in the urls.py file, and everything works: urlpatterns = [ url(r'^', include('core.urls')), url(r'^admin/', admin.site.urls), url(r'^accounts/', include('registration.backends.hmac.urls')), ] What's the minimum effort way of adding context to those views? I've already created and am successfully passing context to emails in my own views (using context processors): def send_some_email_view(request): msg_plain = render_to_string('email_change_email.txt', context, request=request) msg_html = render_to_string('email_change_email.html', context, request=request) But what about views I didn't create? -
django tesy using selenium package error
7 and want to create some django test using selenium package. here the simple test : import unittest from selenium import webdriver class TestSignup(unittest.TestCase): def setUp(self): self.driver = webdriver.Firefox() def test_signup_fire(self): self.driver.get("http://localhost:8000/add/") self.driver.find_element_by_id('id_title').send_keys("test title") self.driver.find_element_by_id('id_body').send_keys("test body") self.driver.find_element_by_id('submit').click() self.assertIn("http://localhost:8000/", self.driver.current_url) def tearDown(self): self.driver.quit if __name__ == '__main__': unittest.main() but I take this error : TypeError: environment can only contain strings in this line : self.driver = webdriver.Firefox() and I don't know why,any idea how to can fix this error ? -
How to get average of 6 first elements in a queryset and annotate the value in Django?
I have 2 models that are something like this: class Foo(models.Model): name = models.CharField(max_length=30) class FooStatement(models.Model): foo = models.ForeignKey(Foo, on_delete.models.CASCADE) revenue = models.DecimalField(decimal_places=2) date = models.DateField() What I want to know is what the average is of the FooStatement revenue for the first 6 dates for each Foo object. Is there any way to achieve this? I was thinking of slicing the first 6 entries (after ordering them), but I cannot seem to get this to work. The statement months all start at different dates so I can't just say that I want all dates that are lesser than 'x'. I'm almost positive the answer lies somewhere in clever annotation, but I just cannot find it. -
Image Compression Before Upload
I'm trying to compress Image before Uploading it to the database. Here's what I tried, from PIL import Image as Img from PIL import Image try: from StringIO import StringIO except ImportError: from io import StringIO class Profile(models.Model): profile = models.ImageField(upload_to='user_image', blank=True) def save(self, *args, **kwargs): if self.profile: img = Img.open(StringIO.StringIO(self.profile.read())) if img.mode != 'RGB': img = img.convert('RGB') img.thumbnail((self.profile.width / 1.5, self.profile.height / 1.5), Img.ANTIALIAS) output = StringIO.StringIO() img.save(output, format='JPEG', quality=70) output.seek(0) self.profile = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.profile.name.split('.')[0], 'image/jpeg', output.len, None) super(Profile, self).save(*args, **kwargs) Whenever I try to upload a image it's raising an error type object '_io.StringIO' has no attribute 'StringIO' How can we fix that? Thank You . . . -
how to read excel data and insert into msql database dynamically using pandas in python 3.X
I have been able to get the headers and able to create table but can't get the excel content and insert excel content by lines each into the database columns import pandas as pd import sqlalchemy as sa import pymysql from pymysql import DatabaseError class ReadCSV(): def read(self, path): clean_header = '' #db = pymysql.connect("localhost", "root", "password", "test") try: df = pd.read_csv(path, skiprows=1, na_values=['not available','n.a.','']) unclean_headers = df.columns for header in unclean_headers: #header = self.clean_data(header) clean_header +=self.header_cleanup(header) #remove the last commas clean_header = clean_header[:-1] #create new table and columns #self.create_tab(clean_header) # insert the csv content in db datas = pd.read_csv(path, chunksize=100000, skiprows=2,header=None, na_values=['not available','n.a.',' ']) for data in datas.split('\n'): #======= I need to get each columns and insert the into data base print(data) except ValueError: print('Invalid value') except: print('Error') thanks in advance -
Issue with importing rest_framework inside django app
I am facing an issue of importing rest_framework inside my django app whenever i try to make migrations or create superuser or simply run the runserver. I have installed the framework using this command but django still doesn't recognize it sudo pip install djangorestframework here's the snippet of settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'companies.apps.CompaniesConfig', ] REST_FRAMEWORK = { 'DEFAULT_MODEL_SERIALIZER_CLASS': 'rest_framework.serializers.HyperlinkedModelSerializer', # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ] } -
Django to create and change mysql database for learning purposes
I am leaning Python programming language. I want to familiarize myself with mysql database as well. I've installed mysql database and Django on my computer. I have Ubuntu 14.04 and python 3.4 installed. I've configured Django settings to use mysql database. I tested Django connection to mysql db and all things work properly. I am a complete newbie with web development. I didn't create my own website and I didn't start developing any web application. My purpose currently is to master creation of mysql database and tables, making changes/migrations/queries, using Django models. Is it reasonable/possible to use Django ORM for work with mysql database without simultaneous development of a web application/local application? As I've said, I don't have my own website. I want just to try using mysql and Django together on my computer in order to get deeper knowledge as to Django and mysql in this respect. -
Django Tweepy Streaming in browser
I want to implement a live streamer in the browser of the Tweeter data. I am using Tweepy library to stream the tweets. class MyStreamListener(tweepy.StreamListener): def on_status(self, status): return status.text This allows me to stream the data to the console, however, I would like to stream and display the data in the browser. What are the steps to achieve that? Should I use Ajax to make a request from time to time in order to populate the data? Is it possible to achieve this by using only the Tweepy library? Thanks, Adrian -
NoReverseMatch at /app/detail/3/
I got an error,NoReverseMatch at /app/detail/3/ Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['app/detail\/(?P[0-9]+)\/$'] . I wrote in views.py def top(request): content = POST.objects.order_by('-created_at')[:5] page = _get_page(blog_content, request.GET.get('page')) return render(request, 'top.html',{'content':content,"page":page}) class DetailView(generic.DetailView): model = POST template_name = 'detail.html' in top.html <div> {% for content in page %} <h2>{{ content.title }}</h2> <p><a href="{% url 'detail' content.pk %}">SHOW DETAIL</a></p> {% endfor %} </div> in detail.html <div> <h2>Comment List</h2> <a href="{% url 'detail' pk %}">Comment</a> {% for comment in post.comment_set.all %} Name:{{ comment.name }} <br> Text:{{ comment.text }} <br> <a href="{% url 'recomment' comment.pk %}">Reply</a> <br> {% endfor %} </div> <div> <h2>Comment Form</h2> <form action="" method="POST"> {{ form.as_p }} {% csrf_token %} <button type="submit">Send</button> </form> </div> When I access top.html, web site is shown correctly , so it is ok. But when I put SHOW DETAIL links, this error happens. I really cannot understand why this error happens. -
Integrating pyejabberd with django api to make ejabberd user registration
i am using django rest framework for making API. I have to integrate django with ejabberd xmpp to register users with ejabberd and get thier jabber id (JID). I came across pyejabberd which provided fucnctionality to register user with ejabberd. I need to know how to integrate it with my django project . The link to pyejabberd is - https://pypi.python.org/pypi/pyejabberd I tried to include it in installed apps to to use it after importing. I am also not sure whether we can use pyejabberd with django or not. Any help will be highly appreciated . Is there any other library to use if we want to register users with ejabberd and obtain JID in django -
Divs with similar structure would all act when only clicked on one
I use div to show a heading and a paragraph. I include a thumb up image on the bottom right corner. My intent is that when thumb up is clicked, it will change color and scale. However, with my code, when click on one thumb up, all thumbs would act the same way. I'm using Django template, here is a mock-up. I think something is wrong with my js file, please let me know how to fix it. Many thanks. var $icon = $(".icon"); $icon.on('click', function() { if ($icon.closest("div").hasClass('anim')) { $icon.closest("div").removeClass('anim'); } else { $icon.closest("div").addClass('anim'); } }); .icon-wrapper { position: absolute; bottom: 0; right: 0; padding: 10px; text-align: center; cursor: pointer; display: inline-block; } .icon-wrapper .icon { color: #90A4AE; } .icon-wrapper i { transform: scale(1); } .icon-wrapper.anim .icon { color: #39CCCC; } .icon-wrapper.anim i { animation: icon-animation cubic-bezier(0.165, 0.84, 0.44, 1) 1.2s; } @keyframes icon-animation { 0% { transform: scale(0); } 100% { transform: scale(1); } } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="things"> <div class="thing"> <div class="icon-wrapper"> <span class="icon"><i class="fa fa-thumbs-up"></i></span> </div> <h2>Wachet auf, ruft uns die Stimme</h2> <p>Wachet auf, ruft uns die Stimme (Awake, calls the voice to us),[1] BWV 140,[a] also known as Sleepers Wake, is a church cantata by … -
super function in Python
Wrt to the code snippet below, why is super().__init__ used in the model? How does it work? model.py class DuckForm(forms.ModelForm): class Meta: model = Duck fields = ('description', 'name') def __init__(self, community, *args, **kwargs): super().__init__(*args, **kwargs) self.community = community def save(self, commit=True): duck = super().save(commit=False) if not duck.community_id: duck.community = self.community if commit: duck.save() return duck views.py def add_duck(request): if request.method == 'POST': form = DuckForm(request.animal.community, data=request.POST) if form.is_valid(): duck = form.save() return redirect('DuckData') else: form = DuckForm(request.user.community) return TemplateResponse(request, 'MyDuck.html', {'form': form}) -
How can I define my metrics for test on django?
I need to define some metrics for my tests in my application. So I need to my application only deploy if the minimum for my code coverage was 50%, like I defined. So if my tests doesn't pass, my deploy will stop (I use Travis CI for my automation deployment) I use Django for my tests. It's possible? -
Nothing is shown in detail.html
Nothing is shown in detail.html. I wrote in views.py def top(request): content = POST.objects.order_by('-created_at')[:5] page = _get_page(blog_content, request.GET.get('page')) return render(request, 'top.html',{'content':content,"page":page}) class DetailView(generic.DetailView): model = POST template_name = 'detail.html' in top.html <div> {% for content in page %} <h2>{{ content.title }}</h2> <p><a href="{% url 'detail' content.pk %}">SHOW DETAIL</a></p> {% endfor %} </div> in detail.html <h2>{{ POST }}</h2> <p>{{ POST.text }}</p> in urls.py urlpatterns = [ path('top/', views.top, name='top'), path('detail/<int:pk>/', views.DetailView.as_view(), name='detail'), ] When I access top.html, web site is shown correctly , so it is ok. But when I put SHOW DETAIL links, nothing is shown. I really cannot understand why detail.html does not show model's content.How should I fix this?What is wrong in my code? -
How to SELECT a field from a LEFT JOIN'ed table/model with Django's ORM (1.11)
Context: Using Django Rest Framework, I've created a ModelViewSet. I'm overriding the list() method to customise the query as explained below. With these models: class Claim(models.Model): permalink = models.SlugField(max_length=255, blank=True, unique=True) author = models.ForeignKey(get_user_model(), db_index=True, on_delete=models.SET_NULL, null=True, blank=True) deleted = models.BooleanField(db_index=True, default=False) collaborators = models.ManyToManyField(get_user_model(), through='ClaimCollaborator', through_fields=('claim', 'user'), related_name='claims') # ...other fields class ClaimCollaborator(models.Model): claim = models.ForeignKey(Claim, db_index=True, on_delete=models.CASCADE) user = models.ForeignKey(get_user_model(), db_index=True, on_delete=models.CASCADE) access_project_only = models.BooleanField(default=True) I'm trying to query Claim to LEFT JOIN ClaimCollaborator and bring back the access_project_only field. ClaimCollaborator is actually an intermediary model handling the ManyToMany relationship between claims and users (collaborators of the claim). So far I have the following (cut down for brevity): class ClaimViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated, ) queryset = models.Claim.objects.all() serializer_class = serializers.ClaimSerializer lookup_field = 'permalink' def list(self, request): result = models.Claim.objects.filter(Q(author=request.user) | Q(claimcollaborator__user=request.user)) print(result.query) return JsonResponse(serializers.ClaimSerializer(result, many=True, context={'request': request}).data, safe=False) Listing produces this SQL: SELECT "api_claim"."permalink", "api_claim"."author_id", "api_claim"."deleted" LEFT OUTER JOIN "api_claimcollaborator" ON ("api_claim"."id" = "api_claimcollaborator"."claim_id") WHERE ("api_claim"."author_id" = 39 OR "api_claimcollaborator"."user_id" = 39) So I'm getting the LEFT JOIN on "api_claimcollaborator" (ClaimCollaborator) just fine, but none of the fields. I've tried .only(, 'claimcollaborator__access_project_only') and .selected_related('claimcollaborator') on the query but this just produces errors (I can be more specific about … -
Slug field from foreignkey in admin
when I select a Community from a dropdown menù I want the community name to appear in the slug field. Mymodel.py: class Province(models.Model): community = models.OneToOneField(community.Community, null=True, on_delete=models.PROTECT) slug = models.SlugField(unique=True) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Myclass, self).save(*args, **kwargs) class Community(models.Model): name = models.CharField(max_length=16, unique=True) My admin.py: class ProvinceAdmin(admin.ModelAdmin): search_fields = ['community__name'] prepopulated_fields = {'slug': ('community',)} #prepopulated_fields = {'slug': ('community__name',)} #prepopulated_fields = {'slug': ('community.name',)} The search field is working like expected but the prepopulated_field isn't: the only working is the first solution, but the slug is the id and not the name. The other solutions give this error message: <class 'core.admin.ProvinceAdmin'>: (admin.E030) The value of 'prepopulated_fields["slug"][0]' refers to 'community__name', which is not an attribute of 'core.Province'. Thank you -
Django Viewflow basic questions
Here are few questions i am searching answers for: 1. Difference between BPMN and pure workflow. 2. Can we integrate any system or it has to be Django based? 3. If we want to set up life cycle of a process, Can we get the info which task is stuck at which stage? 4. How much development effort would require to set up a simple workflow? It would be really helpful if anyone could help me with this. -
Django: How to serial a subset of fields in a model instance?
I was wondering if there is a way of serializing (into Json) a subset of all fields in all instance of a model. An example instead of having for a cinema everything that relates to each cinema like seats, screening , movies and so on. Just cinema name and location coordinators. Thank you for your time. Only using vanilla django.