Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Set specific valdiation rule in UpdateView
I set an UpdateView class to update data of user's markers. I have a Marker model with a field category. I want to have one and only "Where I live" category marker in all the user's markers. Is there a way to create a function in the UpdateView class to invalidate the form if there too many "Where I live" markers. class UpdateMarkerView(UpdateView): model = Marker fields = ["name", "description", "category"] template_name = "map/detail.html" success_url = "/" class Marker(models.Model): WIL = "WIL" WIWG = "WIWG" WIW = "WIW" IDK = "IDK" CATEGORY_MARKER = [(WIL,"Where I live"), (WIWG, "Where I want to go"),(WIW,"Where I went"),(IDK,"I don't know")] user = models.ForeignKey(User,blank=True, null=True,on_delete = models.SET_NULL) name = models.fields.CharField(max_length=100) description = models.fields.CharField(max_length=100) lat = models.fields.DecimalField(default=False, max_digits=5, decimal_places=3) lon = models.fields.DecimalField(default=False, max_digits=5, decimal_places=3) category = models.CharField(max_length=50, choices = CATEGORY_MARKER, default = IDK) I've already done it with a basic function but I can't find a way to it with a generic view if it's possible. -
Automate update database
i have application for dailyhours for work,i just looking around about specific hour will be run script to check database if some value are None will be add value to database. So my question is i need do this with some script with rest api or maybe django-celery will be okay for that ? example: start:8:00 end:12:00 daily:4:00 but sometimes if you forget close work you need change value for some workers in PA so i wanna create script which will be do it automate everyday if value are None -
customer registration not showing in django admin
Trying to create customer registration form for ecommerce website . No errors while submitting the form, but details are not shown in django admin . Here are required codes : models.py class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField(max_length=200) address = models.CharField(max_length=200, null=True, blank=True) joined_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.full_name urls.py urlpatterns = [path("register",views.register, name="register")] forms.py class CustomerRegistrationForm(forms.ModelForm): username = forms.CharField(widget=forms.TextInput()) password = forms.CharField(widget=forms.PasswordInput()) email = forms.CharField(widget=forms.EmailInput()) class Meta: model = Customer fields = ["username", "password", "email", "full_name", "address"] def clean_username(self): uname = self.cleaned_data.get("username") if User.objects.filter(username=uname).exists(): raise forms.ValidationError( "Customer with this username already exists.") return uname views.py def register(request): form = CustomerRegistrationForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") email = form.cleaned_data.get("email") user = User.objects.create_user(username, email, password) form.instance.user = user return redirect("/") return render(request,"register.html",{'form':form}) register.html {% load crispy_forms_tags %} <div class="container"> <div class="row"> <div class="col-md-6 mx-auto"> <h3>Customer Registration Form</h3><hr> <form action="" method="POST"> {% csrf_token %} {{form|crispy}} <button class="btn btn-primary" >Register as a Customer</button> </form> <p> Already have an account? <a href="/home">Login here</a></p> </div> </div> </div> Thank you in advance:) -
Duplicate Django Admin functionality to Add/Edit Related Field
I am looking to duplicate the functionality of Django Admin that displays related fields in a dropdown list and allows one to edit a selected object or add a new object. Digging into the Django admin code, the add/edit button open a popup and set the IS_POPUP_VAR, but I lose the trail from there. What functionality does django.contrib.admin utilize to refresh the dropdown list with related objects once that set of objects is updated, and where is it located in the source (to be used as an example)? -
Where the right place to put recurrent function in Django
I want to make a function that will be used in different parts of my application. It is a function to send email notifications, something like: def mail_notification(): subject = 'New Product' from_email = 'master.aligabra@gmail.com' to = 'ali.corretor.imoveis@gmail.com' html_content = render_to_string('email/new_message_product_client_email.html') msg = EmailMultiAlternatives(subject, html_content, from_email, [to]) msg.content_subtype = "html" msg.send() My doubt is, in a View, signals.py, forms.py, Django have a "right" place or is where i prefer? -
How to return Modal processing result to Modal
I want to display the search screen in the modal screen and display the search processing results on that modal screen. Search result display is completed with modal. But,In my writing style, when I press the process button in modal, the result is displayed on another screen instead of modal. What should I do? I'm using Modal with Ajax in Django. Ajax is a beginner. I found this as a result of my research, but it didn't work. <head> <base target="_self"> </head> Ajax function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function (xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $(function(){ $('#edit_foo').on('click', function (event) { event.preventDefault(); var form = $('form')[0]; var formData = new FormData(form); var form … -
using if is giveing me different results in the same cod
as show in pic, why is this happen to ( Iron - Fe )( Carbon - C)( Nitrogen - N)( Phosphors- P) only the ( Sulfur - S) is working good whitout problem my html cod is: {% if object.Iron_Fe != '-' %} <tr type="hidden> <td style="text-align:left">Iron - Fe</td> <td>{{ object.Iron_Fe }}</td> </tr> {% endif %} {% if object.Carbon_C != '-' %} <tr type="hidden> <td style="text-align:left">Carbon - C</td> <td>{{ object.Carbon_C }}</td> </tr> {% endif %} {% if object.Nitrogen_N != '-' %} <tr type="hidden> <td style="text-align:left">Nitrogen - N</td> <td>{{ object.Nitrogen_N }}</td> </tr> {% endif %} {% if object.Phosphorus_P != '-' %} <tr type="hidden> <td style="text-align:left">Phosphorus - P</td> <td>{{ object.Phosphorus_P }}</td> </tr> {% endif %} {% if object.Sulfur_S != '-' %} <tr type="hidden"> <td style="text-align:left">Sulfur - S</td> <td>{{ object.Sulfur_S }}</td> </tr> {% endif %} -
CSS styling doesn't apply on a Django Project
I am trying to style my textarea for wiki project. There already exists a default CSS and I added background-color to test if it works but it doesn't change. I have restarted the program to load static files but nothing changes. Can you help me please? Here's the html page: {% extends "encyclopedia/layout.html" %} {% block title %} Create New Page {% endblock %} {% block body %} <h1>Create New Page</h1> <form action="{% url 'new_page' %}" method="POST"> {% csrf_token %} <input type="text" name="title" placeholder="Title"> <textarea name="new_entry" id="new_entry"></textarea> <input type="submit" name="save_entry" id="save_entry" value="Save"> </form> {% endblock %} CSS: textarea { height: 90vh; width: 80%; background-color: black; } And layout.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static 'encyclopedia/styles.css' %}" rel="stylesheet"> </head> <body> <div class="row"> <div class="sidebar col-lg-2 col-md-3"> <h2>Wiki</h2> <form action="{% url 'search' %}" method="GET"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> <div> <a href="{% url 'index' %}">Home</a> </div> <div> <a href="{% url 'new_page' %}">Create New Page</a> </div> <div> <a href="{% url 'random' %}">Random Page</a> </div> {% block nav %} {% endblock %} </div> <div class="main col-lg-10 col-md-9"> {% block body %} {% … -
How do you pass two parameters through url in django
I want to pass two parameters through url in django. First of all, here is my current html: {% for lesson in lessons %} {% for class in lessons %} <a href="{% url 'next-page' lesson.pk %}">Link to next page {{lesson}} {{class}}</a> {% endfor %} {% endfor %} And this is my url: path('nextpage/<int:pk>/', ListView.as_view(), name='next-page'), However, I want something like below: {% for lesson in lessons %} {% for class in lessons %} <a href="{% url 'next-page' lesson.pk class.pk %}">Link to next page {{lesson}} {{class}}</a> {% endfor %} {% endfor %} and my url is: path('nextpage/<int1:pk>/<int2:pk>', ListView.as_view(), name='next-page'), Then I want to be able to access the primary keys in my view below: class LessonList(generic.ListView): model = Lesson template_name = 'lesson_list.html' context_object_name = "lessons" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) lesson_id = self.kwargs['pk1'] class_id = self.kwargs['pk2'] return context Obviously, the above code does not work. However, I want to basically be able to pass two parameters in the url, and access both of them in my view's get_context_data. Thank you, and please leave any questions you might have. -
Unable to run collectstatic , "references a file which could not be found: js/canvas-to-blob.min.js.map"
I'm trying to deploy a django react application on heroku , which uses whitenoise to handle staticfiles and cloudinary to handle media files , but when i try to run python manage.py collectstatic it returns an error 'js\canvas-to-blob.min.js' references a file whic could not be found , so i used the find static command to find the static file and discovered it was in the virtualenv folder (venv\Lib\site-packages\cloudinary\static\js\load-image.all.min.js ) and it belongs to cloudinary , when i comment out all its content , collectstatic works fine , pls is there any way to fix the error -
How to overcome locations field caught empty in validated data?
I've a model: class ListingPrice(Timestamps): price = models.ForeignKey("Price", on_delete=models.CASCADE) location = models.ForeignKey("location", on_delete=models.CASCADE) class Meta: unique_together = ["price", "location"] class Price(Timestamps): package = models.ForeignKey("products.Package", on_delete=models.CASCADE) locations = models.ManyToManyField("location", through="ListingPrice") price = models.DecimalField(max_digits=11, decimal_places=3) with a serializer: class LocationSerializer(serializers.ModelSerializer): name = LocalizedField() class Meta: model = location fields = ['id', 'name'] class PriceSerializer(serializers.ModelSerializer): locations = LocationSerializer(many=True) class Meta: model = Price fields = ['package', 'locations', 'price'] def create(self, validated_data): print("validated_data, validated_data) and viewset: class PriceViewSet(ModelViewSet): queryset = Price.objects.all() serializer_class = PriceSerializer ordering = ['id'] permissions = { "GET": ["view_minimum_listing_price", ], "POST": ["add_minimum_listing_price", ], 'PUT': ['update_minimum_listing_price', ], 'DELETE': ['delete_minimum_listing_price', ], } In testing I'mm using the following: data = { "price": 12, "package": self.package.id, "is_enabled": False, "location": [{'name': self.location.name, 'id': self.location.id}] } response = self.client.post(path=self.url, data=data, format='json') locations appear as empty dict in validated_data? I need to caught it and added it to the price by locations.add. how to implement this? -
How can I let the user add a new field in a Django-form dynamically, instead of letting them append the entire form at every addition?
In forms.py: class BillGateway(forms.Form): from_date=forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}), label='From ', label_suffix=' - ') to_date=forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}), label='To ', label_suffix=' - ') billing_date=forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}), label='Date of Billing ', label_suffix=' - ') rt_cash_amount_desc=forms.CharField(label='RT Cash Amount Description', label_suffix=' - ', required=False) rt_cash_amount=forms.DecimalField(label='RT Cash Amount', label_suffix=' - ', required=False) other_desc=forms.CharField(label='Other Head', label_suffix=' - ', required=False) other_amount=forms.DecimalField(label="Other Head's Amount", label_suffix=' - ', required=False) In views.py: def bill_gateway_view(request): if request.method=='POST': fro=request.POST.get('from_date') to=request.POST.get('to_date') bill_date=request.POST.get('billing_date') rt_cash_desc=request.POST.get('rt_cash_amount_desc') rt_cash_amount=request.POST.get('rt_cash_amount') other_desc=request.POST.get('other_desc') other_amount=request.POST.get('other_amount') request.session['fro']=fro request.session['to']=to request.session['bill_date']=bill_date request.session['rt_cash_desc']=rt_cash_desc request.session['rt_cash_amount']=rt_cash_amount return HttpResponseRedirect('/provisional_bill/') else: form=BillGateway() return render(request, 'account/bill_gateway.html', {'form':form}) In templates: <form action="" method="post" novalidate> {% csrf_token %} {{form.as_p}} <button type="submit" id="savebtn">Proceed</button> </form> Now, what I want to achieve is to let the user extend the other fields, both, the other_desc and other_amount if he/she needs to fill in more details in the bills. I'm fairly new to this concept. I have seen some tutorials in which the tutors mainly used htmx to achieve such things and seemed pretty cool and easy but what they did was adding the whole form again upon clicking the add button. I just want the user to be able to add these two fields only and not the entire form. How can I achieve this? I have spent my whole day looking … -
What will happen if I push changes from one branch to another?
I have two branches in my project. main and test_deploy It's incorrect to push changes without any tests to the main branch, but never mind. I use the main branch to make some changes locally and the test_deploy where I have other changes in settings.py (for example DEBUG=False, use a cloud for storing my model images and so on) and files for deployment(Procfile, runtime.txt and so on). For example, I'm going to add a new app and push it to the main branch and to the test_deploy branch too(to get the newest version of my project) I have a question. What will happen if I commit these changes to the main branch, push it to this branch AND also push it to the test_deploy branch? Will I have conflicts that I'll have to fix manually? Or I have firstly pull all files from the test_deploy branch and then push it?(I don't wanna pull files from the test_deploy branch. That's why I asked this question) Summary So, generally, I wanna push changes from the main branch to test_deploy, but without pulling separate files from the test_deploy branch, because they are superfluous on the main branch which I use locally. -
How to keep track of attendance in django project
I have a project in which two different models have cyclic many-to-many relation. Models are "Training" and "Student", where a student can enroll to many trainings and vice-versa, so i want to keep track of attendance of each student for each training. How can i achieve this in django? -
How do you create next and previous buttons for django lists?
I want to basically create a previous and next button so that the dates of a list would change on the same page (next means next day, and previous means previous day). Here is the generic list view I am using: class LessonList(generic.ListView): model = Lesson template_name = 'lesson_list.html' context_object_name = "lessons" def get_queryset(self): today = datetime.datetime.today() queryset = Lesson.objects.filter(date=today) return queryset Here is my html: {% for lesson in lessons %} <h1> {{lesson}} </h1> {% endfor %} And here is my model: Lesson(models.Model): name = models.CharField(max_length=100) date = models.DateField(null=True, blank=True) I did not mention it in the above code, but this list view already takes a primary key through the url, so I need another way of transferring the date value of the list to the next page when I click either the next or previous button. Is there any way I can do this? I would appreciate it if you guys could write the full code based on the code I have given in this question. If you have any questions, please leave a message. -
share media between multiple django(VMs) servers
we have deployed a django server (nginx/gunicorn/django) but to scale the server there are multiple instances of same django application running. here is the diagram (architecture) each blue rectangle is a Virtual Machine. HAProxy sends all request to example.com/admin to Server 3.other requests are divided between Server 1 and Server 2.(load balance) Old Problem: each machine has a media folder and when admin Uploads something the uploaded media is only on Server 3.( normal users can't upload anything ) we solved this by sending all requests to example.com/media/* to Server 3 and nginx from Server3 serves all static files and media. Problem right now we are also using sorl-thumbnail. when a requests comes for example.com/,sorl-thumbnail tries to access the media file but it doesn't exist on this machine because it's on Server3. so now all requests to that machine(server 1 or 2) get 404 for that media file. one solution that comes to mind is to make a shared partition between all 3 machines and use it as media. another solution is to sync all media folders after each upload but this solution has problem and that is we have almost 2000 requests per second and sometimes sync might not … -
Display Todo under its category [Django]
I'm not sure how to ask this question but I'll give it a shot. I am writing a Todo application and want to display each todo under its respective category in the template. For example Display each category {% for category in categories %} <h2>{{ category.name }}</h2> Now show each todo that falls under the above category {% for todo in todos %} <p>{{ todo.description }}</p> {% endfor %} {% endfor %} How do I create a queryset that will give my this type of structure? Or is there are different way to achieve this? If something is unclear or require more info let me know and I'll add it to the post Any help is appreciated, thank you. Models class Category(models.Model): name = models.CharField(max_length=20) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.name class Todo(models.Model): # Priority choices PRIORITY_CHOICES = ( ("bg-danger", "High"), ("bg-info", "Normal"), ("bg-warning", "Low"), ) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) description = models.CharField(max_length=255) priority = models.CharField(max_length=200, choices=PRIORITY_CHOICES, null=True) completed = models.BooleanField(default=False) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) category = models.ManyToManyField(Category) def __str__(self): return self.description View def todo_listview(request): template_name = "todos/listview.html" context = { "todos": get_users_todos(user=request.user), "categories": Category.objects.all(), } return render(request, template_name, context) -
trying to plot d3.js heatmap django backend
Trying to plot heatmap from data, group variable and value, in inspect element the data shows fine data example : data = [ {group: 'HIV-1 protease', variable:'None', value: 30 }, {group: 'HIV-1 protease', variable:'ZINC03915219', value: 0.37 }, {group: 'HIV-1 protease', variable:'ZINC27425989', value: 0.38 }] views.py def search_result(request): if request.method == "POST": ChemSearched = request.POST.get('ChemSearched') tarname = BINDLL.objects.filter(targetnameassignedbycuratorordatasource__contains=ChemSearched).exclude(ki_nm="") return render(request, 'Search/search_result.html', {'ChemSearched':ChemSearched, 'tarname':tarname}) else: return render(request, 'Search/search_result.html',{}) <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <!-- Load d3.js --> <script src="https://d3js.org/d3.v4.js"></script> <!-- Create a div where the graph will take place --> <div id="my_dataviz"></div> <!-- Load color palettes --> <script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script> <title>Search_results</title> </head> <body> {% if ChemSearched %} <script> data = [{% for Bindll in tarname %} {group: '{{ Bindll.targetnameassignedbycuratorordatasource }}', variable:'{{ Bindll.zincidofligand}}', value: {{Bindll.ki_nm}} }, {% endfor %}]; function(data) { var myGroups = d3.map(data, function(d){return d.group;}).keys() var myVars = d3.map(data, function(d){return d.variable;}).keys() // Build X scales and axis: var x = d3.scaleBand() .range([ 0, width ]) .domain(myGroups) .padding(0.05); svg.append("g") .style("font-size", 15) .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x).tickSize(0)) .select(".domain").remove() // Build Y scales and axis: var y = d3.scaleBand() .range([ height, 0 ]) .domain(myVars) .padding(0.05); svg.append("g") .style("font-size", 15) .call(d3.axisLeft(y).tickSize(0)) .select(".domain").remove() // Build color scale var myColor … -
How to use Django + Cloudinary for images + Heroku?
I have some models with the ImageField. If I load an image for a new Django model, it disappears after 1-2 hours. I suppose it's because Heroku doesn't save images. How can I connect my django project, cloudinary and heroku together? -
how to design front-end of blog page with tailwind which renders data of a ckeditor django form which contains images, code snippets and text
{{blog_obj.content|safe}} //this is the rendered part of the blog which contains the main contents of the blog. But the image sometimes has a large width which is destructuring the whole page. Is there a way to fix this? -
How To Use Child Loop value as a key in Parent Loop in Django template?
I am trying to read a dynamic uploaded CSV file and want to show it on HTML Page. Backend Code using to read CSV file = request.FILES.get('file') decoded_file = file.read().decode('utf-8').splitlines() records = csv.DictReader(decoded_file) headers = records.fieldnames rows = [] for row in list(records): rows.append(dict(row)) main_data = { 'headers':headers, 'records':rows } Am passing this main_data passing to the front end as context. And then on the template, I am using below code <thead class="table-dark"> <tr> {% for header in headers %} <th scope="col">{{header}}</th> {% endfor %} </tr> </thead> <tbody> {% for row in records %} <tr> {% for header in headers %} <td> {{row.header}} This is coming blank {{header}} # This is properly printing the header name </td> {% endfor %} </tr> {% endfor %} </tbody> I want to use this header value as a key. If anyone can please tell me how can I achieve it? -
probleme when trying to login in Django Admin
hello i have a legacy database wiche use unix time and I have override an absractbaseuser here is my model from django.db import models from django.contrib.auth.models import AbstractBaseUser,BaseUserManager from django.contrib.auth.signals import user_logged_in from .helper import get_current_unix_timestamp class MyUserManager(BaseUserManager): def create_user(self, username,password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not username: raise ValueError('user must have a username') user = self.model( username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, password=None): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( username, password=password, ) user.is_admin = True user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class Account(AbstractBaseUser): id = models.AutoField(primary_key=True,verbose_name='ID',) username = models.CharField(max_length=50, blank=True, null=True,unique=True) password = models.CharField(max_length=255, blank=True, null=True) email = models.CharField(max_length=255, blank=True, null=True) ip = models.CharField(max_length=255,null=True,blank=True) date_registered = models.IntegerField(default=get_current_unix_timestamp()) last_login = models.IntegerField(null=True,blank=True) member_group_id = models.IntegerField(blank=True, null=True) credits = models.FloatField(blank=True, null=True) notes = models.TextField(blank=True, null=True) status = models.IntegerField(blank=True, null=True) reseller_dns = models.TextField(blank=True, null=True) owner_id = models.IntegerField(blank=True, null=True) override_packages = models.TextField(blank=True, null=True) hue = models.CharField(max_length=50, blank=True, null=True) theme = models.IntegerField(blank=True, null=True) timezone = models.CharField(max_length=255, blank=True, null=True) api_key = models.CharField(max_length=64, blank=True, null=True) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = … -
How do I save share data with two separate models that is linked by a foreignkey
I have a Post model that has a separate image model and i want to have functionality for group users being able to share data to their walls, but i have been challenge in saving the data since the foreignkey of the groupimage mismatch the original data from the post. How do i get the original image id to much the post for it to save ?Here what i have than so far! def share_post(request, pk): original_img = GroupImage.objects.prefetch_related('groupimage_set').get(pk=pk) original_post = Post.objects.prefetch_related('groupimage_set').get(pk=pk) form = ShareForm(request.POST, request.FILES) if form.is_valid(): new_post = Post( shared_body = request.POST.get('description'), description = original_post.description, username = original_post.username, date_posted = original_post.date_posted, group = original_post.group, shared_on = datetime.now(), shared_user = request.user) new_post.save() for f in original_img.images: data = GroupImage(post=original_img,group=original_post.group.pk,image=f) data.save() return redirect('group:main',original_post.group.pk) else: form = ShareForm(request.POST, request.FILES) ctx = {'form':form, 'original_post':original_post} return render(request,'group/share_form.html', ctx) -
How to get max score of answers to a question by each user
I have these 2 models: class Question(models.Model): title = models.CharField(max_length=200) # other fields class Answer(models.Model): user = models.ForeignKey(User) question = models.ForeignKey(Question) score = models.IntegerField() each user can answer a question multiple times. Imagine I have these answers: { "user": 1, "question": 1, "score": 50 }, { "user": 1, "question": 1, "score": 100 }, { "user": 2, "question": 1, "score": 100 }, { "user": 2, "question": 1, "score": 200 }, { "user": 2, "question": 2, "score": 100 }, { "user": 2, "question": 2, "score": 200 } I want a query to give me this result: { "user": 1, "question": 1, "max_score": 100 }, { "user": 2, "question": 1, "max_score": 200 }, { "user": 2, "question": 2, "max_score": 200 } I want all of the max scores of each user to each answer. -
Django DRF Custom user model field "updated" (last login) is not being updated upon login
I have a problem with the user fields "created" and "updated". First of all, there's a "Last login" field (I assume this represents "updated") in admin which is always empty. There's no field for "created" it seems. Secondly, Created and updated do get initiated with the account creation datetime, however it is not updated upon login. I'm using Django 4.0 RegisterSerializer class RegisterSerializer(UserSerializer): password = serializers.CharField(max_length=128, min_length=8, write_only=True, required=True) email = serializers.EmailField(required=True, write_only=True, max_length=128) class Meta: model = User fields = ['id', 'username', 'email', 'password', 'is_active', 'created', 'updated', 'testfield'] def create(self, validated_data): try: user = User.objects.get(email=validated_data['email']) except ObjectDoesNotExist: user = User.objects.create_user(**validated_data) return user User model class User(AbstractBaseUser, PermissionsMixin): id = models.AutoField(primary_key=True) username = models.CharField(db_index=True, max_length=255, unique=True, blank=True) email = models.EmailField(db_index=True, unique=True, null=True, blank=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) testfield = models.CharField(max_length=255, blank=True) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['username'] objects = UserManager() def __str__(self): return f"{self.email}" UserSerializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'email', 'is_active', 'created', 'updated'] read_only_field = ['is_active', 'created', 'updated'] I followed this guide for the user setup https://dev.to/koladev/build-a-crud-application-using-django-and-react-5389