Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Retrieve or get data from selected foreign key field
Relatively new to Django, I'm working on a Django project and attempting to retrieve particular foreign key object into variable when it's selected in Form. model.py class item_category(models.Model): idItemCat = models.CharField(primary_key=True max_length=5) nameCategory = models.CharField(max_length=150) def __str__(self): return self.nameCategory class item_code(models.Model): idItemCat = models.ForeignKey(item_category, on_delete=models.DO_NOTHING) idItemCode = models.CharField(primary_key=True, editable=False, max_length=20) def __str__(self): return self.idItemCode I know I could retrieve object with making QuerySet such as .objects.last() and .objects.filter() or else, but it's just retrieve objects from database or existing data. What I'm about to do is, when a user submit a new data it'll retrieve particular foreign key object based on what I'm selected in this Form, so I could put into variable. Any idea how should do it? it would be so much appreciated. -
How can i check to see if a user is active using signals in django
Im trying to implement an online and offline functionality in my app in django and can't work out how to check to see if a user is logged in and active or offline and inactive in my app can anyone help me with implementing it please. -
Django: DB queries count optimization
I have models (one user can has multiple employees): from django.db import models class User(models.Model): username = ... first_name = ... last_name = ... class OrgUnit(models.Model): name = .... address = ... class Employee(models.Model): personnel_no = ... user = models.ForeignKey(User, related_name='employees'...) orgunit = models.ForeignKey(OrgUnit, ...) Serializers and views: class EmployeeSerializer(serializers.ModelSerializer): orgunit = serializers.CharField(source='orgunit.name') <==== one orgunit - one query to DB class Meta: model = Employee fields = '__all__' class CustomUserSerializer(serializers.ModelSerializer): employees = EmployeeSerializer(many=True) class Meta: model = User fields = '__all__' class UsersViewSet(ViewSet): def me(self, request): serializer = CustomUserSerializer(request.user) return Response(serializer.data) When serializing orgunit.name per one orgunit one query to DB is being performed. How to avoid this? How to prefetch employees related_name and its orgunits? -
django save method not changing attribute
Trying to use the save method to change the admin =True, on a user. But it is not changing. User models class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) first_name = models.CharField(max_length=55, null=True, blank=True) last_name = models.CharField(max_length=55, null=True, blank=True) phone_number = models.CharField(max_length=12, null=True, blank=True) delivery_info = models.ManyToManyField(Address, related_name='address_info', blank=True) is_active = models.BooleanField(default=True) verified = models.BooleanField(default=False) staff = models.BooleanField(default=False) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser And my class where i want to change the admin class Employee(models.Model): """ Main class containing the employee """ user = models.OneToOneField(User, related_name='employee', on_delete=CASCADE) # Every employee have to have an ID, that is unique slug = models.SlugField(max_length=255, unique=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.email # Using slug to id the employee and be able to have its own # profile page to change information def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.user) super(Employee, self).save(*args, **kwargs) class Manager(models.Model): """ Holding the manager/admin employee """ manager = models.ForeignKey(Employee, related_name='manager', on_delete=CASCADE) def __str__(self): return self.manager.user.email def save(self, *args, **kwargs): if self.manager: self.manager.user.admin = True self.manager.user.staff = True super(Manager, self).save(*args, **kwargs) But when adding user as a manager, it does not change the admin fields to True. -
Warning: Unexpected input(s) ..., valid inputs are [...] in GitHub Actions (full text in the answer body)
After github action running I got this warning: Unexpected input(s) 'stack_file_name', valid inputs are ['entryPoint', 'args', 'host', 'port', 'passphrase', 'username', 'password', 'sync', 'use_insecure_cipher', 'cipher', 'timeout', 'command_timeout', 'key', 'key_path', 'fingerprint', 'proxy_host', 'proxy_port', 'proxy_username', 'proxy_password', 'proxy_passphrase', 'proxy_timeout', 'proxy_key', 'proxy_key_path', 'proxy_fingerprint', 'proxy_cipher', 'proxy_use_insecure_cipher', 'script', 'script_stop', 'envs', 'debug'] From main.yml: runs-on: ubuntu-latest needs: build_and_push_to_docker_hub steps: - name: executing remote ssh commands to deploy uses: appleboy/ssh-action@master with: host: ${{ secrets.HOST }} username: ${{ secrets.USER }} key: ${{ secrets.SSH_KEY }} passphrase: ${{ secrets.PASSPHRASE }} stack_file_name: docker-compose.yaml script: | sudo docker pull ${{ secrets.DOCKER_USERNAME }}/foodgram sudo docker-compose stop sudo docker-compose rm web touch .env echo DB_ENGINE=${{ secrets.DB_ENGINE }} >> .env echo DB_NAME=${{ secrets.DB_NAME }} >> .env echo POSTGRES_USER=${{ secrets.POSTGRES_USER }} >> .env echo POSTGRES_PASSWORD=${{ secrets.POSTGRES_PASSWORD }} >> .env echo DB_HOST=${{ secrets.DB_HOST }} >> .env echo EMAIL_HOST=${{ secrets.EMAIL_HOST }} >> .env echo EMAIL_HOST_USER=${{ secrets.EMAIL_HOST_USER }} >> .env echo EMAIL_HOST_PASSWORD=${{ secrets.EMAIL_HOST_PASSWORD }} >> .env echo EMAIL_PORT=${{ secrets.EMAIL_PORT }} >> .env sudo docker-compose up -d sudo docker-compose exec -T web python3 manage.py makemigrations users --no-input sudo docker-compose exec -T web python3 manage.py makemigrations recipes --no-input sudo docker-compose exec -T web python3 manage.py migrate --no-input sudo docker-compose exec -T web python3 manage.py collectstatic --no-input sudo docker-compose restart sudo docker-compose exec -T … -
Best practice to show complex Json on the browser in javascript
I want to show the json object as tree like UI in browser. At first I try this [jqTree][1] However it requires that json will be this style { name: 'node1', children: [ { name: 'child1' }, { name: 'child2' } ] }, Without name childeren node , no tree appars. However my style is more complex and different node name. { title: 'node1', choices: [ { title: 'child1' , choices:[] }, { title: 'child2' choices:{ "answers":[1,2,4] } } ] }, Is there any good method to show more flexible json?? -
django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError ... No module named 'django.core.urlresolvers'
The following error is happening when trying to deploy it using dokku. can any body tell me the reason, my environment is the following. python3.6 Django3.0 DRF3.11 Below is the log -
Bulk Create instances using same info but different photos in django admin?
I'm working with this Media model: class Media(AbstractCreatedUpdatedDateMixin): uuid = models.UUIDField(unique=True, default=uuid4, editable=False, db_index=True) user = models.ForeignKey(User, related_name="uploaded_media", on_delete=models.CASCADE) title = models.CharField(max_length=255) location = models.PointField() image = models.ImageField(upload_to=uuid_directory_path) category = models.CharField(max_length=9, choices=ContentType.choices()) In some cases multiple photos represent the same thing, so the values of user, title, location and category will be the same, and I need this functionality in the admin page. I've created a widget to allow multiple ImageField in the Creation Form: class BulkImageWidget(widgets.MultiWidget): def __init__(self, attrs=None): _widgets = ( widgets.FileInput(attrs=attrs), widgets.FileInput(attrs=attrs), widgets.FileInput(attrs=attrs), widgets.FileInput(attrs=attrs), widgets.FileInput(attrs=attrs), ) super().__init__(_widgets, attrs) def decompress(self, value): if value: return [object for object in value] return None def value_from_datadict(self, data, files, name): return data This was just a test, actually, I'd need this widget to be loaded dynamically, and not be limited to only 5 photos at once. In the Admin I've overridden the formsets related to the Image field: formfield_overrides = { PointField: {'widget': LocationWidget, "label": _("Location (lng, lat)")}, ImageField: {'widget': BulkImageWidget, "label": _("Images")}, } Then I've overridden the save_model function in the ModelAdmin, with an exception raise, in order to verify how was data structured so I could save the instances properly: class MediaAdmin(admin.ModelAmin): ... def save_model(self, request, obj, form, change): … -
TypeError: Object of type Folder is not JSON serializable in Django Rest framework
I am using a property decorator for a field and have put that field into the serializer meta class but keeps getting that error. I am not sure what is the issue. My models: class Example(models.Model): creator = models.ForeignKey( User, on_delete=models.CASCADE, null=True, related_name="example" ) @property def example_packages(self): return self.package.all() class Package(models.Model): parent = models.ForeignKey( Example, on_delete=models.CASCADE, null= True, related_name="package" ) name = models.CharField(max_length=25,blank=True) My serializers: class ExampleSerializer(serializers.ModelSerializer): class Meta: model = Example fields = ['id','creator','example_packages'] The error that I keep geeting is that example_packages is not Json serializable. -
using datefilter in forloop django does not work
dayone.inizio|date:"d" not working in forloop. how can i have only the data of the day in the form? if I call it normally it works but inside the forloop it doesn't go it doesn't take me the day but the whole date. From the views I can't because I also need other fields {% if giorno == dayone.inizio|date:"d" %}...{%endif%} -
How to make the instance inside Django form take multiple values?
I'm making a Django blog and I want to make the user edit his post. I have 2 forms to render, Post Form that includes (title, post image, content, category) and another separated form for the post tags that includes (tag name). To edit the tags I have to get all the tags related to the post and set them to the instance attribute which takes only one object (and I have multiple tags for one post). Here are my Models: class PostTags(models.Model): tag_name = models.CharField(max_length=100) def __str__(self): return self.tag_name class Post(models.Model): title = models.CharField(max_length=50) picture = models.ImageField(null=True,upload_to='images/') content = models.CharField(max_length=255) likes = models.ManyToManyField(User,blank=True,related_name='likes') dislikes = models.ManyToManyField(User,blank=True,related_name='dislikes') date_of_publish = models.DateTimeField(auto_now_add=True,null=True,blank=True) user = models.ForeignKey(User,on_delete=models.CASCADE) category = models.ForeignKey(Category,on_delete=models.CASCADE) tag = models.ManyToManyField(PostTags,blank=True) def __str__(self): return self.title Here are my Forms: class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title','picture','content','category'] widgets = { 'title': forms.TextInput(attrs={'class': 'form-control'}), 'picture': forms.FileInput(attrs={'class': 'form-control'}), 'content':forms.TextInput(attrs={'class': 'form-control'}), 'category' : forms.Select(attrs={'class':'form-control'}), } class TagsForm(forms.ModelForm): class Meta: model = PostTags fields = ['tag_name'] widgets = { 'tag_name': forms.TextInput(attrs={'class': 'form-control', 'data-role': 'tagsinput'}) } and here is my try to get all tags in the tags form in views.py def editPost(request,post_id): post = Post.objects.get(id= post_id) post_form = PostForm(instance=post) # tagInstance = [] for … -
Why pip not installing latest ersion of django
I tried to install django4.0.1 in ubuntu20.14 with virtual environment. pip install Django==4.0.1 It showing error as No matching distribution found for Django==4.0.1 Previously in the same OS django4.0.1 was installed, but why its not installing now? I tried many ways Now it's installing only django3.2.12. Suggest me a way to get latest version -
Blank space instead of input in django admin
What is the reason of such behavior? The field described like this: html = models.TextField(verbose_name='HTML', blank=True, default='') And nothing special in the admin of this model. -
Why celery module isn't available when running celery as a daemon with supervisor?
I'm trying to daemonize my project on VPS. If I am running the celery from command line as celery -A taxomat_api worker -B -l INFO or /var/www/html/taxomat/taxomat_api/venv/bin/celery --workdir=/var/www/html/taxomat/taxomat_api -A taxomat_api worker -B -l INFO or cd /var/www/html/taxomat/taxomat_api root@taxomat:/var/www/html/taxomat/taxomat_api# venv/bin/celery -A taxomat_api worker -B -l INFO everything works good, but now when I'm trying to run celery tasks as daemon with supervisor, I have an error Traceback(most recent call last): File "/var/www/html/taxomat/taxomat_api/venv/bin/celery", line 5, in <module> from celery.__main__ import main File "/var/www/html/taxomat/taxomat_api/celery.py", line4, in <module> ModuleNotFoundError: No module named 'celery.schedules'; 'celery' is not a package Here is my conf file /path /etc/supervisor/conf.d/celery.conf/ [program:deeptechx-celery] environment=PYTHONPATH="/var/www/html/taxomat/taxomat_api:$PYTHONPATH",DJANGO_SETTINGS_MODULE="taxomat_api.settings" command=/var/www/html/taxomat/taxomat_api/venv/bin/celery --workdir=/var/www/html/taxomat/taxomat_api -A taxomat_api worker -B -l INFO directory=/var/www/html/taxomat/taxomat_api user=root numprocs=1 stdout_logfile=/var/log/celery/worker.log stderr_logfile=/var/log/celery/worker.log autostart=true autorestart=true startsecs=10 stopwaitsecs = 600 killasgroup=true priority=1 My project tree is taxomat taxomat_api venv bin celery lib python3.8 taxomat_api settings.py celery.py workers tasks.py My celery.py file from __future__ import absolute_import, unicode_literals import os from celery.schedules import crontab from celery import Celery import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'taxomat_api.settings') django.setup() app = Celery('taxomat_api') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() On my local machine daemon works too. Can anybody help me? I have read docs, try many ways but the error is the same. -
Django admin: pivot table for through model?
I have 2 models: ecrf and calendar. These models are parameters models for app and set via django admin interfaces. class Ecrf(models.Model): ide = models.AutoField(primary_key=True) name = models.CharField("Nom du modèle",max_length=50, null=True, blank=True) class Calendar(models.Model): ide = models.AutoField(primary_key=True) timing = models.CharField("Timing",max_length=50, null=True, blank=True) class EcrfCalendar(models.Model): ecrf = models.ForeignKey(Ecrf, on_delete = models.CASCADE, related_name = "ecrf") calendar = models.ForeignKey(Calendar, on_delete = models.CASCADE, related_name = "calendar") expected = models.BooleanField() vis_typ = models.IntegerField('Visit type (live or phone)', null=True, blank=True) The ecrf model contains type of form that can be collected (eligibility, inclusion, visit). The calendar model contains timing when a form can be completed (Day -1, Day 0, Day 3, Week 1). Some forms are only completed at one timing: e.g. eligibility at Day -1 and inclusion at Day 0. Other forms can be completed at multiple timing: e.g. visit can be collected at Day 0, Day 3 and Week 1. ecrf and calendar models are linked with a manytomany relationship. I explicitly define the through model ecfcalendar. I could use inline forms for admin form but I would like to have a django admin form that enable user to "check" timing of form collection using a pivot table presentation (cf below). Is it possible? -
django find in field type json with value type int or str
I have a field type Json in a model, but I can't be sure if it's an integer or a string, the long version that works is: cars = Car.objects.filter( user_id=self.user_id, car_type=self.car_type, facture__facture_id=1, ) if len(cars) == 0: cars = Car.objects.filter( user_id=self.user_id, car_type=self.car_type, facture__facture_id=1, ) But I want to do not repeat all the block, and I want to know if there is another way like: Car.objects.filter( user_id=self.user_id, car_type=self.car_type, facture__facture_id=1 | facture__facture_id='1', ) -
django LOGGING - How to change filter attribute name by format
I have the following settings: LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' }, 'some_id': { '()': 'my.special.filter' }, }, 'formatters': { 'json': { '()': 'my.special.formatter', 'format': '%(thread)d\t%(message)s' }, ... the filter add "some_id" to the log so the output looks like this: {"thread": 140155333515008, "message": "some log msg", "some_id": "123456"} I want to modify the additional attribute "some_id", so the output would look like this: {"thread": 140155333515008, "message": "some log msg", "some-id": "123456"} I saw that it can be done with CustomAdapter but I have a lot of "logger = logging.getLogger(...)" so I cant use this. How can i change the output attribute name? -
Why Model Serializer is saving partial data?
class CreateWithIpMixin: def create(self, request, *args, **kwargs): created_by = request.user.id created_by_ip = request.META.get("REMOTE_ADDR") ############# creator_info = {'created_by': created_by, "created_by_ip": created_by_ip} data = {**request.data, **creator_info} serializer = self.get_serializer(data=data) ############# serializer.is_valid(raise_exception=True) serializer.save() headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) request.data = {'name': 'Delhi', 'display_name': 'Delhi', 'short_code': 'DL', 'is_approved': True} data = {'name': 'Delhi', 'display_name': 'Delhi', 'short_code': 'DL', 'is_approved': True, 'created_by': 4, 'created_by_ip': '127.0.0.1'} I'm passing complete data in the serializer but only getting request.data in my Serializer (validate method). The other two fields 'created_by' , 'created_by_ip' is present in my model but I want to fill these column automatically that's why I have not mentioned it in serializer fields , also I don't want to return it after saving the data. Serializer.py class StateSerializer(serializers.ModelSerializer): class Meta: model = States fields = [ "id", "name", "display_name", "short_code", ] def validate(self, attrs): print(attrs, "Attrs") return super().validate(attrs) -
Wagtail ajax request does not assume website lang
Im having a problem with ajax request in wagtail. I have installed Wagtail Modeltranslation and now I want to make ajax requests using Views.py but the problem is when I'm in the English version of the website it will always form the link with 'pt/'. Here's the code in URLS.py enter image description here And here is the Ajax Code: enter image description here Any tips to make this work? -
drf_yasg swagger library problem with django_elasticsearch_dsl_drf
Django drf_yasg swagger library seems to have problem with django_elasticsearch_dsl_drf. When I define a viewset of django_elasticsearch_dsl_drf.viewsets.DocumentViewSet the following error will rise in drf_yasg library. Anybody has ever encountered this problem? I did not find any related topic for this issue [2022-02-16 15:22:11] ERROR|django.request|Internal Server Error: /swagger/ Traceback (most recent call last): File "/home/hamed/PycharmProjects/boursrefsengine/venv/lib/python3.8/site-packages/asgiref/sync.py", line 451, in thread_handler raise exc_info[1] File "/home/hamed/PycharmProjects/boursrefsengine/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 38, in inner response = await get_response(request) File "/home/hamed/PycharmProjects/boursrefsengine/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 233, in _get_response_async response = await wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/hamed/PycharmProjects/boursrefsengine/venv/lib/python3.8/site-packages/asgiref/sync.py", line 414, in __call__ ret = await asyncio.wait_for(future, timeout=None) File "/usr/lib/python3.8/asyncio/tasks.py", line 455, in wait_for return await fut File "/home/hamed/PycharmProjects/boursrefsengine/venv/lib/python3.8/site-packages/asgiref/current_thread_executor.py", line 22, in run result = self.fn(*self.args, **self.kwargs) File "/home/hamed/PycharmProjects/boursrefsengine/venv/lib/python3.8/site-packages/asgiref/sync.py", line 455, in thread_handler return func(*args, **kwargs) File "/home/hamed/PycharmProjects/boursrefsengine/venv/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/hamed/PycharmProjects/boursrefsengine/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/hamed/PycharmProjects/boursrefsengine/venv/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/hamed/PycharmProjects/boursrefsengine/venv/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/hamed/PycharmProjects/boursrefsengine/venv/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/hamed/PycharmProjects/boursrefsengine/venv/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/home/hamed/PycharmProjects/boursrefsengine/venv/lib/python3.8/site-packages/drf_yasg/views.py", line 94, in get schema = generator.get_schema(request, self.public) File "/home/hamed/PycharmProjects/boursrefsengine/venv/lib/python3.8/site-packages/drf_yasg/generators.py", line 242, in get_schema endpoints = self.get_endpoints(request) File "/home/hamed/PycharmProjects/boursrefsengine/venv/lib/python3.8/site-packages/drf_yasg/generators.py", line 318, in get_endpoints … -
inline_formset auto_id starting from a custom number
Django user here. I want my first fields in my inline formsets start from a custom number, like 7 for example : <input type="text" name="prescriptiondetails-7-unit" maxlength="100" class=" form-control-sm form-control " id="id_prescriptiondetails-7-unit" value=""> <input type="text" name="prescriptiondetails-7-sqf" maxlength="100" class=" form-control-sm form-control " id="id_prescriptiondetails-7-sqf" value=""> ... here my view class add_prescriptiondetail_field_form_hx(AddMixin_hx): model = Prescription form_class = PrescriptionForm success_url = reverse_lazy('prescriptions:list_prescription') template_name = __name__.split(".")[-2] + '/' + 'prescriptiondetail_field_hx.html' wire_dict = wire_dict_init def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) formset_prefix = 'prescriptiondetails' context['formset_prefix'] = formset_prefix from django.forms.formsets import INITIAL_FORM_COUNT from .forms import PrescriptionDetailForm from .models import PrescriptionDetail form_set = PrescriptionDetailFormSet = inlineformset_factory(Prescription, PrescriptionDetail, form=PrescriptionDetailForm, fields = ['unit', 'sqf'], extra=0, max_num=10, min_num=1, can_delete=True ) context['prescriptiondetail'] = form_set # return context how can I tell django to start from count 7 and not render the form fields id and names from 0 NB : Not interested in JS solutions. I've been pulling my hair for a whole day, read the doc in and out ... but without luck thank you guys -
Former ManytoMany object is not added
I want to add a new passenger to the flight, and I use models to store that. But instead, it had absolutely no change after I submit the form, except for the unexpected URL change: from localhost:8000/flights/5 to localhost:8000/flights/5/book before after def book(request, flight_id): if request.method == "POST": flight = Flight.objects.get(pk=flight_id) passenger = Passenger.objects.get(pk=int(request.POST["passenger"])) passenger.flights.add(flight) return HttpResponseRedirect(reverse("flight", args=(flight.id,))) class Passenger(models.Model): first = models.CharField(max_length=64) last = models.CharField(max_length=64) flights = models.ManyToManyField(Flight, blank=True, related_name="passengers") Flight is another class, by the way. And there are my urlpatterns: urlpatterns = [ path("", views.index, name="index"), path("<int:flight_id>", views.flight, name="flight"), path("<int:flight_id>/book", views.flight, name="book") ] any idea why it's going wrong? Any help would be much appreciated. Thanks a lot! -
Calendar with added events from start date to end date in django
I have this hand crafted calendar I would like to add messages about the days when someone posts a new supplement. Integratore has name, start date and end date, I would like to carry the message from the start day to the end day. How can I do this? views def calendarioView(request): mesi = [ 'Gennaio', 'Febbraio', 'Marzo', 'Aprile', 'Maggio', 'Giugno', 'Luglio', 'Agosto', 'Settembre', 'Ottobre', 'Novembre', 'Dicembre' ] data = datetime.datetime.now() i = int(data.strftime("%m"))-1 mese = mesi[i] anno = int(data.strftime("%Y")) giorno_odierno = int(data.strftime("%d")) init = calendar.TextCalendar(calendar.MONDAY) integratori = Integrazione.objects.all() giorni = [] for day in init.itermonthdays(data.year, data.month): giorni.append(day) context = { 'mese': mese, 'anno': anno, 'giorni': giorni, 'giorno_odierno': giorno_odierno } return render(request, 'calendario.html', context) html <div class="giorni"> {% for giorno in giorni %} {% if giorno == 0 %} <div></div> {% else %} <div class="single-day{% if giorno == giorno_odierno %} oggi{% elif giorno < giorno_odierno %} vecchio{% endif %}"> {{ giorno }} {% if integratori %} <!-- <div class="integrazione"> <div> <img src="{% static 'img/integratori.svg' %}" class="img-fluid"> <h6 class="m-0">Proteine</h6> </div> <div> <img src="{% static 'img/integratori.svg' %}" class="img-fluid"> <h6 class="m-0">Creatina</h6> </div> </div> --> {% endif %} </div> {% endif %} {% endfor %} </div> </div> -
DRF - how to concatenate two different models in one .json api?
I have task to output to different models in one .json file So I need at the end two different models look like this on one api page: http://127.0.0.1:8000/cat_dog_api/ My goal output: [ { "dog_big": "Mastiff", "dog_small": "Terrier", "same_line": "different words 1", }, { "cat_big": "Singapura", "cat_small": "Maine Coon", "same_line": "different words 2", } ] Example models: class Cat(models.Model): cat_big = models.CharField(max_length=300) cat_small = models.CharField(max_length=300) same_line = models.CharField(max_length=300) class Dog(models.Model): dog_big = models.CharField(max_length=300) dog_small = models.CharField(max_length=300) same_line = models.CharField(max_length=300) I found out how to concatenate models with "chain" in one queryset Vies.py: from itertools import chain class Whole_test(generics.ListAPIView): serializer_class = Cat_dog_Serializer def get_queryset(self): return list(chain(Cat.objects.all(), Dog.objects.all())) But I'm stuck when time comes to serializer, I have to choose one model with serialiser, class Cat_dog_Serializer(serializers.ModelSerializer): class Meta: model = Cat fields = '__all__' but in this case it doesn't serealize my Dog model from my queryset Is there a way to achieve my goal, maybe a different approach from mine? -
Translation in Django 3.2
I was working in Django 2.2 and for setting up the current user's language I used the session: language = request.user.language request.session[LANGUAGE_SESSION_KEY] = language translation.activate(language) I just updated to Django 3.2 and I am having an issue with this. Apparently this way to set the language had been deprecated. Instead, I use the language cookie name: response = HttpResponse(...) response.set_cookie(settings.LANGUAGE_COOKIE_NAME, language) translation.activate(language) It is working but I need to set this cookie in every single view or even API GET functions to get the data in the expected language. I wonder if there is any way to set the language just once like I used to do. I want to set the language from the backend, not showing any language selector in the front and so on. Thanks!!