Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Annotating specific attributes of a Datetime Field - Cannot resolve keyword 'toordinal' into field. Join on 'created_at' not permitted
I'm developing a scoring system for posts on a website. It considers other relational fields (comments, views, and reactions_emojis) to have a more insightful way to order the results. But since it's not desirable to have popular posts, but too old, on the front page, I decided to consider the post creation time. The problem is, the DateTime value is too precise, and ordering by it would completely ignore the scoring system and return a simple chronological feed. While testing some solutions, I tried the toordinal built function to have a single value representing the days passed since January 1 of year 1. My idea was to concatenate this value with the post_hour and the result of (post_minute // 14). This way, there would be a 14 minutes window in which all posts would be ordered exclusively by their scores. It looks good enough, and any adjustments would be simple to make. Looking along with some SO posts and Django documentation, I found that I could do this by passing the attribute I was trying to access with a dunder inside an F expression: posts = Post.objects.all().annotate( score=((F("view_count")/20) + (Count("post_emojis")/10) + (Count("post_comments")/5)), ordinal_time=(F('created_at__toordinal')) ) This returns the following error: Cannot … -
Display multiple views in single page
I have a Django Webapp which has a few forms for adding data to the database. Once this data has been added, I want to present this on a dashboard. So I have views that were written that add the logic for the data to be presented, but as far as i can work out you only map 1 view to a template otherwise the data won't be displayed on the template. I think there is a way to pass the data as a context, but I can't get my head around how to write this for my view. A really simple view i have to display events def all_events(request): event_list = Event.objects.all() return render(request, 'pages/event_list.html',{'event_list': event_list}) I'm passing this to event_list which works fine. But if I % include % on the dashboard I get the HTML but not the data, which I now understand is right. But being an absolute bigger with Django, I could really do with an example of the above which I can then apply to all my other views. Thanks -
Python/Django looping over request object and display in a table
Hi so I have a file called b2c2.py where I am making a request to return my balances this request returns b'{"LTC":"0","DOG":"0","USD":"51075.676738623","ADA":"9493.1937","ETH":"3.4E-9","UST":"2977","LNK":"42.422","XLM":"0","GBP":"-58153.761361914","USC":"0.9999995","XRP":"78448.38","EOS":"0","BNB":"0","BTC":"-0.250000004644","EUR":"0.0026082","BCH":"0","DOT":"0","UNI":"0","AUD":"0","CAD":"0","CHF":"0","CNH":"0","ETC":"0","ICP":"0","JPY":"0","KSM":"0","MXN":"0","NZD":"0","SGD":"0","TRX":"0","XAU":"0","XMR":"0","XTZ":"0","ZEC":"0"}' I then pass this into my views.py called b2c2_response_content and pass it into the context, in my template I am then trying to loop through it to show the balance name and balance holdings in a table. But I am unsure on how I can do this for example I want it to display as bitcoin name in a column with its quantity in the column next to it and Ethereum in the row below with its name in one column and its quantity in the next column. Thank you for your help in advance. -
Django - Delete db entry when ForeignKey was deleted
So I am having trouble to solve this issue, even though I thought I understood the on_delete function. I have a model called Project and a model called UserProject. In the Userproject I have two foreign Keys pointing to a User and a Project. What I tried was to use on_delete = CASCADE on the project-Foreign Key. This seems to only affect the Project-field in the Userproject model. So when I delete a Project wich also has Userproject entries, those dont get deleted. How could I achieve this? from django.db import models from django.contrib.auth.models import User # Create your models here. class Project(models.Model): id = models.AutoField(db_column = 'db_ID', primary_key = True) name = models.CharField(max_length=500, default = None) descriptor = models.CharField(max_length = 1000, null = True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'projects' def __str__(self): return self.name class Userproject(models.Model): id = models.AutoField(db_column = 'db_ID', primary_key = True) user = models.ForeignKey(User, on_delete= models.SET_NULL, null = True) project = models.ForeignKey('Project', on_delete = models.CASCADE,default = 1, null = True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null = True) class Meta: db_table = 'UserProjects' def __str__(self): return self.id -
Download file in Nginx-Django with X-Accel-Redirect
I have a Django webpage running on Nginx-Uwsgi. I want to let the user download files of over 10GB. For this purpose, I am using X-Accel-Redirect. The idea is that the user should go to http://XXX.XX.XX.XX/main/download and there it can download a file. After several configurations, now I get a 403 HTTP error on the browser and the following trace on Nginx: 2021/11/11 16:11:45 [error] 29309#0: *1 open() "/home/myuser/direct/example.txt" failed (13: Permission denied), client: 2.136.173.243, server: _, request: "GET /main/download HTTP/1 My Nginx configuration is as follows: events { worker_connections 10000; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; client_max_body_size 128M; proxy_max_temp_file_size 0; proxy_buffering off; server_names_hash_bucket_size 256; # Load modular configuration files from the /etc/nginx/conf.d directory. # See http://nginx.org/en/docs/ngx_core_module.html#include # for more information. include /etc/nginx/conf.d/*.conf; upstream django { server 127.0.0.1:8000; } server { listen 80 default_server; listen [::]:80 default_server; server_name _; root /usr/share/nginx/html; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; location /download { internal; alias /home/myuser/direct; proxy_max_temp_file_size 0; } location /main { uwsgi_pass django; uwsgi_param Host $host; uwsgi_param X-Real-IP $remote_addr; … -
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