Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
HTML background image on full screen: I try to put a picture as background but it cuts the picture for me I want it to stay full size
The image works for me and is displayed on the screen, but when I make it the background, it cuts off part of it, which lowers the quality of the image and looks bad. I would appreciate your help, thanks <!DOCTYPE html> {% load static %} <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> html { background: url("{% static 'images/second.JPG' %}") no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } </style> </head> <body> </body> </html> -
Django Models between apps
Do I need is to import a model from app tienda and show the data in my home.html page My Project name is Proyectoweb My project apps are Proyectowebapp, Tienda I have nothing in Proyectowebapp.models.py In tienda models.py I wrote: from django.db import models class CategoriaProd(models.Model): nombre=models.CharField(max_length=50) imagen = models.ImageField(upload_to="catimgs", null=True, blank=True) created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now_add=True) class Meta: verbose_name="categoriaProd" verbose_name_plural="categoriasProd" def __str__(self): return self.nombre class Producto(models.Model): nombre = models.CharField(max_length=50) categorias = models.ForeignKey(CategoriaProd, on_delete=models.CASCADE) imagen = models.ImageField(upload_to="tienda", null=True, blank=True) precio = models.FloatField() created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now_add=True) class Meta: verbose_name="Producto" verbose_name_plural="Productos" def __str__(self): return self.nombre In Proyectowebapps views.py i wrote: from django.shortcuts import render from tienda.models import CategoriaProd def home(request): return render(request, "Proyectowebapp/home.html") def tienda(request): prodcats=CategoriaProd.objects.all() return render(request, "Proyectowebapp/home.html", {"prcat":prodcats}) In my home.html I wrote: {% for categoriaProd in prcat %} <img src="{{categoriaProd.imagen.url}}"> <h7>{{categoriaProd.nombre}}</h7> {% endfor %} Thanks, Sorry but Im new in Django world -
Calculating serializers read only fields
Here is an example: # models.py class MyModel(models.Model): ... metadata = models.JSONField() # serializers.py class MetadataSerializer(serializers.Serializer): x = serializers.IntegerField() y = serializers.IntegerField(read_only=True) # views.py class MyAPIView(APIView): def post(self, request): serializer = MetadataSerializer(data=request.data) serializer.is_valid() create_mymodel(metadata=serializer.validated_data) return Response(status=201) I would like to calculate y based on x using "complex" business logic y = const * x and save result to json field. Q: Where should i place this business logic? before serializer init, intercepting immutable request.data inside serializer validate() or validate_y() method. using get_y() of SerializerMethodField. inside create_mymodel() service. -
How to disable the grid in Openseadragon (Deepzoom) image
I'm working with deepzoom OpenSeaDragon and a grid keeps showing in some browsers Screenshot Screenshot2 Please help if anyone has an idea about a possible solution.. Thank you so much -
Django WSGI Apache
I am developing a Django Application and currently experiencing issue during WSGI + Apache integration. Below are my server configuration RHEL : 8.6 Python : 3.6.8 Apache : 2.4.37 After following various tutorials i have the following configurations under my httpd.conf, app.wsgi My httpd.conf file look like this LoadModule wsgi_module modules/mod_wsgi.so WSGIDaemonProcess django_project python-path=/home/project user=apache group=developers WSGIProcessGroup django_project WSGIScriptAlias / /home/project/myapp/wsgi.py process-group=django_project <Directory /home/project/myapp> <Files wsgi.py> Require all granted </Files> </Directory> My wsgi file look like this import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') application = get_wsgi_application() Here is the error message which i get under my httpd log [Mon Aug 29 09:49:19.786017 2022] [mime_magic:error] [pid 721666:tid 140511423796992] [client 192.168.1.112:49310] AH01512: mod_mime_magic: can't read `/home/project/myapp/wsgi.py' [Mon Aug 29 09:49:19.786118 2022] [mime_magic:error] [pid 721666:tid 140511423796992] [client 192.168.1.112:49310] AH01512: mod_mime_magic: can't read `/home/project/myapp/wsgi.py' [Mon Aug 29 09:49:19.786443 2022] [wsgi:error] [pid 721665:tid 140511574705920] (13)Permission denied: [remote 192.168.1.112:49310] mod_wsgi (pid=721665, process='django_project', application='192.168.1.114|'): Could not read/compile source file '/home/project/myapp/wsgi.py'. [Mon Aug 29 09:49:19.786503 2022] [wsgi:error] [pid 721665:tid 140511574705920] [remote 192.168.1.112:49310] mod_wsgi (pid=721665): Exception occurred processing WSGI script '/home/project/myapp/wsgi.py'. [Mon Aug 29 09:49:19.786564 2022] [wsgi:error] [pid 721665:tid 140511574705920] [remote 192.168.1.112:49310] PermissionError: [Errno 13] Permission denied: '/home/project/myapp/wsgi.py' My project directory have the following permission chown -R … -
django queryset select all from multiple tables
I want to select all columns from multiple table join using django queryset corresponding to following sql select user.*, address.*, contact.* from user left join address on user.id = address.userid left join contact on user.id = contact.userid I have following python User.objects.values() to get all user data. User.objects.values(first_name, last_name, contacts__number, addresses__zip) to get specific columns But I dont know how to get all columns from all 3 tables something like User.objects.values(*, contacts__*, addressess__*) -
How to access to attrbuite of another model or table using ManyToMany in django
Please, I need your help. How can I access to attribut of another model or table using ManyToMany I need to get data through this method but it's not retrieved ---=> this is Models.py class Mission(models.Model): nom=models.CharField(max_length=50,null=False,blank=False) description=models.CharField(max_length=150,null=False,blank=False) date_publier=models.DateTimeField() class Participer(models.Model): id_benevole = models.ManyToManyField(User) id_mission = models.ManyToManyField(Mission) est_participer = models.BooleanField(default=False) class User(AbstractUser): est_association = models.BooleanField(default=False) est_benevolat = models.BooleanField(default=False) username = models.CharField(max_length=30,unique=True) email = models.EmailField() password1 = models.CharField(max_length=20,null=True) password2 = models.CharField(max_length=20,null=True) class ProfileBenevole(models.Model): user = models.OneToOneField(User,related_name="benevole", on_delete = models.CASCADE, primary_key = True) photo_profile = models.ImageField( upload_to='uploads/images',null=True,blank=True) nomComplet = models.CharField(max_length=50,null=True) --=> this is Views.py def demande_participer(request): participers=Participer.objects.all() return render(request,'Association/success.html', {'participers':participers},print(participers)) ----=> success.html {% extends 'home/base.html'%} {% block content %}{% load static %} <div class=" mt-4 pb-5"> <h1 style="text-align:center;">Confirmation de Participation </h1> <div class="container"> <div class="card mt-5 pb-5"> {% for parti in participers %} {{parti.mission_id.nom}} <br> {{parti.id_benevole.username}} <br> {{parti.est_participer}} {% endfor%} </div> <a class="btn btn-secondary mt-2 " href="{% url 'benevole' %}">Retour </a> </div> </div> {% endblock content %} -
Django template double the data [closed]
I would need to display the information but it displays twice. Does anyone know how to put (list and disci) together as I know the error is in my code with the for i, for j and {% endfor %} in double. Employe and Disciplinaire are 2 different table with is own data. page.html <tr> <th scope="col">Matricule</th> <th scope="col">Prenom</th> <th scope="col">Nom</th> <th scope="col">Avis Verbal</th> <th scope="col">1er Avis Écrit</th> <th scope="col">2er Avis Écrit</th> <th scope="col">Suspension</th> <th scope="col">Fin d'emploi</th> <th scope="col">Actions</th> </tr> {% for i in liste %} {% for j in disci %} <tr> <td>{{i.Matricule}}</td> <td>{{i.Prenom}}</td> <td>{{i.Nom}}</td> <td>{{j.Avis_verbal}}</td> <td>{{j.Avis_ecrit}}</td> <td>{{j.Avis_ecrit2}}</td> <td>{{j.Suspension}}</td> <td>{{j.Fin_emploie}}</td> <td><a href="">Editer </a>/<a href=""> Supprimer</a></td> </tr> {% endfor %} {% endfor %} views.py def disciplinaire(request): disci = Disciplinaire.objects.all() liste = Employe.objects.all() return render(request, 'accounts/page.html', {'disci':disci, 'liste':liste}) Screenshot of page.html -
How to properly use multiprocessing module with Django?
I'm having a python 3.8+ program using Django and Postgresql which requires multiple threads or processes. I cannot use threads since the GLI will restrict them to a single process which results in an awful performance (especially since most of the threads are CPU bound). So the obvious solution was to use the multiprocessing module. But I've encountered several problems: When using spawn to generate new processes, I get the "Apps aren't loaded yet" error when the new process imports the Django models. This is because the new process doesn't have the database connection given to the main process by python manage.py runserver. I circumvented it by using fork instead of spawn (like advised here) so the connections are copied to the other processes but I feel like this is not the best solution and there should be a clean way to start new processes with the necessary connections. When several of the processes simultaneously access the database, sometimes false results are given back (partly even from wrong models / relations) which crashes the program. This can happen in the initial startup when fetching data but also when the program is running. I tried to use ISOLATION LEVEL SERIALIZABLE (like … -
Django does not throw ValidationError when required fields are not present
I am currently testing my django model using pytest (and pytest-django), but I can not write a failing test case in which a required field is missing. My Person-model requires solely a name and a company. The other fields are nullable and therefore optional. models.py: from django.db import models # Create your models here. class Person(models.Model): name = models.CharField(max_length=64) company = models.CharField(max_length=128) position = models.CharField(max_length=64, null=True, blank=True) date_of_birth = models.DateField(null=True, blank=True) def __str__(self): return (f"{self.name}" + (f", {self.position}" if self.position is not None else "") + f"({self.company})" + (f" born {self.date_of_birth}" if self.date_of_birth is not None else "") ) test.py from .models import Person import pytest from django.core.exceptions import ValidationError pytestmark = pytest.mark.django_db # Create your tests here. def test_minimal_person(): """Test if a minimal person can be created""" valid_person = Person(name="Max Mustermann", company="ACME") valid_person.save() assert len(Person.objects.get_queryset()) == 1 def test_insufficient_params(): with pytest.raises(ValidationError): invalid_person = Person() invalid_person.save() def test_missing_company(): with pytest.raises(ValidationError): invalid_person = Person(name="Max") invalid_person.save() def test_missing_name(): with pytest.raises(ValidationError): invalid_person = Person(company="ACME") invalid_person.save() def test_invalid_date_format(): """Test if an invalid date format throws a ValidationError""" with pytest.raises(ValidationError): invalid_person = Person(name="Max", company="ACME", date_of_birth="not-a-date") invalid_person.save() The test test_invalid_date_format and test_minimal_person succeed, but the other ones do not throw an (expected) error. What am I … -
My django form is showing that data is posted but data isnt being saved to database
So my form was working just fine until i played around with my frontend...changing the look of the system. But i dont think this has an effect on my forms but surprisingly all my forms are no longer saving data to the database!! Some help here guys. Here is my views.py from django.contrib.auth.models import User from django.contrib import messages from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate from .forms import * # Create your views here. def register(request): form = RegistrationForm() if request.method == "POST": form = RegistrationForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'User successfully registered!') return redirect('home') else: form = RegistrationForm() return render(request, 'accounts/register.html', {'form': form} ) def login(request): if request.method == 'POST': username = username.POST['username'] password = request.POST['password'] try: user = Account.objects.get(username=username) except: messages.error(request, 'username does not exist') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.error(request, 'Invalid username Or Password') return render(request, 'accounts/login.html', {} ) models.py from distutils.command.upload import upload import email from django.db import models from django.conf import settings from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.base_user import BaseUserManager class MyAccountManager(BaseUserManager): def _create_user(self, email, username, profile_pic, address, phone_number, car, details, password): if not email: raise ValueError("User … -
Django is not collecting all my static files
I have 2 folders containing my static files (admin, and assets). However, when I run python manage.py collectstatic, only the static files in the admin folder are collected. Below is a code snippet for static files in settings.py STATIC_URL = 'static/' STATTICFILES_DIRS = [ BASE_DIR/ "asert" ] STATIC_ROOT = (BASE_DIR/"asert/") Below are some urls linking to the static files from an html page <link rel="stylesheet" type="text/css" href="{% static 'assets/css/assets.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'assets/vendors/calendar/fullcalendar.css' %}"> <!-- TYPOGRAPHY ============================================= --> <link rel="stylesheet" type="text/css" href="{% static 'assets/css/typography.css' %}"> <!-- SHORTCODES ============================================= --> <link rel="stylesheet" type="text/css" href="{% static 'assets/css/shortcodes/shortcodes.css' %}"> <!-- STYLESHEETS ============================================= --> <link rel="stylesheet" type="text/css" href="{% static 'assets/css/style.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'assets/css/dashboard.css' %}"> <link class="skin" rel="stylesheet" type="text/css" href="{% static 'assets/css/color/color-1.css' %}"> -
I'm very new to Django. I am trying to desing my login module and trying to print the values i submit. its not working [closed]
def login(request): form =LoginForm() print(form,'0000000000') if request.method == "POST": form = LoginForm(request.POST) print(form,'1111111111') if form.is_valid(): user = authenticate( username = form.cleaned_data['username'], password = form.cleaned_data['password'], ) if user is not None: login(request, user) else: messages.error(request,"Invalid username or password") else: form =LoginForm() return redirect("post_list", pk=user.pk) return render(request,"blog/login.html", context={"form":form}) -
datalist in HTML new option adding
I have a datalist elements from my view in django model, and i want to have sticky option(option that it's there even if the user enter something not in the list with "add new button" inside or to track it using javascript) to add new record in my model. -
How can I change the "Delete?" label in a Djano Inline
I'd like to replace the default "Delete?" label in TabularInLine to be something like "X". Is there a way to do this in Django directly or do I have to change it after the page loads with JS? example image -
NoReverseMatch at /assetAdmin/ error in Django
I have created a table that contains details about all the Assets. I wish to update the details of the asset. So, from the table, a made asset_id as URL to update page as happens in Django Administration. But after I added the URL pattern to update the asset, I am receiving this error: Reverse for 'asset-update' with keyword arguments '{'id': UUID('cd7edefa-796d-428e-bcec-c90ceecc7fc3')}' not found. 2 pattern(s) tried: ['assets/(?P<pk>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/update/\\Z', 'assets/(?P<pk>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/\\Z'] Here is my urlpatterns from urls.py: urlpatterns = [ path('home/', home, name='home'), path('assets/', assets, name='assets'), path('assetAdmin/', adminAssetView, name='assetsAdmin'), path('createAsset/', createAssetView, name='createAssets'), path('assets/<uuid:pk>/update/', assetUpdateView.as_view(), name='asset-update'), path('register/', register, name='register'), path('login/', auth_views.LoginView.as_view(template_name='assets/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='assets/logout.html'), name='logout'), path('accounts/profile/', profile, name='profile'), path('admin/', admin.site.urls), ] Here are the views involved: @user_passes_test(lambda u: u.is_superuser) def adminAssetView(request): context = { 'assets': asset.objects.all(), 'users':User.objects.all(), } return render(request, 'assets/assetAdmin.html', context) class assetUpdateView(SuperUserCheck, LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = asset fields = ['currentOwner',] def form_valid(self, form): return super().form_valid(form) def test_func(self): asset = self.get_object() if self.request.user.is_superuser == True: return True return False And here is the part in assetAdmin.html where I am using asset-update urlpattern {% for asset in assets %} <tr> <td><a href="{% url 'asset-update' id=asset.id%}">{{ asset.id }}</a></td> <td>{{ asset.asset_type }}</td> <td>{{ asset.asset_name }}</td> <td>{{ asset.brand }}</td> <td>{{ asset.isActive }}</td> <td>{{ asset.currentOwner }}</td> … -
Issue with django factory for GenericForeignKey
models.py class GoogleCreative(models.Model): name = models.CharField creative_type = models.CharField url = models.URLField table_url = models.URLField status = models.CharField tags = GenericRelation( 'CreativeTag', object_id_field='creative_id', content_type_field='creative_content_type' ) class Tag(models.Model): name = models.CharField(max_length=150) slug = models.SlugField(max_length=150, allow_unicode=True) class CreativeTag(models.Model): tag = models.ForeignKey(Tag, on_delete=models.CASCADE) creative_content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) creative_id = models.PositiveIntegerField() creative = GenericForeignKey('creative_content_type', 'creative_id') class Meta: unique_together = ['tag', 'creative_content_type', 'creative_id'] factories.py class GoogleCreativeFactory(factory.django.DjangoModelFactory): class Meta: model = GoogleCreative name = factory.Faker('word') ..... class TagFactory(factory.django.DjangoModelFactory): class Meta: model = Tag django_get_or_create = ('name',) slug = factory.LazyAttribute(lambda o: slugify(o.name, allow_unicode=True)) class CreativeTagFactory(factory.django.DjangoModelFactory): class Meta: model = CreativeTag exclude = ['creative'] class Params: name = factory.Sequence(lambda n: f'tag {n}') tag = factory.SubFactory(TagFactory, name=factory.SelfAttribute('..name')) creative_id = factory.SelfAttribute('creative.id') creative_content_type = factory.SelfAttribute('creative.content_type') test.py @pytest.mark.django_db def test_tags_removed(google_creative_factory, creative_tag_factory, user): creative = google_creative_factory() creative_tag_factory(creative=creative, name='Big Fish') But getting error AttributeError: 'GoogleCreative' object has no attribute 'content_type' I try to solve it adding new field creative to CreativeTagFactory and comment Meta exclude field class CreativeTagFactory(factory.django.DjangoModelFactory): class Meta: model = CreativeTag # exclude = ['creative'] class Params: name = factory.Sequence(lambda n: f'tag {n}') tag = factory.SubFactory(TagFactory, name=factory.SelfAttribute('..name')) creative_id = factory.SelfAttribute('creative.id') creative_content_type = factory.SelfAttribute('creative.content_type') creative = factory.SubFactory(GoogleCreativeFactory) But got the same error -
How to use Django models with enumeration in REST APIs?
I am using User model to store user details: class User(models.Model): MEMBERSHIP_BRONZE = 'B' MEMBERSHIP_SILVER = 'S' MEMBERSHIP_GOLD = 'G' MEMBERSHIP_CHOICES = [ (MEMBERSHIP_BRONZE, 'Bronze') (MEMBERSHIP_SILVER, 'Silver') (MEMBERSHIP_GOLD, 'Gold') ] name = models.CharField(max_length=255) email = models.EmailField(unique=True) phone = models.CharField(max_length=255) membership = models.CharField(max_length=1, choices=MEMBERSHIP_CHOICES, default=MEMBERSHIP_BRONZE) When customer created using post api then i want to allow only these three values Bronze for MEMBERSHIP_BRONZE, Silver for MEMBERSHIP_SILVER & Gold for MEMBERSHIP_GOLD in membership field. When a user select membership choices lebel from ui then i need to insert the respected value. I don't know how to do this? serializer.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ["name", "email", "phone", "membership"] views.py @api_view(["GET", "POST", "PUT"]) def userActions(request): if request.method == "GET": users = User.objects.all() serializer = UserSerializer(users, many=True) res = serializer.data if request.method == "POST": name = request.POST.get("name") email = request.user.email phone = request.POST.get("phone") membership = request.POST.get("membership") user = User.objects.create(name=name, email=email, phone=phone, membership=membership) serializer = UserSerializer(user) res = serializer.data return res -
Django create a custom model field for currencies
Here I my custom model field I created it class CurrencyAmountField(models.DecimalField): INTEGER_PLACES = 5 DECIMAL_PLACES = 5 DECIMAL_PLACES_FOR_USER = 2 MAX_DIGITS = INTEGER_PLACES + DECIMAL_PLACES MAX_VALUE = Decimal('99999.99999') MIN_VALUE = Decimal('-99999.99999') def __init__(self, verbose_name=None, name=None, max_digits=MAX_DIGITS, decimal_places=DECIMAL_PLACES, **kwargs): super().__init__(verbose_name=verbose_name, name=name, max_digits=max_digits, decimal_places=decimal_places, **kwargs) How can I show the numbers in a comma-separated mode in Django admin forms? Should I override some method here on this custom model field or there is another to do that? Should be: -
how can i set up my server with winscp, putty, nginx, ubuntu and gunicorn [closed]
My English is very bad.And I am a beginner in programming I created a backend project with python ,django and rest api.But I don't know how to set up server. Please if someone knows about this , teach me -
django @cache_page decorator not setting a cache
Here's my cache setting: CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', } } } And a very basic view with cache_page decorator @api_view(['POST']) @cache_page(60*1) def sawan_ko_jhari(request): data = request.data.get('name') return JsonResponse({"success": True, "data": data}, safe=False) I've been checking cache keys for every request sent.. and I get empty array. Is there something I'm missing here? -
How to incorporate django-tailwind into Dockerized cookiecutter-django project?
Apologies for what is likely a very simple question, I am pretty new to Docker and am struggling to integrate django-tailwind into my docker project, which was created using cookiecutter-django. I have tried altering my Dockerfile and local.yml file to follow the Example dockerfiles on the Example app on the django-tailwind github repo but haven't been able make it work. The instructions beyond the example app are not very detailed. I have quoted my Dockerfile and local.yml file below; would someone be able to advise on what changes I need to make in order to incorporate django-tailwind, or point me in the direction of information that would help me to do it myself? Thanks for any help anyone can offer! Dockerfile: ARG PYTHON_VERSION=3.9-slim-bullseye # define an alias for the specfic python version used in this file. FROM python:${PYTHON_VERSION} as python # Python build stage FROM python as python-build-stage ARG BUILD_ENVIRONMENT=local # Install apt packages RUN apt-get update && apt-get install --no-install-recommends -y \ # dependencies for building Python packages build-essential \ # psycopg2 dependencies libpq-dev # Requirements are installed here to ensure they will be cached. COPY ./requirements . # Create Python Dependency and Sub-Dependency Wheels. RUN pip wheel --wheel-dir … -
Number of questions Django/Python
Number of questions: Try to create a new game of 20 questions of medium difficulty (MEDIUM) in the Art category. It was acting weird, right? This is definitely not a desirable situation. It follows that Open Trivia DB does not have enough questions from a given category with a given level of difficulty, so it returns us an error. And we do not handle it wisely: try: question = quiz.get_question() quiz.save(request) return render(request, 'game.html', vars(question)) except IndexError as x: return redirect('/finish') because we assume that the end of the questions = the end of the game. What makes sense if the API has the right number of questions ... The response code from the Open Trivia website in this case is 1. Looking at the documentation (https://opentdb.com/api_category.php), we will find out what each code means: Hint We have to think about how to solve this problem. It would be nice if the answer, apart from the error code, would include all possible tasks for a given category and level of difficulty - but unfortunately it is not. We have to adapt to the existing API, changing anything there is beyond our reach. We have three possible solutions: or we will … -
Django excel export, file is not downloading
I am trying to perform excel export functionality in Django with xls. But When I am trying to perform that file is not downloading and there is no error also. Here is my code. def excelExport(request): response = HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment;filename="InitalRegistaration.xls"' work_book = xlwt.Workbook(encoding='utf-8') uc = u"".join(chr(0x0410 + i) for i in range(32)) # some Cyrillic characters u8 = uc.encode("UTF-8") work_sheet = work_book.add_sheet('Client Registration') work_sheet.write(0,0,"Clients") work_book.save(response) return response I don't know what's wrong with my code but the file is not getting downloaded nor there is the error coming from the code. -
Django: executing UPDATE query always returns rowcount 0
I'm new to programming and I'm not sure, whether the problem is in me or in the Django code. I call link method from my view and update field MatchId on Record model. Database is SQL Server 2017. My view: class RecordViewSet(viewsets.ModelViewSet): """ API for everything that has to do with Records. Additionally we provide an extra `link` action. """ queryset = Record.objects.all().order_by("Id") serializer_class = RecordSerializer permission_classes = [permissions.IsAuthenticated] @action(methods=["post"], detail=False) def link(self, request, *args, **kwargs): idToMatch = request.POST.getlist("Id") recordsToMatch = Record.objects.filter(Id__in=idToMatch) lastMatchId = Record.objects.latest("MatchId").MatchId matchedSuccesfully = recordsToMatch.update(MatchId=lastMatchId + 1) if matchedSuccesfully > 1: return Response(data=matchedSuccesfully, status=status.HTTP_200_OK) else: return Response(data=matchedSuccesfully, status=status.HTTP_404_NOT_FOUND) For some reason matchedSuccessfully always returns zero. Relevant Django code: def execute_sql(self, result_type): """ Execute the specified update. Return the number of rows affected by the primary update query. The "primary update query" is the first non-empty query that is executed. Row counts for any subsequent, related queries are not available. """ cursor = super().execute_sql(result_type) try: rows = cursor.rowcount if cursor else 0 is_empty = cursor is None finally: if cursor: cursor.close() for query in self.query.get_related_updates(): aux_rows = query.get_compiler(self.using).execute_sql(result_type) if is_empty and aux_rows: rows = aux_rows is_empty = False return rows I rewrote execute_sql as follows: def execute_sql(self, result_type): …