Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
get last seven month list and last seven weeks list in python
I am new to python and django framework so please help me. if present week number is 41 (10/10/2019) so last seven weeks means 40, 39,38,37,36,35,34 etc if present week number is 1 then need last year weeks numbers and also for months. This all for me to get the last 7 weeks day and the last 7 months data Thank you -
gunicorn v job queue in django
In Django webapp that's deployed, I get request in views.py As soon as post request is received, I modified post function to do certain action and deliver results in views.py def post(self, request, *args, **kwargs): #do some action #deliver results to 1.1.1.1 In this case, I'm currently running task as the request comes. For instance, if 5 requests come in at once, it's currently processing one by one. But, I'd like to process all requests at once(assuming there are enough server load) and deliver results back. Would increasing workers in gunicorn solve the issue of concurrency or would it be better to utilize job queue like celery? If gunicorn is enough, how many workers would need to be set? And what is best practice method? -
How to fix "ImportError at / cannot import name "bar" " for the HelloWorldApp example?
I am a newbie in Django. last week, I did all the steps for running the HelloWorld example by this tutorial: http://taswar.zeytinsoft.com/visual-studio-code-with-python-django/ which worked perfectly. However, I was trying to run it today, and it is not working. when i run: "python manage.py runserver", I got the message of "0 error found", but in the browser I have the following error: Exception Type: ImportError Exception Value: cannot import name bar can anyone please help me? need to mention that I tried all posted answer into the similar question, but the problem is still there!! Thanks -
Django : TypeError: 'ListSerializer' object is not iterable
I'm posting multiple values to my "KeyboardEventView" ModelViewSet. The post is successful and I can see the data in the database getting logged correctly. However, I'm getting an error thrown from Django, ... TypeError: 'ListSerializer' object is not iterable This is driving me nuts. It works, but it's bothersome to see errors get thrown. Anyone else experiencing this? -----Views.py----- class KeyboardEventView(viewsets.ModelViewSet): queryset = KeyboardEvent.objects.all() serializer_class = KeyboardEventSerializer def get_serializer(self, *args, **kwargs): if "data" in kwargs: data = kwargs["data"] # check if many is required if isinstance(data, list): kwargs["many"] = True return super(KeyboardEventView, self).get_serializer(*args, **kwargs) -----Models.py----- class KeyboardEvent(models.Model): value = models.CharField(max_length=15) time = models.DateTimeField(auto_now=True) user_id = models.ForeignKey(UserData,on_delete=models.CASCADE) def __str__(self): return self.value -
How to call custom function inside generic class base view
How to call the custom function in update function, my views is this- class StokeBulkUpdate(generics.APIView): ...... def custom_function(list): return list def update(self, request,*args,**kwargs): data = self.request.data custom_function -
See if Django form submission came from the admin
I'm new to django, so I apologize if this has been asked. I'm using the post_save signal to run a task when a new object is created. I need to be able to check if the form was submitted from the admin page or if it was submitted on the live website, is this possible? Where might I find documentation on this? -
Why doesn't this Django filter by 'annotate' variable work?
I have this queryset in Django: obj = Obj.objects.annotate(duration = F('date_end') - F('date_start')).order_by('duration') The following works perfectly: obj[0].duration obj.aggregate(Sum('duration'))['duration__sum'] However filtering doesn't work in this case even though documentation says that it should: obj = obj.filter( duration__gte = <a_class_datetime.timedelta> ) # doesn't work obj = obj.filter( duration = 1 ) # doesn't work This is the error I am getting: TypeError: expected string or bytes-like object My way to bypass this issue is to loop through the dataset - which is huge. Any tips as to why this is not working? -
ModuleNotFoundError: No Module named 'django' when trying to run makemigrations
I have taken over maintenance of a deployed Django app that is used by employees. I have made minor changes here and there and I only had to restart the apache to implement the changes. For the first time, I have to add an integerfield model to one of the pre-existing models. This said value is already in the DB with default value of 0 for all rows. All I want to do is add it as one of the fields in one of the models but when I try to run sudo python3 manage.py makemigrations in the virtual environment, I get ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback(most recent call last): File "manage.py", line 14, in <module> ) from exc As the app is currently running fine, why am I receiving this error? If this is not how you apply changes in the model field in the live server, how else are you supposed to do it? Thank you so much! -
In Django, How to gather dynamic input forms entry?
In django, I was able to create add and delete rows via js. How to add those rows of data into django DB. It only saves last row entry. Here is the following code. VIEW: def dynamicRow(request, *args, **kwargs): form = Add_Form(request.POST or None) template_name = 'addentry.html' if request.method == 'POST': if form.is_valid(): no_of_rows = int(request.POST.get('totalnum')) print(no_of_rows) list_of_rows = [Add_Form() for i in range(no_of_rows)] args = {'forms': list_of_rows} for i in args['forms']: print(i) ## only prints last entry i = Add_Form(request.POST) task = i.save(commit=False) task.save() messages.success(request, 'Successfully stored data into database.') else: messages.error(request, form.errors) else: form = Add_Form() return render(request, template_name, {'form': form }) HTML: <form id="add_data" role=form method="POST" class="post-form" action="">{% csrf_token %} <div class="container"> <table id="table" class=" table order-list"> <thead class="thead-light"> <tr> <th scope="col">Device#</th> <th scope="col">Name</th> </tr> </thead> <tbody> <tr> <td class="col-sm-4"> <input type="mail" name="device" class="form-check"/> </td> <td class="col-sm-4"> <input type="mail" name="name" class="form-check"/> </td> <td class="col-sm-2"><a class="deleteRow"></a> </td> </tr> </tbody> <tfoot> <tr> <td colspan="5" style="text-align: left;"> <input type="button" class="btn btn-lg btn-block " id="addrow" value="Add Row" /> </td> </tr> </tfoot> </table> <div class="row"> <div align="center" class="col"> <h4>Number of Rows: </h4> <input name="totalnum" id="totalnum" class="form-control" type="text" maxlength="2"></input> </div></div> </div> <!-- container --> <br><br> <div class="row "><div class="col"> <button type="submit" name="submit" class="btn">Submit</button><p><p> … -
Add new context variable in get_queryset
I've a page that shows the will show the monthly revenue, according to what user selects as month. In HTML there is a with all the possible inputs. Now in my I'm returning a new variable for use in the template, **not a queryset**. I just want to put `{{ revenue }}` in the template. I've read that I don't need to send a post, only with a get I can achieve this. So I've set up this form to capture selected month, but I'm getting: TypeError at /ordenes/ingresos unhashable type: 'slice' How should I set the context in the get_queryset method? Views.py class OrdersListView(ListView): model = Order template_name = "order/revenue.html" paginate_by = 10 def get_queryset(self): filter_month = self.request.GET.get('filtromes', '0') order = self.request.GET.get('orderby', 'created') context = {} if filter_month == "0": paid_orders = Order.objects.filter(status = 'recibido_pagado') revenue = 0 for order in paid_orders: revenue += order.total - order.shipping_cost context['revenue'] = revenue return context else: paid_orders = Order.objects.filter(created__month=filter_month).filter(status = 'recibido_pagado') #orders_shipping = Order.objects.filter(created__month=9).filter(status = 'recibido_pagado') revenue = 0 for order in paid_orders: revenue += order.total - order.shipping_cost context['revenue'] = revenue return context def get_context_data(self, **kwargs): context = super(OrdersListView, self).get_context_data(**kwargs) #filter_month = self.request.GET.get('filtro_mes', '0') context['filtromes'] = self.request.GET.get('filtromes', '0') context['orderby'] = self.request.GET.get('orderby', 'created') … -
I am getting unformulated Modal form for my Edit form in Django
I am new to Python and tying to create my first project, to add/edit/delete customers I have successfully done my first move which is the listing and crating parts but when i arrive to the editing part i hanged there, and could not know how to fix it So, would someone help me to fix this issue Thanks My Form customerform.py from .Customers import Customer,City, Region from TARGET.bootstrap_modal_forms.forms import BSModalForm class CustomerForm(BSModalForm): class Meta: model = Customer ` My Model Customers.py class Customer(models.Model): SMALL = 1 MEDIUM = 2 BIG = 3 CUST_SIZE = ( (SMALL, 'Small Business'), (MEDIUM, 'Medium Business'), (BIG, 'Larg Business'), ) name = models.CharField(max_length=50) description = models.CharField(max_length=100, blank=True) account_id = models.CharField(max_length=30, blank=True) account_executive_id = models.CharField(max_length=30, blank=True) customer_size = models.PositiveSmallIntegerField(choices=CUST_SIZE) branches = models.IntegerField(blank=True, null=True) country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True) region = models.ForeignKey(Region, on_delete=models.SET_NULL, null=True) city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) address = models.CharField(max_length=100, blank=True) credit_limit = models.IntegerField(blank=True, null=True) payment_term = models.CharField(max_length=30, blank=True) libility = models.IntegerField(blank=True, null=True) timestamp = models.DateField(auto_now_add=True, auto_now=False) def get_absolute_url(self): return reverse("contacts", kwargs={"id": self.id}) def __str__(self): return self.name ` My Url url.py from django.urls import path from . import views from django.conf.urls import url from .views import (customers_view,dashboard_view,leads_view,opportunities_view,product_details_view,channel_details_view) app_name = "crm" urlpatterns = [ path("contacts/", view=product_details_view, … -
Using YAML file as data source in Django
I'm using django and django-rest-framework. I have a YAML file that represents a database. Every object has an id and data. I want to be able to use the data as a resource in drf. I don't need to create new objects and save them, I just need to read it. Am I supposed to use fixtures for this? Or is there a better way. -
Django Rest Framework: two viewsets for one router
I want to have TWO DIFFERENT viewsets (for example, one implements only the GET method, the other implements only the POST method), but which will have the same url: GET /tournament/ - returns concrete object of the model Tournament; POST /tournament/ - create object of the model Tournament. But it is important that they must have the same url /tournament/! I trying something like this: models.py class Tournament(Model): ... viewsets.py class PublicTournamentEndpoint( mixins.RetrieveModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet ): queryset = Tournament.objects.all() authentication_classes = [] # empty! class PrivateTournamentEndpoint( mixins.CreateModelMixin, viewsets.GenericViewSet ): queryset = Tournament.objects.all() authentication_classes = ['SomeAuthBackend'] # not empty! routers.py class TournamentRouter(SimpleRouter): routes = [ Route( url=r'^{prefix}/tournament/$', mapping={ 'get': 'retrieve', 'post': 'create', }, name='{basename}', detail=True, initkwargs={}, ), urls.py tournament_router = TournamentRouter() tournament_router.register( 'tournaments', PublicTournamentEndpoint, basename='tournaments', ) tournament_router.register( 'tournaments', PrivateTournamentEndpoint, basename='tournaments', ) urlpatterns += tournament_router.urls But my urlpatterns has next values: [ <URLPattern '^tournaments/tournament/$' [name='tournaments']>, <URLPattern '^tournaments/tournament/$' [name='tournaments']> ] and so when I send a POST /tournament/ request, I get the following error: 405 "Method \"POST\" not allowed." because the first match url does not have a POST method, but only GET. How can i resolve this problems? Thank you! -
How can I relate some, but not all, models to users using Django?
I have a project which includes two different apps: users and school. In my current implementation, the users app contains a custom user class derived from Djagno's AbstractUser. It defines allowed user types as student or teacher, and the user must select one during registration. The school app contains a classroom model which I need to relate to students and one or more teachers. I have two main problems here. The first is regarding how to relate the classroom model to only specific users restricting their access based on their user type. I have tried using a ManyToManyField relation in the classroom model in order to associate the instance with the user who created it (and then I would later allow the user to add students). It appears I don't understand this field correctly -- it actually all users to all classroom instances. This obviously does not meet my requirement to restrict access among different classroom instances. OneToOneField and ForeignKey do not seem to meet my needs either. I have tried adding those fields to my user, but then I am restricted to a single classroom per user which is not acceptable either. I have also played around with creating … -
How do I create a queryset to display products that are linked to a category, that is shown by each category slug?
I have a product model and a productcategory model. The products are linked to the productcategory by a category attribute. I want to create a query that displays ONLY products that are in a category, when the webpage is displayed for that specific category. The way I have my views currently setup, I get an attribute error, saying the view has no attribute of slug. Models: class ProductCategory(models.Model): title = models.CharField(max_length=200) slug = models.SlugField() parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.PROTECT) class Product(models.Model): title = models.CharField(max_length=100) category = models.ForeignKey(ProductCategory, related_name='ProductsCategory', null=True, blank=True, on_delete=models.CASCADE) slug = models.SlugField(blank=True) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=6) image = models.ImageField(upload_to='products/', null=True, blank=True) Views: class ProductListView(ListView): look_up = 'slug' template_name = 'products/products.html' def get_queryset(self, *args, **kwargs): category = ProductCategory.objects.get(self.slug) products = Product.filter(category=category) return products -
How to set a variable inside for loop inside template in Django2.1?
I have a context dictionary containing data to be passed into the template. I need to toggle two divs based on some flag variable which I have implemented using {% with %} Django template tag. However, when I try to set the variable using {% set %} syntax I am getting following error:- set', expected 'endwith'. Did you forget to register or load this tag? I following the solution given here but it gives me error. index.html {% with flag=1 %} {% for benefit in content.benefits %} <div style="background-color: #fff;" class="row mt-5"> {% if not flag %} <div class="col-lg-4 col-md-4 col-sm-12"> <img src="{% static "{{benefit.image}}" %}" alt="tablet" class="img-responsive mx-auto mt-5 w-100 h-75 h-md-50 working-img"> </div> {% endif %} <div class="col-lg-8 col-md-8 col-sm-12 h-100"> {% for desc in benefit.heading %} <div class="d-flex h-25 w-100 m-1 mt-4"> <div class="col-3 col-sm-2 h-100"> <div class="mx-auto"> <i class="fas fa-check fa-2x" style="color: #6fe33d"></i> </div> </div> <div class="col-9 col-sm-10"> <div class="d-flex flex-column"> <div class="working-caption font-weight-bold">{{ desc }}</div> {# <div class="py-2 working-description-courses text-muted">{{ description }}</div>#} </div> </div> </div> {% endfor %} </div> {% if flag %} <div class="col-lg-4 col-md-4 col-sm-12"> <img src="{% static "{{benefit.image}}" %}" alt="tablet" class="img-responsive mx-auto mt-5 w-100 h-75 h-md-50 working-img"> </div> {% endif %} </div> … -
How can run multiple celery tasks in parallel?
I have a two tasks. @app.task def run2(): while True: print(1) time.sleep(5) return HttpResponse('ok') @app.task def run3(): while True: print(2) time.sleep(2) return How can I run these two tasks at the same time from the same console, from one command (preferably with a different number of workers). -
Mutation not working with django graphene - AttributeError refers to non-existent attribute
I'm making project with Django and graphene-django. I have the following models: from django.db import models class Address(models.Model): class Meta: verbose_name_plural = "Addresses" number = models.CharField(max_length=4) street = models.CharField(max_length=100) city = models.CharField(max_length=100) postcode = models.CharField(max_length=7) class Person(models.Model): class Meta: verbose_name_plural = "Persons" avatar = models.ImageField(upload_to='images/avatars/') first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) address = models.ForeignKey(Address, on_delete=models.CASCADE) personal_image = models.ImageField(upload_to='images/personal_images/') def get_fullname(self): return self.first_name + ' ' + self.last_name My root schema is: import people.person.schema import graphene from graphene_django.debug import DjangoDebug class Query( people.person.schema.Query, graphene.ObjectType, ): debug = graphene.Field(DjangoDebug, name="_debug") class Mutations( people.person.schema.Mutations, graphene.ObjectType, ): debug = graphene.Field(DjangoDebug, name="_debug") schema = graphene.Schema(query=Query, mutation=Mutations) And my app schema is: import graphene from graphene_django.types import DjangoObjectType from .models import Person, Address class PersonType(DjangoObjectType): class Meta: model = Person class AddressType(DjangoObjectType): class Meta: model = Address class Query(object): person = graphene.Field(PersonType, id=graphene.Int(), first_name=graphene.String()) all_persons = graphene.List(PersonType) address = graphene.Field( AddressType, id=graphene.Int(), name=graphene.String() ) all_addresses = graphene.List(AddressType) def resolve_all_persons(self, context): return Person.objects.all() def resolve_all_addresses(self, context): # We can easily optimize query count in the resolve method return Address.objects.select_related("person").all() def resolve_person(self, context, id=None, firstName=None, lastName=None): if id is not None: return Person.objects.get(pk=id) if firstName is not None: return Person.objects.get(first_name=firstName) if lastName is not None: return Person.objects.get(first_name=firstName) return … -
Error: django.db.utils.OperationalError: FATAL: password authentication failed for user "mydatabaseuser"
This is the full error I am recieving: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/site-packages/psycopg2/init.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: password authentication failed for user "mydatabaseuser" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check_migrations() File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/core/management/base.py", line 453, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/migrations/executor.py", line 18, in init self.loader = MigrationLoader(self.connection) File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/migrations/loader.py", line 49, in init self.build_graph() File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/migrations/recorder.py", line 73, in applied_migrations if self.has_table(): File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/migrations/recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/base/base.py", line 256, in cursor return self._cursor() File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/base/base.py", line 233, in _cursor self.ensure_connection() File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/utils.py", line … -
Default Manager "Objects" is not working for me
I'm very new in Python & Django and I'm following a tutorial but for some reason, a similar exercise I'm trying to do is not working for me. I'm creating a simple views.py and a simple class MissingBusiness. Trying to refer to the "objects" default manager for the model class is not recognized. I want to use MissingBusiness.objects.all() to get all records from the database. How to make objects to be recognized? This is my views.py from django.http import HttpResponse from django.shortcuts import render from .models import MissingBusiness def indexRoot (request): **BusinessList = MissingBusiness.objects.all()** return render(request,'index.html') This is my models.py from django.db import models class MissingBusiness(models.Model): businessName = models.CharField(max_length=255) category = models.IntegerField() Seems the default manager "objects" is not recognized for some reason. getting an error: AttributeErrorat /ManageMissingBusinesses/ 'function' object has no attribute 'objects' Request Method: GET Request URL: http://localhost:59564/ManageMissingBusinesses/ Django Version: 2.2.5 Exception Type: AttributeError Exception Value: 'function' object has no attribute 'objects' Exception Location: C:\Python\BankAccountUI\BankAccountUI\ManageMissingBusinesses\views.py in indexRoot, line 7 Python Executable: C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\python.exe Python Version: 3.6.3 Python Path: ['C:\Python\BankAccountUI\BankAccountUI', 'C:\Python\BankAccountUI\BankAccountUI', 'C:\Program Files (x86)\Microsoft Visual ' 'Studio\Shared\Python36_64\python36.zip', 'C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\DLLs', 'C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib', 'C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64', 'C:\Program Files (x86)\Microsoft Visual … -
How to redirect user to a URL when he choce from dropdown Form Django?
i am working on a form that i integrated with facebook pixel, and i have a Dropdown nationality field with two choices (Khaleegy - not khaleegy) when user submitting a form redirect him to Thanks_page.html but i when the user choice (Khaleegy) he redirect to Thanks_page.html that have a facebook pixel code - and when he choice (not khaleegy) he redirect to another Thanks_page this is a Form models.py class User(models.Model): first_name = models.CharField(max_length=100) second_name = models.CharField(max_length=100) E_mail = models.EmailField(max_length=254) COUNTRY_CHOICES = [('saudi arabia +966','SAUDI ARABIA +966'), ('oman +968','OMAN +968'), ('kuwait +965','KWUAIT +965'), ('Qatar +948','QATAR +948')] country = models.CharField(max_length=250, choices=COUNTRY_CHOICES, null=True) phone = models.IntegerField(null=True) phone_code = models.IntegerField(null=True) birthday = models.IntegerField(null=True) NATIONALITY_CHOICES = [('not khaleegy','Khaleegy'), ('not khaleegy','Khaleegy')] nationality = models.CharField(max_length=250, choices=NATIONALITY_CHOICES, null=True) def __str__(self): return self.first_name forms.py class UserForm(forms.ModelForm): class Meta: model = User fields = ('first_name', 'second_name', 'E_mail', 'country', 'phone', 'phone_code','birthday', 'nationality',) widgets = { 'first_name': forms.TextInput(attrs={'placeholder': 'الاسم الاول'}), 'second_name': forms.TextInput(attrs={'placeholder': 'الاسم الثاني'}), 'E_mail': forms.EmailInput(attrs={'placeholder': 'joe@schmoe.com'}), } views.py def form_page(request): if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): form.save() return redirect('LandingPage:thank_you') else: form = UserForm() posts = Article.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'LandingPage/form_page.html', {'form': form, 'posts': posts}) # Thank you page. def thank_you(request): return render(request, 'LandingPage/thank_you_page.html', {}) url.py urlpatterns = [ … -
Django object related and manyTomany, prefetch_related?
I have three models: class Season(models.Model): name = models.CharField(max_length=512) class Clothes(models.Model): season = models.ForeignKey(Season, related_name='season_clothes', on_delete=models.CASCADE) name = models.CharField(max_length=512) class User(models.Model): name = models.CharField() clothes = models.ManyToManyField(Clothes) How How can I get User's all clothes with season in template, if I know for which User this request. Something like this: Winter - (It's a Season name) Сoat - (name of clothes) Scarf - (name of clothes) Boots - (name of clothes) Summer - (It's a Season name) Shorts - (name of clothes) Swimming trunks - (name of clothes) Sneakers - (name of clothes) -
How can I query fields of a one to many related object?
So if I have model Run and ExceutedTestResults class Run(TimeStampedModel): RUN_TYPE_CHOICES = ( (MANUAL_RUN, 'Manual'), (AUTOMATED_RUN, 'Automated'), ) run_type = models.CharField(max_length=1, choices=RUN_TYPE_CHOICES) class ExecutedTestResult(Duration): """Lists the results of every test case executed.""" run = models.ForeignKey(Run, on_delete=models.CASCADE, related_name='run_results') RESULT_TYPE_CHOICES = ( ('P', 'Passed'), ('F', 'Failed'), ('N', 'No Run'), ('B', 'Blocked'), ) result = models.CharField(max_length=1, choices=RESULT_TYPE_CHOICES) I want to create a queryset method in class RunQuerySet(QuerySet): which would return a queryset of runs that are all passed/no run within a single run I'm not sure how to do this on a one to many relationship. Suggestions? -
Django apps shared python api client
Let's say I have an external python client that I use as a data source. Let's call it api. It's a pretty standard API, so creating a session object is easy and allows you to connect to the data source. I have a few Django apps that will depend on this api, and I'd like to have as few handles to this api per site as possible (one per process I'm guessing). I was thinking of two approaches: Write a non Django slim wrapper around my API implementing the singleton pattern, with one session object per site. Use it in my Django apps. Write a Django app with a custom signal that sends the instance once connected. It's one of these the best approach, or is there a more ad hoc way? -
Django / Jinja2: How do I extend a variable name dynamically with the value of another variable (e.g. in a for-loop)?
In my django db model I have e.g. 5x ImageField, which I want to use for a carousel in the front end: slider_image_1 = models.ImageField(upload_to='images/', blank=True) slider_image_2 = models.ImageField(upload_to='images/', blank=True) slider_image_3 = models.ImageField(upload_to='images/', blank=True) slider_image_4 = models.ImageField(upload_to='images/', blank=True) slider_image_5 = models.ImageField(upload_to='images/', blank=True) Depending whether the images were uploaded or not, I want to display the images and I am looking for an approach similar to something like this: {% for FOO in range(5) %} {% if object.slider_image_|extend_name_with:FOO %} <img src="{{ object.slider_image_|extend_name_with:FOO.url }}"> {% endif %} {% endfor %} Is something similar possible? What are other good approaches for this problem?