Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django migrations in a replication scenario
I have a bunch of apps written in Django on a Docker Swarm. Currently all are defined to have exactly one replica. They start up run their collectstatic and migrate commands of the entrypoint.sh files and exec Uwsgi. Now I need to replicate the tired old Django applications and I can't figure out how to approach it: There is hope that the first replica will "lock" - whatever the lock maybe - I was thinking maybe a select for update on the django_migrations table, but that does not seem to be the case - it would be perfect, since the second replica would have to wait for the first one to finish (?) Maybe I'm safe by default as one already executed ALTER TABLE will make the one run by the other replica fail - not perfect as the migration command will fail and bounce the container but at least would not wreck the database Maybe there is no way and I need to cut the migration task out of the replicated containers into a "administrative container" and then run it manually I can't find an documentation about it while I don't want to believe that Django (being so "big" … -
How can I use Django to pull data from one application using REST url and push data to other application
I'm new and still in learning the concepts of Django, I need to understand how can I use Django capabilities to pull data from one application using REST API url and push the data to second application using REST API url. REST API url for APP 1 - GET - http://fqdn:port/app1/rest/users REST API url for APP 2 - POST - http://fqdn:port/app2/rest/users/action/create Scenario: Whenever a data for users is added in Application 1 , Django call the REST API url of app 1 & push it to Application 2 for user record creation. Please suggest!! Thanks In advance -
Can i pass two model in class based view?
I have creating blog website. My page has 2 part one is post one is category. My view is class based view where is pass ListView. So i can pass one model name. Have there any way to pass two model through it... -
NoReverseMatch at /NewListing
I have a form on my webpage for users to create a new listing. The form loads up okay but on submission an error comes up: NoReverseMatch at /NewListing Reverse for 'listing' with keyword arguments '{'listing': None}' not found. 1 pattern(s) tried: ['(?P<listing_id>[0-9]+)$'] The form does save the new listing and update the homepage with the new listing but I would like that once the listing is submitted, the user is taken to the new listing page and I can't seem to get that to work without this error popping up. models.py class Category(models.Model): group = models.CharField(max_length=20) def __str__(self): return f"{self.group}" class Listing(models.Model): title = models.CharField(max_length=64) description = models.TextField(max_length=64) price = models.DecimalField(max_digits=9, decimal_places=2, validators=[MinValueValidator(0.99)]) image = models.URLField(max_length=200, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="categories") def __str__(self): return f"Product: {self.title} \nDescription: {self.description} \nCurrent Price: £{self.price}\nImage: {self.image} \nCategory: {self.category}" forms.py class NewListingForm(forms.ModelForm): class Meta: model = Listing fields = ["title", "description", "price", "image", "category"] title = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'off'})) description = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'off'})) price = forms.DecimalField(label='Starting Bid Price (£)') image = forms.URLField(widget=forms.URLInput(attrs={'autocomplete':'off'})) views.py def listing(request, listing_id): listing = Listing.objects.get(pk=listing_id) return render(request, "auctions/listingPage.html", { "listing": listing }) def newListing(request): if request.method == "POST": form = NewListingForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] description = form.cleaned_data['description'] price = form.cleaned_data.get('price') … -
How to save tag in django to my model using django-taggit
I dont know how to save tag to my model ,can you plz guide me to do this This is my model class publish(models.Model): Userid=models.ForeignKey(Userdata,on_delete=models.CASCADE) tittle=models.CharField(max_length=20) contend=models.TextField(max_length=20000) select_cat=models.CharField(max_length=30,default='Horror') tags=TaggableManager() def __str__(self): return self.tittle And this is my form class DisplayformNew(forms.ModelForm): CHOICES=(('Horror','Horror'),('Education','Education'),('Sports','Sports'),('Story','Story'),('Comic','Comic')) title=forms.CharField(label='Title',max_length=30) text= forms.CharField(widget=forms.Textarea(attrs={"rows":15, "cols":50})) sel_cat=forms.ChoiceField(choices=CHOICES,label='Select Catagoriy') class Meta: model=publish fields=['title','text','sel_cat','tags'] And this is my views def add_new(request): form=DisplayformNew(request.POST) if form.is_valid(): new_todo=publish(Userid=Userdata.objects.get(Email=request.user.email),tittle=request.POST['title'],contend=request.POST['text'],select_cat=request.POST['sel_cat'],tags=request.POST['tags']) new_todo.save() #form.save_m2m() context={'form':form} return render(request,'newpost.html',context) I cant save Tag to my model ,can anyone help me to solve this ...... I can save it from admin view but how to save from user interface -
Getting error during installation of virtual environment package in ubuntu
I am trying to install virtual environment in ubuntu but I am getting this error: karan@karan-HP-Notebook:~/Django_Applications/projects/project_1$ sudo apt-get install python3-venv Reading package lists... Done Building dependency tree Reading state information... Done The following additional packages will be installed: libpython3-stdlib python-pip-whl python3 python3-minimal python3.6-venv Suggested packages: python3-doc python3-tk The following NEW packages will be installed: python-pip-whl python3-venv python3.6-venv The following packages will be upgraded: libpython3-stdlib python3 python3-minimal 3 upgraded, 3 newly installed, 0 to remove and 330 not upgraded. Need to get 46.0 kB/1,425 kB of archives. After this operation, 1,671 kB of additional disk space will be used. Do you want to continue? [Y/n] y Err:1 http://in.archive.ubuntu.com/ubuntu artful-updates/main amd64 python3-minimal amd64 3.6.3-0ubuntu3 404 Not Found [IP: 2403:8940:3:1::f 80] Err:2 http://in.archive.ubuntu.com/ubuntu artful-updates/main amd64 python3 amd64 3.6.3-0ubuntu3 404 Not Found [IP: 2403:8940:3:1::f 80] Err:3 http://in.archive.ubuntu.com/ubuntu artful-updates/main amd64 libpython3-stdlib amd64 3.6.3-0ubuntu3 404 Not Found [IP: 2403:8940:3:1::f 80] Err:4 http://in.archive.ubuntu.com/ubuntu artful/universe amd64 python3.6-venv amd64 3.6.3-1ubuntu1 404 Not Found [IP: 2403:8940:3:1::f 80] Err:5 http://in.archive.ubuntu.com/ubuntu artful-updates/universe amd64 python3-venv amd64 3.6.3-0ubuntu3 404 Not Found [IP: 2403:8940:3:1::f 80] E: Failed to fetch http://in.archive.ubuntu.com/ubuntu/pool/main/p/python3-defaults/python3-minimal_3.6.3-0ubuntu3_amd64.deb 404 Not Found [IP: 2403:8940:3:1::f 80] E: Failed to fetch http://in.archive.ubuntu.com/ubuntu/pool/main/p/python3-defaults/python3_3.6.3-0ubuntu3_amd64.deb 404 Not Found [IP: 2403:8940:3:1::f 80] E: Failed to fetch http://in.archive.ubuntu.com/ubuntu/pool/main/p/python3-defaults/libpython3-stdlib_3.6.3-0ubuntu3_amd64.deb 404 Not Found … -
Why I can't add custom middleware?
I am trying to connect my custom middleware (using Django 1.8) by copying an example from the Django manual. class SimpleMiddleware(object): def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): response = self.get_response(request) return response But I get an initialization error. TypeError: __init__() takes exactly 2 arguments (1 given) What's the problem? -
What django do when allow_migrate() on a database router returns false?
I'm writing a DB router to control what should be or not applied on the DB, so, implemented allow_migrate(). Here is what I did: def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'django_q': return db == 'tasks' elif app_label != 'django_q': return db == 'default' I was expecting that when a router returns False, then an app wouldn't be applied on the current DB at all, it happened somehow, no tables were created, but, the entire app migration list is added to django_migrations table at the DB. I was expecting that when allow_migrate() return False, then Django won't add anything to current DB about this app, but if this behaviour is the expected, then, this is the same as migrate --fake, right? if this so, I prefer doing it manually for the other DB. I have done some research to see what is actually done when allow_migrate() returns False but got no luck. Thanks in advance. -
django @action decorator doesnt seem to work
Im trying to write simple crm rest api in django using viewsets, however when I use @action decorator to modify my database upon posting data, it doesnt seem to do anything class PurchaseViewSet(viewsets.ModelViewSet): queryset = Purchases.objects.all() serializer_class = PurchaseSerializer @action(detail=False, methods=['post']) def api_make_purchase(self, request): product = Products.objects.get(product_name = request.data['product_name']) product.product_stock -= int(request.data['quantity']) product.sold_units += int(request.data['quantity']) product.save() return Response({'done': True}) when I query back after posting into purchases table, the product stock still stays at previous values, I dont get the response from api_make_purchase function either -
How to customize in django-rest_framework-knox LoginView
hi i am trying to create login api which will give me extra output fields by default knox login is giving 'expire' and 'token' but i want to add other values too for example it is giving me : { "expiry": "2020-10-02T17:00:22.906891Z", "token": "2a6d73cf85f3f15d855ab0386db7fcf4342167ab3d47e1d0983a775c120ff267", } ``` but i want to extra values too like : { "expiry": "2020-10-02T17:00:22.906891Z", "token": "2a6d73cf85f3f15d855ab0386db7fcf4342167ab3d47e1d0983a775c120ff267", "username" : "foo", "projects" :"["faa","fee","fuu"]", } my views.py is given below from django.shortcuts import render from .models import * from django.views.generic.edit import FormView from rest_framework import generics, permissions from rest_framework.response import Response from knox.models import AuthToken from .serializers import UserSerializer, RegisterSerializer from django.contrib.auth import login from rest_framework import permissions from rest_framework.authtoken.serializers import AuthTokenSerializer from knox.views import LoginView as KnoxLoginView # Register API class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) class LoginAPI(KnoxLoginView): permission_classes = (permissions.AllowAny,) def get_post_response_data(self, request): data def post(self, request, format=None): serializer = AuthTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] user_id_main=user.id user_name=user.username # projects_list=ProjectTable.objects.filter(id=Project_user_reletional_table.objects.filter(id=user_id)) # for a in projects_list: # print(a.name) # print(a.project_city) print(user_id_main,user_name) b=Project_user_reletional_table.objects.filter(user_id_id=user_id_main) for a in b: print(a.project_id) login(request, user) login_details=super(LoginAPI, self).post(request, format=None) return super(LoginAPI, self).post(request, format=None) please help me thanks … -
Is there a way to optimize the creation of users (that are also part of another model) in Django with just one request?
My app has Users that can be Doctors. To create a Doctor, therefore, I perform two POST requests: one for the creation of a User and one for a Doctor. The way I do this, the User has to be created first so that I can later create the Doctor (Doctor requires a 'User' field). class User(AbstractUser): ROLES = ( ('d', 'Doctor'), ('s', 'Secretary'), ('p', 'Patient'), ) role = models.CharField( max_length=1, choices=ROLES, blank=True, default='p', help_text='Role') class Doctor(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ... Since I'm new to Django, I don't know if two requests is the de facto way of creating this User/Doctor. This comes to mind as I am also thinking of the GET methods which will I'll need to perform later on (two requests when a Doctor logs in if I want to retrieve all of their info?) I read about subclassing, which would be something like Doctor(User), then the only necessary request would be a single POST to create a Doctor (which would alongside create the User). I am, however, skeptical of subclassing the User as I read at least 3 SO answers stating it could cause problems in the future. -
can't run as root without the -u switch
I'm trying to add memcached to a django app to help with speed issues. So I installed it using the command sudo apt get install memcached Then I attempted to see if it was installed by using the command memcached -vv I get the error can't run as root without the -u switch I'm not sure what this error means. I need to understand before I attempt to research solutions. -
Django REST Framework share class instance between files
I have some code in my apps.py's ready() method that loads some Oauth providers using the authlib module. Basically I am doing this: oauth = OAuth(fetch_token=fetch_token) allproviders = OauthProvider.objects.all() for provider in allproviders: oauth.register( name=provider.name, client_id=provider.client_id, client_secret=provider.client_secret_decrypted, access_token_url=provider.access_token_url, access_token_params=provider.access_token_params, authorize_url=provider.authorize_url, authorize_params=provider.authorize_params, api_base_url=provider.api_base_url, client_kwargs=eval(provider.client_kwargs), ) #here it saves to caches which is caches['default'] (LocMemCache) cache.set('oauth', oauth) # Uncommenting the following line gives a stack overflow # cache.get('oauth') This registers some oauth credentials (info) that can be used using the oauth variable (for example oauth.get_authorization_url() which gets me the authorize URL for that Oauth Provider. Now, I have a lot of different files (I split my views.py into multiple files). How can I access this oauth variable in those files? I have tried with django caches, but then I get a weird overflow error when I try to access the variable. How would you recommend? -
JQuery script for only one checkbox selection at a time [duplicate]
I got my script and it works pretty well (as I planned), but only after complete document loading with all checkboxes. It looks like this: You can see it disables other checkboxes in required column. But here's the thing. I need to use this script when I creating my entriesm and at first loading my page with this entries look like this: And after adding new entries script already doesn't work. I think this is about AJAX page reloading, the script is doesn't react to AJAX and don't work as a result. $(document).ready(function () { $('.field-correct :checkbox').change(function() { var $check = $(this), $div = $check.parent(); if ($check.prop('checked')) { $('[name~="choice"], [name$="correct"]').each(function() { if (!$(this).is(':checked')) { $(this).prop('disabled', true); } }); } else { $('[name~="choice"], [name$="correct"]').each(function() { if (!$(this).is(':checked')) { $(this).prop('disabled', false); $(this).css('background-color', 'red'); } }); } }); }); What should I do to make my script work with AJAX too? upd: here's html -
DJANGO with docker and postgresql
I'm novice in docker, and playing around docker to learn it more. Here is my Dockerfile FROM python:3.8.3-alpine #set the working directory for the container WORKDIR /user/src/app/ #set the env variables ENV PYTHONBUFFERED=1 ENV PYTHONWRITEBYCODE=1 # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev RUN pip install psycopg2-binary RUN apk add zlib-dev jpeg-dev gcc musl-dev #install pip for the docker image RUN pip install --upgrade pip #copy the requirement from local system to docker image inside /user/src/app/ COPY ./requirements.txt . RUN pip install -r requirements.txt #copy the complete project files after installing dependencies. COPY . . ENTRYPOINT ["/user/src/app/entrypoint.sh"] Second is entrypoint.sh #!/bin/sh if [ "$DATABASE" = "postgres" ] then echo "Waiting for postgres..." while ! nc -z $DB_HOST $DB_PORT; do sleep 0.1 done echo "PostgreSQL started" fi # python manage.py flush --no-input # python manage.py migrate exec "$@" And the last one docker-compose.yml version: "3.8" services: db: image: postgres:12.4-alpine environment: - POSTGRES_DB=demo_1 - POSTGRES_USER=*** - POSTGRES_PASSWORD=*** volumes: - postgres_data:/var/lib/postgresql/data/ web: build: context: . dockerfile: Dockerfile command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/user/src/app/ ports: - "8000:8000" depends_on: - db env_file: - ./.env volumes: postgres_data: I'm able to run postgres and make the server up … -
Django connect to mysql
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'onlineCourse', 'HOST': 'localhost', 'PORT': '3306', 'USER': 'root', 'PASSWORD': 'root', } } I tried to connect mysql to django follow django tutorial but its not work when i press in commnadline python manage.py migrate so it report error like below. someone help me please FIELD_TYPE.JSON: 'JSONField', AttributeError: module 'MySQLdb.constants.FIELD_TYPE' has no attribute 'JSON' -
read Object from Django in Javascript
I have the following situation and I don't have any solution I have a array Object coming from Django and I read it in my index.html in this way: {% for feature in Features %}..code...{% endfor %} Now I need to assign these values to a array Object in javascript/jQuery. I tried in this way but is not working: <script> var myfeatures = [{% for feature in Features %}]; </script> Have anybody any idea about how to solve this problem? Thanks -
django.core.exceptions.ImproperlyConfigured: COMPRESS_ROOT defaults to STATIC_ROOT, please define either
when I try to run the migrations , I get the following error: File "/home/shree/Desktop/projects/Hackoctomber/CRM/venv/lib/python3.6/site-packages/appconf/base.py", line 102, in _configure value = callback(value) File "/home/shree/Desktop/projects/Hackoctomber/CRM/venv/lib/python3.6/site-packages/compressor/conf.py", line 111, in configure_root + 'STATIC_ROOT, please define either') django.core.exceptions.ImproperlyConfigured: COMPRESS_ROOT defaults to STATIC_ROOT, please define either I have checked settings.py and it is configured as follows: MEDIA_ROOT = os.path.join(BASE_DIR, "media") MEDIA_URL = "/media/" STATIC_URL = "/static/" STATICFILES_DIRS = (BASE_DIR + "/static",) COMPRESS_ROOT = BASE_DIR + "/static/" I have also added following line, but it didn't help: STATIC_ROOT = "static" Django-CRM Here is the project Where and what should I configure? -
[DJANGO][II] Can't deploy application
I'm facing an issue with my Django Application Deployment. I have followed several tutorials ( lastly this one : https://www.youtube.com/watch?v=APCQ15YqqQ0) to help me deploy my application, I don't understand why my Handler is not working. Here is my web.config file : <?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <handlers> <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="c:\users\xxx\documents\github\app_folder\scripts\python.exe|c:\users\xxx\documents\github\app_folder\lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> <appSettings> <add key="PYTHONPATH" value="C:\Users\xxx\Documents\GitHub\app_folder\app" /> <add key="WSGI_HANDLER" value="app_name.wsgi.application" /> <add key="DJANGO_SETTINGS_MODULE" value="app_name.settings" /> </appSettings> </configuration> As I have my virtualenv in the app_folder folder, app folder contains the Django project. I have this message for output : Additional information about the error : Module FastCgiModule Notification ExecuteRequestHandler Handler django_handler_test Error code 0x8007010b URL requested http://localhost:94/ Physical Path C:\Users\xxx\Documents\GitHub\app_folder\app Session opening Method Anonyme User Session Anonyme I translated the category name as they were in french -
How to have different change frequency and priority for a list of items in django sitemap?
I have built a static sitemap in my django project as below: class StaticViewSitemap(Sitemap): changefreq = "weekly" priority = 0.9 protocol = 'http' if DEBUG else 'https' def items(self): return ['home', 'contact_us', 'blog', ] def location(self, item): return reverse(item) What should I do if I want to set different priorities and change frequency for different urls? I have seen this question but I still ddo not know what to do: Priority issue in Sitemaps -
Server Error 500 when trying to add instance of a model on Django
I have a website working perfectly in Django for me, I can add and delete instances of models as I want. However, if someone else tries to add an instance with the exact same admin account, the page shows "Server Error 500". I am using the default SQLite settings for django. models.py: from django.db import models from datetime import datetime # Create your models here. class Receita(models.Model): titulo_receita = models.CharField(max_length=200); resumo_receita = models.CharField(max_length=255, default='') tempo_receita = models.CharField(max_length=200, default=''); rendimento_receita = models.CharField(max_length=200, default=''); imagem_preview = models.ImageField(upload_to='uploads/%Y/%m/%d/', default='static/default_image.png') conteudo_receita = models.TextField(); data_receita = models.DateTimeField('Data publicação', default=datetime.now()); def __str__(self): return self.titulo_receita; class Produto(models.Model): nome = models.CharField(max_length=200); desc = models.TextField() # desc = models.CharField(max_length=255, default=''); imagem = models.ImageField(upload_to='uploads/%Y/%m/%d/', default='static/default_image.png') info1 = models.CharField(max_length=255, default='', blank=True) cod1 = models.CharField(max_length=255, default='', blank=True) info2 = models.CharField(max_length=255, default='', blank=True) cod2 = models.CharField(max_length=255, default='', blank=True) info3 = models.CharField(max_length=255, default='', blank=True) cod3 = models.CharField(max_length=255, default='', blank=True) def __str__(self): return self.nome; admin.py: from django.contrib import admin from .models import Receita from .models import Produto from tinymce.widgets import TinyMCE from django.db import models # Register your models here. class ReceitaAdmin(admin.ModelAdmin): formfield_overrides = { models.TextField: {'widget': TinyMCE()} } admin.site.register(Receita, ReceitaAdmin) admin.site.register(Produto) -
ProgrammingError at / relation "products_product" does not exist LINE 1: ...votes_total", "products_product"."hunter_id" FROM "products_
Error: ProgrammingError at / relation "products_product" does not exist LINE 1: ...votes_total", "products_product"."hunter_id" FROM "products_... My views.py from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from .models import Product from django.utils import timezone def home(request): products = Product.objects return render(request, 'products/home.html',{'products':products}) @login_required(login_url="/accounts/login") def create(request): if request.method == 'POST': if request.POST['title'] and request.POST['body'] and request.POST['url'] and request.FILES['icon'] and request.FILES['image']: product = Product() product.title = request.POST['title'] product.body = request.POST['body'] if request.POST['url'].startswith('http://') or request.POST['url'].startswith('https://'): product.url = request.POST['url'] else: product.url = 'http://' + request.POST['url'] product.icon = request.FILES['icon'] product.image = request.FILES['image'] product.pub_date = timezone.datetime.now() product.hunter = request.user product.save() return redirect('/products/' + str(product.id)) else: return render(request, 'products/create.html',{'error':'All fields are required.'}) else: return render(request, 'products/create.html') def detail(request, product_id): product = get_object_or_404(Product, pk=product_id) return render(request, 'products/detail.html',{'product':product}) @login_required(login_url="/accounts/login") def upvote(request, product_id): if request.method == 'POST': product = get_object_or_404(Product, pk=product_id) product.votes_total += 1 product.save() return redirect('/products/' + str(product.id)) My models.py: from django.db import models from django.contrib.auth.models import User class Product(models.Model): title = models.CharField(max_length=255) pub_date = models.DateTimeField() body = models.TextField() url = models.TextField() image = models.ImageField(upload_to='images/') icon = models.ImageField(upload_to='images/') votes_total = models.IntegerField(default=1) hunter = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def summary(self): return self.body[:100] def pub_date_pretty(self): return self.pub_date.strftime('%b %e %Y') urls.py: from django.urls import path, include from . import … -
Send values from URL to JavaScript
I don't know JavaScript yet, so I got a function online to create and delete new fields on my HTML page, but, I'd like to give it one more function, which I'm not able to do. Here's what I need: I'd like that at the same time I click on it to delete the input field, it would call a function view to also delete the data. To delete the data, I had to create a new link inside the HTML, which is not the best way. Is there a way to make it work? Here's the code. edit.html {% extends 'base.html' %} {% load static %} {% block content %} {% include 'partials/_header.html' %} <style> a:link, a:visited{ color: #006600; } .btn-green{ background-color:#008000 ;color: #FFF; } .btn-green:hover{ color:#fff; background-color: #009900; border-color: #008000; } .btn-ico{ background-color:#008000; padding: 2px 5px; margin-bottom: 10; } textarea { height: 100px; } </style> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous"> <!-- Begin page content --> <main role="main"> <div class="container mt-4"> <form enctype="multipart/form-data" action="" class="form-group" method="POST">{% csrf_token %} <div class="form-group"> {{ form.nome_projeto.label_tag }} {{form.nome_projeto}} </div> {{ form_colab.management_form }} <label>Colaboradores do Projeto:</label> {% for colab in form_colab %} {{ colab.non_field_errors }} {{ colab.errors }} {% for hidden in colab.hidden_fields %} … -
Django annotate using WHEN CASE
I have a question regarding annotation in Django, and inside the annotation I have CASE WHEN conditions, same as in the following example: queryset = queryset.annotate( title=Case(When(title_filter, then=Value("any text")), When(test_filter, then=F('name')), When(test1_filter, then=F('test__name')), output_field=CharField()), key=Case(When(title_filter, then=F('category__id')), When(test_filter, then=F('test_id')), When(test1_filter, then=F('test1__id')), output_field=CharField())) I want to annotate these fileds, title, key. But, we can see that for the each field is applyed the same condition, like Case(When(title_filter), When(category_filter)). There is a posiblity to apply the condintion just once and after that to apply the value for each field ? Like: if title_filter: title = Value("any text") key =then=F('category__id') elif test_filter: title = F('name') key = F('test_id') -
Getting error " Failed building wheel for twisted" while trying to install Django channels in windows10
I was trying to install Django channels but got error: ERROR: Failed building wheel for twisted Running setup.py clean for twisted Failed to build twisted Installing collected packages: twisted, daphne, channels Running setup.py install for twisted ... error ERROR: Command errored out with exit status 1: The screenshot of terminal: How can I solve this problem?