Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TemplateDoesNotExist at / index.html After dividing settings.py into 3seperate files
I was working on a Django project. my urls.py: urlpatterns = [ path('', index, name='index') ] my views.py: def index(request): return render(request, 'index.html') in my settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [(BASE_DIR / "templates")], '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', ], }, }, ] Till this point, all works perfectly, the template also rendered as it should. Now I approach to divide my settings.py into 3 separate files for my production purpose like: Settings (Folder) | base.py | development.py | production.py Here the base.py contains almost all necessary settings, development.py and production.py inherit the base.py and have only allowed host and debug values. development.py and production.py are also properly hooked up with manage.py and wsgi.py file of the project. Now after this work it shows me an error like: TemplateDoesNotExist at / index.html I also try with def index(request): return HttpResponse("Hello, world. You're at the diagnosis index.") It also works perfectly! maybe it only has problem with template/Base dir. Please suggest how can I fix this? -
Two projects use the same Postgres database, and the project on Django
I have two projects that use the same Postgresql database. One of these projects is written with Golange and the other with Django. I have a task in the Django project, to take the data from the table that is created in another project. More precisely I have to take the data from the Clients table, which is not created in Django. There is no information about Clients table on the Django project. Below is how I take the date from the Cook table, which is created in the Django project. How can I take the date from the Clients table in the same way as above? Below are both project repositories, and some screenshots from the database. https://github.com/NarminSH/Go-Client.git https://github.com/NarminSH/Lezzetly Thanks in advance. -
DRF simple-jwt error "detail": "No active account found with the given credentials"
I can create an account with DRF_simple_jwt but when it comes to loging in to that account, it says {"detail":"No active account found with the given credentials"} I tried googling and tried this and more but all in vain . I don't know where the problem lies. here is my serializers.py code from rest_framework import serializers from .models import * from rest_framework_simplejwt.tokens import RefreshToken from rest_framework_simplejwt.serializers import TokenObtainSerializer from django.contrib.auth.hashers import make_password class EmailTokenObtainSerializer(TokenObtainSerializer): username_field = User.EMAIL_FIELD class CustomTokenObtainPairSerializer(EmailTokenObtainSerializer): @classmethod def get_token(cls, user): return RefreshToken.for_user(user) def validate(self, attrs): data = super().validate(attrs) refresh = self.get_token(self.user) data["refresh"] = str(refresh) data["access"] = str(refresh.access_token) class UserSerializer(serializers.ModelSerializer): """ Serializer for user object """ isAdmin = serializers.SerializerMethodField(read_only=True) class Meta: model = User fields = ('id', 'username','isAdmin', 'email','phone','room','hostel') def get_isAdmin(self, obj): return obj.is_staff def validate_password(self, value: str) -> str: """ Hash value passed by user. : param value: password of a user :return: a hashed version of the password """ return make_password(value) and here is code for views.py file class EmailTokenObtainPairView(TokenObtainPairView): serializer_class = CustomTokenObtainPairSerializer and here is urls.py: path("login/", EmailTokenObtainPairView.as_view(), name="token_obtain_pair"), path("refresh/", TokenRefreshView.as_view(), name="token_refresh"), You can ask for further codes. Thanks for helping because you are my last hope. -
How to put the 'non_field_errors' in the end of the form in Django
By default The non_field_errors are placed in the beginning of the form, and I want to place it at the end of the form. This is how I am calling the form : <div ... > {{ form.media }} {% crispy form form.helper %} </div> -
Error while outputting template engine maximum recursion depth exceeded while calling a Python object
The problem is that I get an error when I try to display a block on a page, I don't really know what to do, since I'm working with a template engine for the first time. this is code of views.py class IndexView(generic.ListView): template_name = 'Homepage/index.html' model = Goods context_object_name = 'goods' def sale(request): return render(request, 'articles/sale.html') this is code of index.html {% include "article/sale.html" %} {% block sale %} {% endblock %} this is code of sale.html {% extends "Homepage/index.html" %} {% block sale %} <td class ="sale"> <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/1280px-Image_created_with_a_mobile_phone.png"> <h1 class="description">ОписаниеОписаниеОписаниеОписание</h1> <a class="buy" href="#openModal" > <span >Купить</span></a> <h1 class="price">цена</h1> </td> {% endblock %} This is building a template in the end it gives an error maximum recursion depth exceeded while calling a Python object вот TraceBack -
Get coordinates of click event on image with Django
I am a beginner in Django and writing a Django app for labelling objects in images via bounding boxes. I want users to be able to draw a bounding box on the image and the box coordinates should be saved directly in the db. In my app, the images are already displayed and users can select the object type: However, now I am struggling with how to capture a click event using django. Specifically: How do I capture the coordinates of a click event on the image so I can save the click coordinates in my db? I know how to capture inputs via <input type="..." > but I haven't found a related method to find click coordinates on a grid. I found this great project which contains a more advanced image labeller based on django - but I can't seem to find the code location where the coordinates of a click are saved. I'd be very thankful for hints of which packages/functions to look into to find a solution. -
Django CreateView not working with custom auth model
I have a simple application with a very simple custom user auth model and base manager. When I try to create a user using CreateView, I get no errors and no user entries are made in the database. Here is what I have. models.py: from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.contrib.auth.models import PermissionsMixin from django.db import models class AccountManager(BaseUserManager): def create_user(self, email, username, password, **other_fields): .... .... email = self.normalize_email(email) user = self.model(username=username, email=email, **other_fields) user.set_password(password) user.save() def create_superuser(self, email, username, password, **other_fields): .... return self.create_user(email, username, password, **other_fields) class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) date_joined = models.DateTimeField(default=timezone.now) last_login = models.DateTimeField(default=timezone.now) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = AccountManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def __str__(self): return self.username Here is my forms.py: class CreateUserForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CreateUserForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): # If it's a checkbox, add form-check-input css class, else form-control class if visible.field.widget.__class__.__name__ == forms.CheckboxInput().__class__.__name__: visible.field.widget.attrs['class'] = 'form-check-input' else: visible.field.widget.attrs['class'] = 'form-control' class Meta: model = get_user_model() fields = ('username', 'email', 'password') And here is how I am calling the form in views.py: … -
Celery encoder error with django rest framework
I am using Celery - Redis - Django rest framework together. The error happens when I try to pass the serializer to the delay of celery within the Django rest framework. Here is the viewset class TestSet(viewsets.ModelViewSet): queryset = Test.objects.all() serializer_class = ImageSerializer def create(self, request, *args, **kwargs): serializer = TestSerializer(data=request.data) if serializer.is_valid(): print("I AM HERE") <-- This prints out result = test_call.delay(serializer) <-- The error happens here data = {"task": result.task_id} return Response(data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @shared_task(name="values") def test_call(serializer): ..some logic return serializer The error I get is kombu.exceptions.EncodeError: Object of type ImageSerializer is not JSON serializable I have the following in settings.py CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' -
Testing admin custom action with form
I am developing a small django project to help administrate my dance school(my hobby) So the app has some courses and for each course has many classes or lessons. in the django admin in the course_changelist url i added a custom action create lesson with a custom form CreateLessonsDatesForm with 2 charfield a start_date and a end_date. This actions basically create a lesson of that course. So for example if the course is on weekly basis every Wednesday, the action will automatically create a lesson of that course every Wednesday from the start date until the end date The action works fine on browser but when tested it doesn't create any lesson. I create a second action "prova" just to double check, it simply change the vowels of the place field in all i, without passing any form value, and it works. So probably i am missing something when using the form with the tests. Thanks a lot here's the code: #core/models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, \ PermissionsMixin from django.utils.translation import gettext as _ class Course(models.Model): """ Blueprint course it contain information about what style is taught, the time and place and the frequency """ … -
Use to_representation to combine fields from related models in Django Rest Framework
I've got the following models:- class Player(models.Model): first_name = models.CharField() etc. class Game(models.Model): date = models.DateField() etc. class GameMembership(models.Model): player = models.ForeignKey(Player, related_name="memberships") game = models.ForeignKey(Game, related_name="memberships") available = models.BooleanField(default=False) I've created a ModelViewSet to return all the Players but I'd like to be able to, for each player in the list, return a list of their game memberships. I can do that, quite easily, but the data it returns looks like this:- { "id": "1", "memberships": [ { "available": True, "game": { "date": "a date", etc. } }, { "available": False, "game": { "date": "a date", etc. } } ] } but I'd like to hide the "memberships" aspect of my database from the API users and return something like this instead:- { "id": "1", "games": [ { "available": True, "date": "a date", etc. }, { "available": False, "date": "a date", etc. } ] }, So I want to take a field (or two) from the GameMembership model and combine it with all the fields from the Game model but crucially, I want it all in to one dictionary in the returned results. I know I can simply serialize Game on the GameMembershipSerializer, but that means that I'll be … -
Axios post request to send file using form data in Typescript
I want to send the file from typescript to Django. But Server response content-length=''. But it work well when I send a file using POSTMAN. What am I doing wrong? const form = new FormData(); form.append('file',fs.createReadStream(file_path)); axios.post(URL, form , {headers: form.getHeaders()} ) .then(res => { console.log(`statusCode: ${res.status}`); console.log(res); }) .catch(error => { console.error(error); }) Server (django) class IndexView(View): def post(self, request): print(request.headers) print(request.body) print(request.FILES) Result {'Content-Length': '', 'Content-Type': 'multipart/form-data; boundary=--------------------------630438350591138162261166', 'Host': 'URL', 'User-Agent': 'axios/ 0.24.0', 'Transfer-Encoding': 'chunked', 'Accept': 'application/json, text/plain, */*', 'Accept-Encoding': 'gzip', 'X-App': 'go-proxy', 'X-Forwarded-For': '10.1.20.116, 10.1.20.239'} b'' <MultiValueDict: {}> -
Show DB content in template sorted by date
I'm currently showing the content in the template ordered by sequence_number #models: class FlowPhase(models.Model): sequence_number = models.IntegerField(validators=[MinValueValidator(1)]) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) #viewset # Function to define sort criteria def take_seq_number(elem): return elem['flow_phase']['sequence_number'] def phase_details(request, batch_pk): ph_details_url = API_HOST + "/api/phase_details_full/?batch=" + str(batch_pk) answer = requests.get(ph_details_url).json() if 'results' not in answer: return HttpResponse('<h1>Could not retrieve phase details.</h1>') ph_details = answer['results'] if len(ph_details) == 0: return HttpResponse('<h1>No phase associated to this batch.</h1>') ph_details.sort(key=take_seq_number) # <------ sorting by sequence number rendered_page = render(request, 'batches_phases/consumer/phase_details.html', {'ph_details': ph_details}) return rendered_page So, I want to show the content of ph_details in the template ordered by updated_at and not by sequence_number anymore. Any suggestions on how to do this in python? In this case, I believe that the changes would only be in ph_details.sort(key=take_seq_number) and def take_seq_number(elem): return elem['flow_phase']['sequence_number'] My difficulty is that since sequence_number is integer, it's easier to sort. But how to do this with dates? -
infinite scroll working but not doing things as it should
in my web site i want to show the user ratings for that i used the infinite scroll but i am facing one problem. when it first loads the data before calling the <a class="infinite-more-link" href="?page={{ ratings.next_page_number }}"></a> it is showing the star with the count of vote,but when after calling the <a class="infinite-more-link" href="?page={{ ratings.next_page_number }}"></a> it is not showing the star. my views.py @login_required def ratings_user(request,pk): ratings = VoteUser.objects.filter(the_user_id=pk).order_by('-pk') paginator = Paginator(ratings, 1) page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) return render(request,request.session['is_mobile']+'profile/ratings.html',{'ratings':posts}) html {% extends 'mobile/profile/base.html' %} {% load static %} {% load crispy_forms_tags %} {% load get_companion %} {% load cache %} {% block title %} Ratings {% endblock %} {% block leftcontent %} <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.min.css" rel="stylesheet"> {% endblock %} {% block middlecontent %} <div class="infinite-container"> {% for i in ratings %} <div class="infinite-item"> <div class="w3-container w3-card w3-white w3-round w3-margin"> <img src="{{ i.the_user.profile.avatar.url }}" alt="Avatar" class="w3-left w3-circle w3-margin-right" style="width:40px;height:40px;border-radius:50%;"> <a href ="{% url 'profile' i.the_user_id %}" style="color:black;">{% with user=i.the_user.profile %}{{ user.prenom|title|truncatewords:2 }} {{ user.nom|title|truncatewords:1 }}{% endwith %}</a> <br> <span class="stars" data-rating="{{ i.vote.vote }}" data-num-stars="5" ></span> <hr class="w3-clear"> <p> {{ i.commentaire|linebreaksbr }} </p> <span class="glyphicon glyphicon-user"></span> <a href … -
populate text field based on dropdownlist selection in django models
I have a dropdown list named car_model. I bind it with my t_cars model. What I wanted to happen is, when I choose a car model, the textboxes will be populated with the other car attributes from my car model. Like for example, (sample table) Model=Toyota Price=$2500 Color=Red Model=Nissan Price=$3000 Color=Orange When I select Toyota, the textboxes will be populated with the color and price of the car model Toyota which is $2500 and color orange. I'm sorry for having a hard time explaining it. I hope that someone can help me with this. Here are my codes. models.py class t_cars(models.Model): c_model=models.TextField("Model",max_length=25, blank=True, null=True) c_price=models.FloatField("Price",blank=True, null=True) c_lot=models.TextField("Color",max_length=25, blank=True, null=True) views.py def createCars(request): cars=t_cars.objects.all() context={'cars':cars} return render(request, 'accounts/cars_form.html', context) car_form.html <div> <label>Car Model:</label> <select id='car_model' name='car_model' type="text" onchange="populateTxtBox(this)"> {% for c in car %} <option>{{ c.c_model }}</option> {% endfor %} </select> </div> <label><b>Price: </b></label> <input id='car_price' name='car_price' type="text"> <label><b>Color: </b></label> <input id='car_color' name='car_color' type="text"> script In my script, I'm only trying to show the price first before I proceed to car color but it does not working. function populateTxtBox(){ var model = document.getElementById("car_model"); var selectedOption = model.selectedOption[model.selectedIndex].value; var price=document.getElementById('car_price'); price.value=selectedOption; } -
How to return multiple variables in celery?
The error I get is TypeError: cannot unpack non-iterable AsyncResult object The function is from celery import shared_task @shared_task(name="values", trail=True) def simple(x,y): return x,y x, y = simple.delay(1,2) -
I need people who are confident about Django,I need Help ,Thank you
I have researcing from 3 weeks, but ı couldnt any solution about my problem Can Someone help me, ı severe I will pray for him, I m trying to create an User model and a CellingTable in Django, I created.. but there is a little nightmate in my mind.. user has a local wallet like " user_balance" , user will buy something from "Product Table", Product Table already has priceses by the way, Thats Products( user bought) prices sum, Should be fall from the "user_balance". But I couldnt any example or advice about that stiation. I know Maybe that problem so easy. But again ı know, we guys so perfect for helping eachother. I hope u guys can help me, if u guys help me ı can learn , but no ones dont help eachother, no ones can learn Thank u for ur attention and helping, Good afternoon, Good Evening and Good Night :) -
Large video file upload(like 2gb) in chunk by chunk and add those chunk to get the original file using javascript ajax and django without any api call
My views.py file like this Now I have some problem to stich all the chunks into the file in views.py and also take so much time to upload this video file.Please help. This file upload need to ajax form submit, here I am taking the file and slice it into some specific size of chunk and then send that chunk to our video_upload method. def video_upload(request): video_upload_response = [] curr_time = time.localtime() curr_clock = time.strftime("%H:%M:%S", curr_time) if request.method == 'POST': form = VideosForm(request.POST, request.FILES) if form.is_valid(): course_id = request.POST.get("course_id") print(course_id) video_title = request.POST.get("video_title") print(video_title) video_file_name = request.POST.get("video_file_name") print(video_file_name) video_file = request.FILES['video_file'] # print(list(video_file)) chunk_data = request.POST.get("chunk_data") print(type(chunk_data)) print(curr_clock) if chunk_data == 'null': print("ok") else: chunk_data = bytes(chunk_data, 'ascii') print("hhhhhh") print(type(chunk_data)) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+"/media" file = open(os.path.join(BASE_DIR, video_file_name), 'wb+') file.write(chunk_data) return JsonResponse(video_upload_response, safe=False) (function($) { var reader = {}; var file = {}; var slice_size = 10485760; $(document).on('click', '.video_form_submit', function(event){ form_id = $(this).data("form-id") // console.log(form_id) course_id = $(this).data("course-id") // console.log(course_id) video_title = $("#video_title_"+form_id).val() file = $("#video_id_"+form_id)[0].files[0] csrf_token = $(this).data("csrf-token") $("#progress_process_"+form_id).css('display', 'block'); $("#progress-bar1_"+form_id).css("width", "0%"); $("#progress-text1_"+form_id).html("0 %"); start_upload(event, file, csrf_token, course_id, video_title, form_id); }); function start_upload(event, file, csrf_token, course_id, video_title, form_id) { event.preventDefault(); reader = new FileReader(); file = file console.log(file) upload_file(0, csrf_token, … -
Django: Return id of maximum value where grouped by foreign key
Information I have two models: class BookingModel(models.Model): [..fields..] class BookingComponentModel(models.Model): STATUS_CHOICES = ['In Progress','Completed','Not Started','Incomplete','Filled','Partially Filled','Cancelled'] STATUS_CHOICES = [(choice,choice) for choice in STATUS_CHOICES] COMPONENT_CHOICES = ['Test','Soak'] COMPONENT_CHOICES = [(choice,choice) for choice in COMPONENT_CHOICES] booking = models.ForeignKey(BookingModel, on_delete=models.CASCADE, null=True, blank=True) component_type = models.CharField(max_length=20, choices=COMPONENT_CHOICES) status = models.CharField(max_length=50, choices=STATUS_CHOICES, default='Not Started') order = models.IntegerField(unique=True) [..fields..] What I want I want to get the booking component for each booking which has the last value (maximum) in order. It will also need to have a status='In Progress' and component_type='Soak'. For example for table: +----+------------+----------------+-------------+-------+ | id | booking_id | component_type | status | order | +----+------------+----------------+-------------+-------+ | 1 | 1 | Test | Completed | 1 | +----+------------+----------------+-------------+-------+ | 2 | 1 | Soak | Completed | 2 | +----+------------+----------------+-------------+-------+ | 3 | 1 | Soak | In Progress | 3 | +----+------------+----------------+-------------+-------+ | 4 | 2 | Test | Completed | 1 | +----+------------+----------------+-------------+-------+ | 5 | 2 | Soak | In Progress | 2 | +----+------------+----------------+-------------+-------+ | 6 | 3 | Test | In Progress | 1 | +----+------------+----------------+-------------+-------+ Expected outcome would be id's: 4 & 6 What I've tried I've tried the following: BookingComponentModel.objects.values('booking').annotate(max_order=Max('order')).order_by('-booking') This doesn't include the filtering but returns … -
Django FormModel map fields to HTML Form
I have forms created on my Django site, they have been manually created using HTML and then using JavaScript to POST the form content to the model. Now I am working on updates to the model. I've taken the existing HTML form for the page, but I can't work out how I map the view fields to the HTML form? Views.py def update_event(request,event_id): event = Event.objects.get(pk=event_id) form = addEventForm(request.POST or None, instance=event) return render(request, 'pages/update_event.html', {'event': event, form : form}) models.py class Event(models.Model): project = models.ForeignKey(Game, to_field='project_name', on_delete=models.CASCADE) event_name = models.CharField(max_length=20) event_date = models.DateTimeField(blank=True, null=True) def __str__(self): return str(self.event_name) HTML <div class="col-md-6"> <div class="mb-3"> <label class="form-label" for="event-name-label">Event Name</label> <input type="text" class="form-control" id="event-name" value="" required> <div class="valid-feedback"> Looks good! </div> <div class="invalid-feedback"> Please fill Event name. </div> </div> </div> I've tried using form.event_name but this doesn't work. Any help would be great Thanks -
Django select from multiple models
What is the best way to select data from multiple models? For example class User(models.Model): ... class User_feature1(models.Model): user = models.ForeignKey(User) ... class User_feature2(models.Model): user = models.ForeignKey(User) ... ... class User_feature30(models.Model): user = models.ForeignKey(User) ... If you have 30 tables with foreign key to User table, it will be hard to write 30 select_related queries as User is not the model that holds the foreign key. Even writing raw SQL query is hard with so many models. What is the cleanest method to use? And what is the most performant method? Taking in consideration of calling them from template. Thanks -
How to resolve sql query that is not working in djongo set up
I am using djongo as Sql to Mongodb query convertor in my Django project. However i am facing issues in Server because of Sql queries. Below is the Sql error i am facing while trying to retrieve data in front end UI. raise exe from e djongo.exceptions.SQLDecodeError: Keyword: None Sub SQL: None FAILED SQL: SELECT COUNT(*) FROM (SELECT DISTINCT "engine_task"."id" AS Col1, "engine_task"."project_id" AS Col2, "engine_task"."name" AS Col3, "engine_task"."mode" AS Col4, "engine_task"."owner_id" AS Col5, "engine_task"."assignee_id" AS Col6, "engine_task"."bug_tracker" AS Col7, "engine_task"."created_date" AS Col8, "engine_task"."updated_date" AS Col9, "engine_task"."overlap" AS Col10, "engine_task"."segment_size" AS Col11, "engine_task"."status" AS Col12, "engine_task"."data_id" AS Col13, "engine_task"."dimension" AS Col14, "engine_task"."subset" AS Col15 FROM "engine_task" LEFT OUTER JOIN "engine_segment" ON ("engine_task"."id" = "engine_segment"."task_id") LEFT OUTER JOIN "engine_job" ON ("engine_segment"."id" = "engine_job"."segment_id") WHERE ("engine_task"."owner_id" = %(0)s OR "engine_task"."assignee_id" = %(1)s OR "engine_job"."assignee_id" = %(2)s OR "engine_job"."reviewer_id" = %(3)s OR "engine_task"."assignee_id" IS NULL)) subquery Params: (6, 6, 6, 6) Version: 1.3.4 Below are the versions i am using Django = 3.0.5 mongodb Server = 4.4.6 djongo = 1.3.4 sql parse = 0.2.4 Please help me resolve this issue. -
Django When(...) object SQL missing when used with __in lookup with empty list as value, leading to ProgrammingError
using Django 3.0 (will be upgraded) I get some invalid SQL that leads to a django.db.utils.ProgrammingError, and I wonder if anyone can help me see why. I wonder if this problem also occurs in newer versions of Django. But I hope to get it working without having to upgrade Django right away. Querying a Model I am annotating a field to each instance, and using Case and When with that, and it seems that the error happens when using a negated Q object with a __in lookup that gets an empty list as value. I will show three examples that are very similar, but lead to different SQL. Only the first example leads to erroneous SQL. Example query that leads to invalid SQL: Activity.objects.all() .annotate( employee_authorized=Case( When(~Q(case__assigned_unit__in=[]), then=Value(False)), default=Value(True), output_field=BooleanField(), ) ) This leads to the following SQL, where there's nothing in between WHEN and THEN. This results in a django.db.utils.ProgrammingError. SELECT "activity_activity"."id", ... CASE WHEN THEN False ELSE True END AS "employee_authorized" FROM "activity_activity" LEFT OUTER JOIN "case_case" ON ("activity_activity"."case_id" = "case_case"."id") The below example seems to lead to logical SQL. The only difference being that the Q object is not negated. Activity.objects.all() .annotate( employee_authorized=Case( When(Q(case__assigned_unit__in=[]), then=Value(False)), default=Value(True), output_field=BooleanField(), … -
How to access a table which is present in mysql database in django?
I'm a django beginner and now I got stuck with one issue which is - I'm trying to access a table which is already present in mysql database now I want to render that table on a html page, How can I access that table and render it on html page -
Creating a staff user and giving permissions in Django
I have created a staff user from admin panel for a Django application, but haven't assigned any permissions manually to that user, when I logged in with this staff user credentials I am getting all the permissions by default. I am using custom user but not customised any permissions. please help me with where I am going wrong and how to create a staff user without any permissions by default. -
Django / Blender / Celery / Channels
I found this repository / youtube video https://www.youtube.com/watch?v=42nvLjOv8Ng https://github.com/hophead-ninja/django_blender But Channels has changed quite a bit and I admit I have never tried anything like this with Django before. I have tried to recreate it up using Channels 3.0 - I can get the Webpage up and the Render button "click" does return a 200 from the server - nothing is failing - but the monkey.blend does not render. I do not see my Worker pick up the click I simply get a 200 back from the server Here is my code - maybe together we can make this work. My code is also open source and will be available if we do get it working Here is all of the files and code - if you need anything else please let me know. I do appreciate your help and would love to get the monkey.blend open in a web browser! Thanks for your time. Screenshot of the rendered HTML page /viewer/ html page Which I get a 200 status back and the REDIS IP HTTP GET /viewer/? 200 [0.00, 172.18.0.1:39096] merlin/settings.py CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get('REDIS_URL', 'redis://redis:6379')] }, }, } BLENDER_FILE = ("monkey.blend") …