Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set correct file permissions for sqlite3.db for django website
I am new to django and in the process of deploying a test site to a target production server. I have set-up and run the test locally, all is good. I have moved spawned a new ubuntu server, transferred the files, made the necessary config changes and the site runs fine. However, when I go to register a new user of even to login as an existing one the server throws a 500 error. (i have masked my IP). [Wed Jan 22 12:08:15.233965 2020] [wsgi:error] [pid 19296:tid 139823034910464] [remote x.x.x.x:60559] return Database.Cursor.execute(self, query, params) [Wed Jan 22 12:08:15.234022 2020] [wsgi:error] [pid 19296:tid 139823034910464] [remote x.x.x.x:60559] django.db.utils.OperationalError: attempt to write a readonly database On inspection I noticed that the sqlite3.db file had only root permisions. (I uploaded as root user via ftp). I modified the ownership and permissions for the file, they are now: -rw-rw-r-- 1 root www-data 151552 Jan 22 15:29 db.sqlite3 I have confirmed that www-data is running the site using apachectl -S VirtualHost configuration: *:80 is a NameVirtualHost ....... User: name="www-data" id=33 Group: name="www-data" id=33 What am I missing? On a further note, should I be change the ownership and permissions of the /var/www folder tree to be … -
How to convert string list into python list? [duplicate]
this is the list which is saved into my database in string, I want to fetch it and iterate the list (which is actually in string) in html table. So my question is how to consider this string list to real python list so that i can use it in html table by using for loop. Please help [[1, 'Wide Pushups', 4, 15], [2, 'Burpees', 4, 18], [3, 'Tricep dips', 4, 18], [4, 'Squats', 4, 15], [5, 'Lunges', 4, 16], [6, 'Plank (1 minutes)', 3, 1], [7, 'Side Kicks', 4, 15], [8, 'Knee Raises', 4, 15], [9, 'Leg raises', 4, 15], [10, 'Bicyle Crunches', 4, 15], [11, 'Toe', 'Toucher', 4, 12]] -
Django save many to many form info - autocomplete
Im having trouble trying to save many to many field in a form, I got the "object is not iterable" error, on one field that has many to many relation, Im not sure if its the autocomplete modelselect2 widget, but it also dont let me select more than 1 value (in the admin works fine ) forms.py class Urbaniz_Form(forms.ModelForm): roles = forms.ModelChoiceField( queryset=RolesSII.objects.all(), widget=autocomplete.ModelSelect2(url='roles-autocomplete') ) class Meta(): model = SubdUrb_Solicitud exclude = [] widgets = { 'roles': autocomplete.ModelSelect2(), } def limpiar(self): cd = self.cleaned_data views.py @login_required def crear_urb(request): p_form = Urbaniz_Form() if request.method == 'POST': p_form = Urbaniz_Form(request.POST, request.FILES) if p_form.is_valid(): #VALIDACION DE INFO limpiar() - is_cleaned p_form.limpiar() p_form.save() p_form.save_m2m() messages.success(request, f'Registro de Urbanización creado con éxito') return dom_home(request) else: return render(request, 'b_dom/crear_urb.html', {'form':p_form, 'error':p_form.errors}) else: return render(request,'b_dom/crear_urb.html', {'form':p_form}) class RolAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = RolesSII.objects.all() if self.q: qs = qs.filter(rol__istartswith=self.q) return qs Thanks!! -
django and vue.js production error:nothing shows up after runinng npm build and linking static files in django
i have connected django to vue using webpack loader before running the command npm build everythig was fine by running both terminals everything's working fine but just after running that command and connecting the static file and when i tried to check localhost:8000(defaul django server) i dont see anything not even in console no error and there is nothing here is my base.html file < !DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Question Time</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link href="https://fonts.googleapis.com/css?family=Playfair+Display" rel="stylesheet"> {% block style %} {% endblock %} </head> <body> {% block content %} {% endblock %} </body> {% block js %} {% endblock %} </html> and here is my index.html {% extends "base.html" %} {% load static %} {% block style %} <link rel="stylesheet" href="{% static 'bundle.css' %}"> {% endblock %} {% block content %} <noscript> <strong>We're sorry but frontend doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> </noscript> <div id="app"></div> {% endblock %} {% block js %} <link rel="stylesheet" href="{% static 'bundle.js' %}"> {% endblock %} i have tried removing dist folder from vue i have tried removing all the static links which casused this issue but … -
Django creating table with hyperlink in cells
I want to display table with basic informations about products, and add hyperlink to cells in column "Product name" after clicking which you will be redirected to more detailed description of product with possibility to edtiing, deleting it etc. <table class="table table-striped table-dark"> <thead> <tr> <th scope="col">Product name</th> <th scope="col">Price</th> </tr> </thead> <tbody> {% for element in object %} <tr> <td><div class="btn active"><i class="fa fa-check"></i></div></td> <td> <a href="{% url 'prod_desc' pk:element.pk %}"> {{element.name|lower|capfirst}} </a> </td> <td> {{element.price}} </td> </tbody> </table> How can I connect hiperlink with product name in table? In case is there any walk-around solution ? Is there any restriction about inserting hyperlink in html in general or it's a "Django thing" ? -
I can't save an object through my view. MultiValueDictKeyError at
I'm trying to save a object 'Animal' with the data from my form but im getting a error. This is my view: def addAnimal(request): if request.user.id == None: return render(request, "deny.html") else: if request.method == 'POST': animal_name = request.POST['animal_name'] animal_type = request.POST['animal_type'] animal_age = request.POST['animal_age'] animal_port = request.POST['animal_port'] animal = Animal(animal_name=animal_name, animal_age=animal_type, animal_type=animal_age, animal_port=animal_port) animal.save() return render(request, "home.html", args) This is the model im trying to save: class Animal(models.Model): animal_name = models.CharField(max_length=255) animal_age = models.ManyToManyField(Age) animal_type = models.ManyToManyField(Type) animal_port = models.ManyToManyField(Port) def __str__(self): return self.animal_name And this is my form: <form method="post" class="form-signin" action="{% url 'addAnimal' %}"> {% csrf_token %} <img class="mb-4" src="{% static 'images/logo_transparent.png' %}" alt="" width="300" height="300"> <h1 class="h3 mb-3 font-weight-normal text-white">Adicione o seu Animal de Estimação</h1> <input type="text" id="animal_name" name="animal_name" class="form-control" placeholder="Nome do Seu Animal de Estimação"> <select class="form-control" id="animal_type" name="ration_type"> <option value="Cão">Cão</option> <option value="Gato">Gato</option> </select> <select class="form-control" id="animal_age" name="animal_age"> <option value="Junior">Junior</option> <option value="Adulto">Adulto</option> <option value="Senior">Senior</option> </select> <select class="form-control" id="animal_port" name="animal_port"> <option value="Pequeno">Pequeno</option> <option value="Médio">Médio</option> <option value="Grande">Grande</option> </select> <div> &nbsp</div> <button class="btn btn-lg btn-primary btn-block" type="submit">Adicionar</button> </form> And a print if you nedd so: -
Celery + Django on Windows: debugging asynchronous tasks
With Django 1.8 I used django-celery to run asynchronous tasks and I was able to debug them in my IDE (either PyCharm or Eclipse+PyDev) just launching "python celery worker" in debug mode. django-celery doesn't support Django 2.2, so I have to run pure celery.exe. Celery docs say that I have to add "pdb" to my code and run debug via console. How can I debug these tasks as I did before, adding breakpoints dynamically from my IDE? -
What are Arguments in Python Class Inheritance used for?
When browsing the source code for the django_filters library, I found a class declaration syntax that I've never seen before: inheritance with arguments. I could not find an explanation in the official python class documentation. Here is the source, snippet below: class FilterSet(BaseFilterSet, metaclass=FilterSetMetaclass): pass what does metaclass=FilterSetMetaclass in the class definition do? -
Dispatching Celery Task In Django - Add task.id to the Response
I was wondering, if it were possible to dispatch a Celery task from a Django view, such as: class TaskDispatchViewSet(viewsets.ViewSet): @action(methods=['get'], detail=False, permission_classes=[], url_path='', url_name='') def initiate_task(self, request, pk=None, format=None): task = task.delay() standardized_json_response = responses.standardized_json_response( message='Surfer Waiver List Task Has Been Successfully Dispatched', data=task.id ) return Response(data=standardized_json_response, status=status.HTTP_200_OK) And send back the task.id as part of the response back to the front end? -
Django class based view: passing additional information to the view
I'm very new to Django and a bit overwhelmed by the documentation. I think my problem is pretty simple but everything i've found just confused me more. I am building a little news app with a model NewsItem: from django.db import models from django.utils import timezone # Create your models here. class NewsItem(models.Model): title = models.CharField(max_length=50) newsText = models.TextField() dateEntered = models.DateTimeField('date entered') datePublished = models.DateTimeField('date published', blank=True, null=True) user = models.CharField(max_length=30) #temporary field. will be changed to user foreign key def __str__(self): return self.title def publish(self): if (self.datePublished == None): self.datePublished = timezone.now() def published(self): return self.datePublished != None two views (technically 3) index and detail from django.http import HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from django.urls import reverse from django.views import generic from .models import NewsItem # Create your views here. class IndexView(generic.ListView): template_name = 'news/index.html' context_object_name = 'latestNewsList' def get_queryset(self): return NewsItem.objects.order_by('-datePublished')[:5] #todo class DetailView(generic.DetailView): model = NewsItem template_name = 'news/detail.html' def publish(request, itemId): newsItem = get_object_or_404(NewsItem, pk=itemId) newsItem.publish() newsItem.save() return HttpResponseRedirect(reverse('news:detail', args=(newsItem.id,))) and an urlconf like this from django.urls import path from . import views urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('<int:itemId>/publish', views.publish, name='publish'), ] In the detail view i have a link … -
Materialize carousel not working with Django
Is there a way I can get the materialize carousel to work with Django? I've tried using JQuery and other examples but I can't get it to work when viewing the website in the web inspector, the images are in the resources and have working links but they are not showing up on the page (note the post.getID results in the href being #1!, #2! and so on for how many images in the loop) <head> {% load static %} <!-- Compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" /> <!-- Compiled and minified JavaScript --> </head> <body> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.7/js/materialize.min.js"></script> <h1>POSTSSS</h1> <div class="carousel carousel-slider center"> {% for post in object_list %} <a class= "carousel-item" href="{{post.getID}}"><img src="{{post.cover.url }}" alt="{{post.title}}" /></a> {% endfor %} </div> <script> document.addEventListener('DOMContentLoaded', function() { var elems = document.querySelectorAll('.carousel'); var instances = M.Carousel.init(elems, options); }); </script> </body> Thanks in advance! -
Implementing Session authentication in django rest framework?
I am trying to implement session based auth in drf. I Didnt not understand a thing from django session documentation as well as from drf documentation. I want to have an API endpoint for login , logout and one for listing all users. class Login(APIView): def post(self, request, format=None): email = request.POST.get("email", "") print(request.session) password = request.POST.get("password", "") user = authenticate(request,username=email,password=password) if user is not None: login(request,user) print(user) return Response('yes') else : return Response('No') class UserList(APIView): authentication_classes = (SessionAuthentication,) permission_classes = [ IsAuthenticated, ] def get(self, request, format=None): user = User.objects.all() print(request.user) serializer = UserSerializer(user, many=True) return Response(serializer.data) Settings.py MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] I tried to call login api from browser. Yes it logged in Now when i try to call Userlist view Im getting Authentication details not provided error My client server code (js) for requesting users var myHeaders = new Headers(); myHeaders.append("Content-Type", "application/x-www-form-urlencoded"); console.log(Document.cookie); var urlencoded = new URLSearchParams(); var requestOptions = { method: 'GET', credentials: 'include', headers: myHeaders, redirect: 'follow' }; fetch("http://127.0.0.1:8000/api/", requestOptions) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error)); Please help me understand sessions in drf. -
social-auth-app-django : how to get user's groups
setup: web container: Django 2.2 social-auth-app-django==3.1.0 social-auth-core==3.2.0 keycloak container: pulled jboss/keycloak image. The question is about the code: I am using social-auth-app-django (not python-keycloak), login and logout are already functional. Is there a call that would give me the list of groups that the user belongs to (obviously I am talking about not "django" users and groups but "keycloak" users and groups, which were set up via keycloak admin interface)? I have my pipelines.py file where I am trying to create a custom pipeline to pull this info out of user and backend objects, e.g. print("backend.get_user", backend.get_user(user_id)) this gives me back: {'username': 'xxxx', 'email': 'xxxx', 'fullname': 'xxxx', 'first_name': 'xxxx', 'last_name': 'xxxx'} and print("backend.extra_data", backend.extra_data(user, user_id, response)) gives me back {'auth_time': 1579705033, 'access_token': 'xxxx', 'token_type': 'bearer'} and several other things, with no luck. The documentation Python Social Auth’s documentation did not help. How do I get the list of groups for a given user using whatever is available in social-auth-app-django? -
Render Django Formset Manually
When i render my formset using a loop, everything works. When i try to render it manually by accessing each field separately ( for frontend purpose ) the form is rendering but the submit fail. Every fields are the same, so i guess there is a hidden field created when working with the formset that i dont know about. Here a simplified sample of my working code <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ formset.management_form }} {% for p in formset %} {{p.as_p}} {% endfor %} </form> And a simplified example of what is not working <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ formset.management_form }} {% for p in formset %} {{p.field1}} {{p.field2}} {{p.field3}} ## etc.... {% endfor %} </form> Any idea ? Thanks. -
FormView doesn't update but creates new record of model
I'm using class based views. I'm using a FormView, but open to change to UpdateView if necessary. My main Goal is that after I access my List (name of Model) I can change it's name if desired. URL that acceses a particual List, inside user should see all elements related to that particular list, and can update it's name using a form. path('lista-detalles/<int:lista_id>/', views.ListDetailsFormView.as_view(), name='list_details'), Currently my ListDetailsFormView doesn't update but creates a new record. views.py: from django.shortcuts import get_list_or_404, get_object_or_404 class ListDetailsFormView(LoginRequiredMixin, FormView): form_class = ListForm template_name = "scolarte/listas/lista-detalles.html" def get(self, request, lista_id, *args, **kwargs): context = self.get_context_data(**kwargs) lista = get_object_or_404(List, id=lista_id) data_dict = {'name': lista.name,} form = ListForm(initial=data_dict) context['form'] = form list_items = ListItem.objects.filter(lista=lista) context['list_items'] = list_items total = 0 for list_item in list_items: total += Decimal(list_item.sub_total()) context['total'] = total return self.render_to_response(context) def form_valid(self, lista_id, form): # instance = get_object_or_404(List, id=lista_id) # form = ListForm(request.POST or None, instance=instance) # form = form.save(commit=False) # form.user = self.request.user # form.save() form.instance.name = self.request.name form.save() return super(ListDetailsFormView, self).form_valid(form) def get_success_url(self): return reverse_lazy('lists:list_details', kwargs={'lista_id': self.kwargs['pk']}) BONUS: I'd like to return to the same page, the one that shows the current List and it's items. -
DJANGO - AJAX - REQUIRED ID
I have this form: <form method="POST" id="solver_args-form">{% csrf_token %} {% for field in form.visible_fields %} <div class="form-group"> {{ field.label_tag }} {{ field }} </div> {% endfor %} <button type="submit" class="btn btn-primary">Submit</button> </form> Unfortunately, this {{ field }} creates an inputwith a required idattribute, instead of an idattribute: <input type="text" name="name" value="blabla" maxlength="20" required id="id_name"> I need the idattribute for the ajax function: $(document).on('submit', '#solver_args-form',function(e){ $.ajax({ type:'POST', url:'{% url "create" %}', data:{ name:$('#id_name').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, success:function(json){ document.getElementById("solver_args-form").reset(); }, error : function(xhr,errmsg,err) { console.log(xhr.status + ": " + xhr.responseText); } }); }); So, I tried to replace the required idattribute with the idattribute: $('form-group').each(function(){ xinput = $(this).find('input'); xinput.attr('required id','id'); }); But, 1 this does not work and 2 Im not sure if this is the way to do it. No errors in console and the page does refresh when I submit the form. Thank you for any help -
getaddrinfo failed! I don't know what's causing this error
I have been using sendgrid for few months now when i setup to build a new application using django allauth as it's authentication system,i am getting this error getaddrinfo failed.i stakcoverflowed it but I couldn't find any reasonable answer that could solve my problem. Here's my sendgrid code SEND_GRID_API_KEY= "SENDGRID API KEY" EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = "SENDGRID ACCOUNT USERNAME" EMAIL_HOST_USER_PASSWORD = "SENDGRID ACCOUNT PASSWORD" EMAIK_PORT=587 EMAIL_USE_TLS=True DEFAULT_FROM_EMAIL="SENDGRID ACCOUNT EMAIL" EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' The error i am getting like this [Errno 10047] getaddrinfo failed Exception Type: gaierror -
Is there a way to store a tuple in an attribute instance in Django?
I am wondering if it is possible to store a tuple in a attribute instance in Django? Something like: class MyModel(models.Model): my_tuple_field = TupleField() and then create an instance of MyModel as follow: an_instance = MyModel.objects.create(my_tuple_field=('foo', 'bar')) Thanks, -
Breadcrumb dynamic content
I have a simple breadcrumb which is working great. But I want to add a feature, that every < li > tag is going to be displayed depending on the user's group. So if the user is in group sample1, only the sample1 tag will be visible in the breadcrumb. Also, if the user is in the sample1 and sample2 group, both tag's will appear. So I need something like this : def bc(request): user_groups = request.user.groups.all() context = {'user_groups': user_groups} return render(request, 'opportunity/opp_breadcrumb.html', context) opp.breadcrumb.html : <ul id="bread" class="breadcrumb"> {% for group in user_groups %} {% if group.name == 'Sample1' %} <li class="breadcrumb-item"><a href="{% url 'opportunity:sample1' %}">Sample1</a></li> {% elif group.name == 'Sample2' %} <li class="breadcrumb-item"><a href="{% url 'opportunity:sample2' %}">Sample2</a></li> {% elif group.name == 'Sample3' %} <li class="breadcrumb-item"><a href="{% url 'opportunity:sample3' %}">Sample3</a></li> {% elif group.name == 'Sample4' %} <li class="breadcrumb-item"><a href="{% url 'opportunity:sample4' %}">Sample4</a></li> {% endif %} {% endfor %} <div class="ml-auto"> <li style="margin-right: 20px"> <a href="{% url 'opportunity:pdf' %}" target="_blank"> <i class="fa fa-file-pdf-o" aria-hidden="true"></i> </a> </li> </div> <li class=" breadcrumb-item" style="margin-right: 20px"><a href="{% url 'opportunity:sample5' %}">Sample 5</a></li> </ul> But as you can suppose, this logic is not working at all. -
How can I throw pk to forms.py django
moneylog get relation with moneybook, and when i create moneylog, I wanna moneybook of moneylog choose default=moneybook.pk and these are my codes. moneylog/model.py moneybook = models.ForeignKey( moneybook_models.Moneybook, on_delete=models.CASCADE) moneylogs/urls.py app_name = "moneylogs" urlpatterns = [ path("create/<int:pk>/", views.moneylog_create.as_view(), name="create"), moneybooks/detail.html <a style="display:scroll;position:fixed;bottom:50px;right:30px;" href="{% url 'moneylogs:create' pk %}"> <div class="rounded-full h-16 w-16 flex items-center justify-center bg-red-400 text-bold font-bold text-white">+</div> </a> so if i click the + button, then moneylogs/views.py class moneylog_create(FormView): form_class = forms.CreateMoneylogForm template_name = "moneylogs/create.html" def form_valid(self, form): moneylog = form.save() moneylog.save() return redirect(reverse("cores:home")) moneylog/forms.py class CreateMoneylogForm(forms.ModelForm): class Meta: model = models.Moneylog form.fields['moneybook'].initial = moneybook_models.Moneybook.objects.get( pk=pk) fields = ( "pay_day", "payer", "dutch_payer", "price", "category", "memo", ) widgets = { "dutch_payer": forms.CheckboxSelectMultiple } def save(self, *args, **kwargs): moneylog = super().save(commit=False) return moneylog but it doesn't work. as you see.. how can i transfer moneybook.pk to moneylogs forms.py? or how can achieve moneybook belongs to moneybook default? -
How to config django media folders?
I have Django v 3.0. My requirements. I try to open media link but I get an error that the path / file doesn't exists. In my settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, "templates") STATIC_DIR = os.path.join(BASE_DIR, "static") STATIC_ROOT = os.path.join(BASE_DIR, "assets") MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'assets', 'media') STATIC_URL = '/assets/' STATICFILES_DIRS = [ STATIC_DIR, ] STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR, ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', ], }, }, ] my urls.py urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I don't know how to going on and need your help -
How to make only part of text to be a clickable link
So I'm developing a django app. I have a template which takes text as a variable. I make only part of that text a clickable link. For example I have a text "Today is John Smith's birthday" and I need "John Smith" to be an href while the other text is not. Can you help me with that please. -
How to annotate only to a few instances in a queryset?
So I have a queryset of 'Post' objects. I want to annotate 'user_voted' the 'Post' objects that are created by a specific user. In the end I want to send all the 'Post' objects to the template, even those that are not annotated with 'user_voted'. How do I do that? Thank you very much! -
In Django queryset: how to annotate a Subquery, which returns more than one row?
I am trying to annotate to the queryset a Subquery, which returns more than one row. I need to annotate first value of Subquery. picture_url = Picture.objects.filter( product_id=OuterRef('pk'), is_3d=False ) final_queryset = final_queryset.annotate(picture_url_exists=Exists(picture_url))\ .annotate(picture_url=Case(\ When(picture_url_exists=True, then=Subquery(picture_url.values('pk'))),\ default=Value(0) )) I have tried to add first() if (add_name_translation): picture_url = Picture.objects.filter( product_id=OuterRef('pk'), is_3d=False ).first() But I received this error: ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. Also I have tried to take first value like with this [:1] final_queryset = final_queryset.annotate(picture_url_exists=Exists(picture_url))\ .annotate(picture_url=Case(\ When(picture_url_exists=True, then=Subquery(picture_url.values('pk')[:1])),\ default=Value(0) )) But I received this error: AttributeError: can't set attribute As mentioned before I need to annotate first value of Subquery. What am I missing? -
Creating a Django object with field values from a SELECT equivalent
I am trying to figure out how to reproduce the following using Django - anyone help? INSERT INTO table1 (table2_id, a_field) SELECT table2.id as table2_id, table3.a_field FROM table2 INNER JOIN table3 ON table3.table2_id == table2.id WHERE table2.id = 123 If I've got this correct (not my original query ;-) ), this is doing the following: Creating an entry in table1 where... a field named table2_id will match the id of a row in table2 and a field named a_field will match the same named field in a_field in a row of table3 and the table2/table3 objects from which these values are read are identified by a shared table2.id/table3.table_id2 relationship and also the table2 id being 123. I don't see how such "calculated" field values can be passed to a create() or get_or_create() style command. It this perhaps possible using Q() objects?