Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the use and sense of Meta Class used in Django under Models Section. Also Why and When we specify it and when not
class Comment(models.Model): lesson_name = models.ForeignKey(Lesson , null=True, on_delete=models.CASCADE, related_name='comments') comm_name= models.CharField(max_length=100 , blank=True) author = models.ForeignKey(User , on_delete=models.CASCADE) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): self.slug = slugify("comment by" + "-" +str(self.author) + str(self.date_added)) super().save(*args, **kwargs) def __str__(self): return self.comm_name class Meta: ordering = ['-date_added'] -
Can we use django filter with a variable?
Here are my codes: Models.py class Members(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) username = models.CharField(max_length=100) email = models.EmailField() phone = models.CharField(max_length=14) Views.py (fails to return any value) def employeeView(request): member = User.username members = Members.objects.filter(username= member) return render(request,'members/user_profile.html', {'members': members}) Views.py (returns properly) def employeeView(request): members = Members.objects.filter(username= 'mahesh') return render(request,'members/user_profile.html', {'members': members}) I am trying to get the data out by filtering the Members.obejcts by passing the username of the logged-in user. It works when hardcoded, but not by passing a variable. Is there any workaround? -
How to Scale ERPNext application on your own server to 2000 user with heavy load?
How to Scale the ERPNext application on your own server to 2000 users with a heavy load? I have created one application server and two read/ write replica database servers. with heavy RAM and SSD's more than enough to handle the load. But at the time of load testing UI Becomes slow and unresponsive. Could anybody please help me figure out the right way to scale erpnext to 2000 users to our own server -
How to navigate to part of page in Django
So I have posts and I can add comments to them. I have a CreateCommentView and I want that the success_url goes to the home page where it has all posts, but navigate to the post I added a comment to. (so like it scroll down to the past I added comment to ) views.py class CommentCreatView(LoginRequiredMixin, CreateView): model = Comment fields = ['text'] template_name = 'comments/create.html' success_message = 'Your comment has been added' success_url = reverse_lazy('homepage') def form_valid(self,form): form.instance.user = self.request.user form.instance.post_id = self.kwargs['pk'] return super().form_valid(form) models.py class Comment(models.Model): text = models.CharField(max_length= 2200) post = models.ForeignKey(Posts, on_delete=models.CASCADE , related_name='comments' ) user = models.ForeignKey(User, on_delete=models.CASCADE) date_posted = models.DateTimeField(default=timezone.now()) def __str__(self): return self.text the homepage HTML {% extends "posts/base.html" %} {% block content %} {% for post in posts %} <h6>{{post.user.username}}</h6> <img src="{{ post.image.url }}" /> <h6>{{post.user.username}}</h6> <p>{{post.caption}}</p> <h6>Comments</h6> {% for comment in post.comments.all %} <hr class="bg-danger border-2 border-top border-primary"> <h6>{{comment.user}}</h6> <p>{{comment.text}}</p> {% endfor %} <div> <a href="{% url 'add-comment' post.id %}" class="btn btn-outline-primary mt-2">Add Comment</a> </div> {% endfor %} {% endblock %} -
django dict.get() takes no keyword arguments
I'm trying to build a form that sends an email to me and to the person who summited the form and also create an object in Aanmelden. Views.py def send_email(email): context = {'email': email} template = get_template('emails/message-confirmation.html') content = template.render(context) email = EmailMultiAlternatives( 'Test email', 'AmiSalta message confirmation', settings.EMAIL_HOST_USER, [email] ) email.attach_alternative(content, 'text/html') email.send() def activiteit(request, activiteit_id): activiteit = Activiteit.objects.get(pk=activiteit_id) form = AanmeldenForm() if request.method == 'POST': email = request.POST.get('email') send_email(email) form = AanmeldenForm(request.POST) if form.is_valid(): naam = form.cleaned_data['naam'] activiteit = Activiteit.objects.get(pk=activiteit_id) email = form.cleaned_data['email'] send_mail('Aangemeld!' + naam, activiteit, email, ['varela.enmanuel@gmail.com']) form.save return redirect('./') return render(request, "activiteit.html", { "activiteit": activiteit, 'form':form, }) models.py class Activiteit(models.Model): titel = models.CharField(max_length=64) docent = models.CharField(max_length=32) icon = models.ImageField() uitleg = models.TextField() lange_uitleg_1 = models.TextField() lange_uitleg_2 = models.TextField(default=None, blank=True) afbeelding_1 = models.ImageField(default=None, blank=True) afbeelding_2 = models.ImageField(default=None, blank=True) nos = models.IntegerField() rem = models.IntegerField() class Aanmelden(models.Model): naam = models.CharField(max_length=32) leerlingnummer = models.IntegerField(validators=[beperk_aanmelden,]) email = models.EmailField(name='email') klas = models.ForeignKey(Klas, on_delete=models.CASCADE, default=None, blank=True) nos = models.IntegerField(default=1) activiteit = ForeignKey(Activiteit, on_delete=models.CASCADE, default=None, blank=True) forms.py class AanmeldenForm(forms.ModelForm): class Meta: model = Aanmelden fields = ( 'naam','leerlingnummer','klas','activiteit', 'email') But I keep getting this error error message django dict.get() takes no keyword arguments. What is causing it? The emails get send anyway … -
My for loop stops working when I add an else condition
I am trying to define a function in order to create a new page in a wiki application. The user should provide a title and a content. If the title already exists in the list, the user should get an error message. If not, the new entry should be saved in the list with its content. Here is my code so far: def new_page(request): if request.method == "POST": title = request.POST.get("title") entries = util.list_entries() #this function is already defined and it returns a list of all names of encyclopedia entries. for entry in entries: if title.lower() == entry.lower(): return HttpResponse(f"ERROR: {entry} Already Exists") else: return render(request,"encyclopedia/new_page.html") The above code works fine, when I type in an existing title I get the error message. The problem starts when I add an else condition. Here's an example (for just trying out the code,I don't want the content to be saved yet.) def new_page(request): if request.method == "POST": title = request.POST.get("title") entries = util.list_entries() for entry in entries: if title.lower() == entry.lower(): return HttpResponse(f"ERROR: {entry} Already Exists") else: return HttpResponse("Thank you for your contribution!") else: return render(request,"encyclopedia/new_page.html") Now, even if I type in an existing title, I get "Thank you for your contribution!". … -
Preview option is worked one time, after i click edit and update the forms it allow me to login url in django?
views.py #Vendor Signup def VendorSignup(request): vendorform = VendorCreationForm() vendordetailform = VendorAdminDetailsForm() if request.method == 'POST': vendorform = VendorCreationForm(request.POST) vendordetailform = VendorAdminDetailsForm(request.POST, request.FILES) if vendorform.is_valid() and vendordetailform.is_valid(): # if vendorform.is_valid(): new_user = vendorform.save() vendordetailform.instance.vendoruser = new_user vendordetailform.save() # new_user.is_active = False new_user.save() user_details = CustomUser.objects.filter(id=new_user.id) vendor_details = user_details[0].vendor_details.all() return render(request,'vendor/preview.html', {'user_details':user_details, 'vendor_details':vendor_details}) else: vendorform = VendorCreationForm() vendordetailform = VendorAdminDetailsForm() return render(request, 'vendor/signup.html', {'vendorform': vendorform, 'vendordetailform':vendordetailform}) #Vendor Edit def VendorEdit(request, id=0): if request.method == "GET": vendor = CustomUser.objects.get(pk=id) print(vendor) form = VendorCreationForm(instance=vendor) vendordetails = VendorDetails.objects.filter(vendoruser_id=vendor.id) print(vendordetails) vendordetailform = VendorAdminDetailsForm(instance=vendordetails[0]) return render(request, 'vendor/edit.html', {'form':form, 'vendor':vendor, 'vendordetailform':vendordetailform}) else: vendor = CustomUser.objects.get(pk=id) form = VendorCreationForm(request.POST, instance=vendor) vendordetails = VendorDetails.objects.filter(vendoruser_id=vendor.id) vendordetailform = VendorAdminDetailsForm(request.POST, request.FILES, instance=vendordetails[0]) if form.is_valid() and vendordetailform.is_valid(): vendor=form.save() vendordetailform.instance.vendoruser = vendor vendordetailform.save() # vendor.is_active = False # vendor.save() return redirect('login') here I registered users and preview their details in preview.html.Edit is worked. but after update the register form, it won't me to preview the form, it redirect me to login page.I have save and edit button in preview.html. If i click save button it redirect me to login page and it worked, but when occuring this i want to inactive the user in the final stage of signup. can anyone please,solve this issue -
Find all appointments for specific date
My goal is to get all appointments (start_date and time) for current month and put them in a table under dates of the current month. For example show all dates of November (Monday, Tuesday, etc. and under the dates show the appointments that took place for that day. Can you propose a way of doing that? My first try is to get all dates of the month (November) and show them to template. Then get all appointments with start_date and time For example: # Show dates of current month and show them in template year = today.year month= today.month num_days = calendar.monthrange(year, month)[1] days = [datetime.date(year, month, day) for day in range(1, num_days+1)] print(days) days_list = [] for days in days: days_str = days.strftime('%A, %d') days_list.append(days_str) print(days_str) #Query for the appointments, something like: appointments = Appointment.objects.filter().... -
how change redis for recommender.py app in django?
i wrote a code for suggested product named recommender.py i want to change redis because my host does not support redis-server but i don't know how do that. i want to change all code from redis to mysql or postgresql or mongodb anyone can help me? this is my code from myshop.settings import REDIS_DB, REDIS_PORT import redis from django.conf import settings from .models import Product r = redis.Redis(host=settings.REDIS_HOST,port=settings.REDIS_PORT,db=settings.REDIS_DB class Recommender(object): def get_product_key(self,id): return f"product:{id}:bought_with" #product:1:bought_with def products_bought(self,products): product_ids = [p.id for p in products] for product_id in product_ids: #[1,2,3] for with_id in product_ids: if product_id != with_id: r.zincrby(self.get_product_key(product_id),1,with_id) def suggest_products_for(self,products,max_results=6): product_ids = [p.id for p in products] if len(products) == 1: suggestions = r.zrange(self.get_product_key(product_ids[0]),0,-1,desc=True)[:max_results] else: flat_ids = ''.join([str(id) for id in product_ids]) #[1,2,3] => "123" tmp_key = f"tmp_{flat_ids}" #"123" => tmp_123 keys = [self.get_product_key(id) for id in product_ids] r.zunionstore(tmp_key,keys) r.zrem(tmp_key,*product_ids) suggestions = r.zrange(tmp_key,0,-1,desc=True)[:max_results] r.delete(tmp_key) suggested_products_ids = [int(id) for id in suggestions] suggested_products = Product.objects.filter(id__in=suggested_products_ids) return suggested_products -
how to customize sent emails in djoser?
I build React&Django project and use Djoser for registration and auth. I want to customize sent email content on Gmail. Where should I change it? -
Django: ForeignKey(models) to not visible model?
below you can see a simple connection of two models via foreignkey! class Manufacturer(models.Model): name = models.CharField(max_length=50, null=False, blank=False) user_created = models.CharField(max_length=50, null=False, blank=False) date_created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['name'] def __str__(self) -> str: return self.name class CarModel(models.Model): manufacturer = models.ForeignKey(Manufacturer, null=False, blank=False, on_delete=models.CASCADE) name = models.CharField(max_length=50, null=False, blank=False) user_created = models.CharField(max_length=50, null=False, blank=False) date_created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['name'] def __str__(self) -> str: return f"{self.name} ({self.manufacturer})" My Question: is it possible to create such a connection, even if the first model (in this example the Manufacturer) is not created by django - so there is no typical modelclass - but still inside the same database? Like importing or loading the other model from the database to connect it? Also I'm using Postgresql! Thanks for your help and have a great sunday! -
Nginx. Issue to access redoc
I have the Django project and trying to deploy it on server using docker and nginx. There is no problem to deploy it and get access to required pages, but I can't get access to redoc page. Nginx config is following ( default.conf): server { listen 80; location /static/ { root /var/html/; } location /media/ { root /var/html/; } location /redoc/ { root /var/html; try_files $uri $uri/redoc.html; } location / { proxy_pass http://web:8000; } } docker-compose.yaml: services: db: image: postgres:12.4 volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env web: image: restart: always volumes: - static_value:/code/static/ - media_value:/code/media/ depends_on: - db env_file: - ./.env nginx: image: nginx:1.19.3 ports: - "80:80" volumes: - ./nginx/default.conf:/etc/nginx/conf.d/default.conf - static_value:/var/html/static/ - media_value:/var/html/media/ - .static/redoc.yaml:/var/html/redoc/redoc.yaml - .templates/redoc.html:/var/html/redoc/redoc.html depends_on: - web volumes: postgres_data: static_value: media_value: Could you, please, advice what is wrong is set up ? -
How to display querysets in Django?
I write a functiın and the final, function creates several model objects (same model different values). I listed these objects but I want to list just one time with the same dashboard_id value. I found something about that but I have an issue with displaying in the table. It is working but does not display the values. How can I solve it? views.py def reports_list(request): report_list = Reports.objects.values_list('dashboard_id', flat=True).distinct() context = { 'report_list': report_list, } return render(request, "report_list.html", context) report_list.html <table id="table_id" class="display"> <thead> <tr> <th>Kullanıcı</th> <th>Yüklenme Tarihi</th> <th>Görüntüle</th> </tr> </thead> <tbody> {% for report in report_list %} <tr> <td>{{ report.user.first_name }} {{ report.user.last_name }}</td> <td>{{ report.created_at }}</td> <td>view</td> </tr> {% endfor %} </tbody> </table> to be clear: -
Use GCC and java in Heroku dyno
I am trying to build a code compiler using Python Djano. The code works in my local machine as I use subprocess to compile and then run codes like python,java,c/c++. But when I upload it on Heroku which has a python build pack, it fails to run java and c/cpp codes because somehow it cannot access gcc and java [probably they are unavailable]. Hence how do I use java and cpp while retaining python too and run and execute the codes that are inputted from the front end. -
Django select_related() with latest() limit on related object
Consider having Table table and Reservation table in my restaurant Django APP. class Reservation(models.Model): table = models.ForeignKey( Table, on_delete=models.CASCADE, blank=False,null=False, related_name='reservations' ) def __str__(self): return str(self.pk) class Table(models.Model): def __str__(self): return str(self.pk) If I wanna to show a list of restaurant tables with it's corresponding reservation, then I need to select related reservation for each table. but I need to select related only the last reservation of each table (that is active right now). How To Achieve that? -
Django file upload with model form
there are tons of relevant posts: https://docs.djangoproject.com/en/3.2/topics/http/file-uploads/ Uploading A file in django with ModelForms https://github.com/axelpale/minimal-django-file-upload-example I am creating a simple app that allow user to upload css file: First, validate field field to make sure the file is css and the max size does not exceed 5MB. fields.py from django.db import models from django import forms from django.template.defaultfilters import filesizeformat def mb(n): return n * 1048576 class FileField(models.FileField): def __init__(self, *args, **kwargs): self.content_types = kwargs.pop('content_types', []) self.max_upload_size = kwargs.pop('max_upload_size', []) super().__init__(*args, **kwargs) def clean(self, *args, **kwargs): data = super().clean(*args, **kwargs) file = data.file try: content_type = file.content_type if content_type in self.content_types: if file.size > self.max_upload_size: raise forms.ValidationError('Please keep filesize under {}. Current filesize {}' .format(filesizeformat(self.max_upload_size), filesizeformat(file.size))) else: raise forms.ValidationError('File type rejected') except AttributeError: pass return data second, implement validation into model models.py # Create your models here. class Css(models.Model): file = FileField(upload_to='css', blank=True, null=True, content_types=['text/css'], max_upload_size=mb(5), ) third, create form for model creation forms.py class CssCreateForm(forms.ModelForm): class Meta: model = Css fields = ['file'] last, write a callable view views.py # Create your views here. def cssUploadView(request): if request.method == 'POST': print(request.POST['file']) print(type(request.POST['file'])) print(request.FILES) form = forms.CssCreateForm(request.POST, request.FILES) if form.is_valid(): print('---------') print(form.cleaned_data['file']) else: print('not valid') else: form = forms.CssCreateForm() return … -
How can I resolve fts5 error after I upgraded Wagtail
I have upgraded my Wagtail installation to 2.15.1 with Django 3.1.13 When I run manage.py migrate I get an error django.db.utils.OperationalError: no such module: fts5 I have searched but cannot find any solutions to this problem Can someone please help? -
|as_crispy_field got passed an invalid or inexistent field django?
views.py def VendorEdit(request, id=0): if request.method == "GET": vendor = CustomUser.objects.get(pk=id) print(vendor) form = VendorCreationForm(instance=vendor) vendordetails = VendorDetails.objects.filter(vendoruser_id=vendor.id) print(vendordetails) vendordetailform = VendorAdminDetailsForm(instance=vendordetails[0]) return render(request, 'vendor/edit.html', {'form':form, 'vendor':vendor, 'vendordetailform':vendordetailform}) else: vendor = CustomUser.objects.get(pk=id) form = VendorCreationForm(request.POST, instance=vendor) vendordetails = VendorDetails.objects.filter(vendoruser_id=vendor.id) vendordetailform = VendorAdminDetailsForm(request.POST, request.FILES, instance=vendordetails[0]) if form.is_valid() and vendordetailform.is_valid(): vendor=form.save() # vendordetailform.instance.vendoruser = vendor vendordetailform.save() # vendor.is_active = False # vendor.save() return redirect('login') edit.html <form method="POST" action="{% url 'vendor_edit' vendor.id %}" enctype='multipart/form-data'> {% csrf_token %} {{ vendorform.email|as_crispy_field}} {{ vendorform.first_name|as_crispy_field}} {{ vendorform.last_name|as_crispy_field}} {{ vendorform.mobile_number|as_crispy_field}} {{ vendorform.password1|as_crispy_field}} {{ vendorform.password2|as_crispy_field}} {{ vendordetailform.type_of_vendor|as_crispy_field}} {{ vendordetailform.aadhar_number|as_crispy_field}} {{ vendordetailform.aadhar_image|as_crispy_field}} {{ vendordetailform.pan_number|as_crispy_field}} {{ vendordetailform.pan_image|as_crispy_field}} {{ vendordetailform.store_name|as_crispy_field}} {{ vendordetailform.brand_name|as_crispy_field}} {{ vendordetailform.mail_id|as_crispy_field}} {{ vendordetailform.contact_no|as_crispy_field}} {{ vendordetailform.gst_number|as_crispy_field}} {{ vendordetailform.attach_gst_cert|as_crispy_field}} {{ vendordetailform.acct_number|as_crispy_field}} {{ vendordetailform.attach_passbook|as_crispy_field}} {{ vendordetailform.ifsc_code|as_crispy_field}} {{ vendordetailform.insta_account|as_crispy_field}} {{ vendordetailform.website|as_crispy_field}} {{ vendordetailform.street_name|as_crispy_field}} {{ vendordetailform.city|as_crispy_field}} {{ vendordetailform.pincode|as_crispy_field}} <button type="submit" class="btn btn-dark" value="Submit">Preview</button>&ensp; <a href="{% url 'login' %}">Already a Vendor?</a> </form><br> after the user signup, I allow them to preview and edit their details once they edit their details and preview, then click submit. It will redirect to login. The edit option is not working and after the preview submit not redirect to login the user. please need help. -
Django is using old views.py
So when running my project the homepage is good and the signup and in. However, some things don't work. I found errors where have things from old views.py. So I am thinking that Django is using a vies.py folder for other projects. views.py class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, SuccessMessageMixin, DeleteView): model = Posts success_message = 'Your post has been deleted' #it is not working and I dont know why success_url = reverse_lazy('homepage') template_name = 'posts/delete.html' def test_func(self): post = self.get_object() if self.request.user == post.user: return True return False urls.py from django.urls import path from django.conf import settings from django.conf.urls.static import static from .views import PostsListView, PostCreatView, PostDeleteView urlpatterns = [ path('', PostsListView.as_view(), name='homepage'), path('delete/<int:pk>/', PostDeleteView.as_view(), name='delete-post'), path('creat-post', PostCreatView.as_view(), name='create-post') ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) delete.html {% extends "posts/base.html" %} {% block content %} <form method="POST"> {% csrf_token %} <h2> Are you sure you want to delete your post?</h2> <button class="btn btn-outline-danger mt-1 mb-1 mr-1 ml-1" type="submit">Yes Delete</button> <a class="btn btn-outline-secondary mt-1 mb-1 mr-1 ml-1" href="{% url 'post-and-comments' object.id %}">Cancel</a> </div> </form> {% endblock %} list.html {% extends "posts/base.html" %} {% block content %} {% for post in posts %} <p class="font-weight-bold">{{post.user.username}}</p> {% if user == post.user %} <div> <a href="{% url 'delete-post' post.pk … -
ImportError: Couldn't import Django in running Docker image
I am so new in Docker and I have dockerized a simple django application and this is Dockerfile : FROM python:3.8-slim-buster ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY . . RUN pip freeze > requirements.txt RUN pip3 install -r requirements.txt CMD ["python3","manage.py", "runserver","0.0.0.0:8000"] i have created image myapp 4 successfuly and when i tried to run this image with dcoker run myapp4 i got the following error : Traceback (most recent call last): File "manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? what am i missing here? -
Display all dates of November in a template
I'm trying to learn datetime and i'm currently trying to display all dates of November in an html template, in views i have: year = today.year month= today.month num_days = calendar.monthrange(year, month)[1] days = [datetime.date(year, month, day) for day in range(1, num_days+1)] for days in days: days_str = days.strftime('%A, %B, %d, %Y') print(days_str) context = {'': } return render(request, 'template.html', context) The output of the above is: Monday, November, 01, 2021 Tuesday, November, 02, 2021 Wednesday, November, 03, 2021 Thursday, November, 04, 2021 Friday, November, 05, 2021 Saturday, November, 06, 2021 Sunday, November, 07, 2021 Monday, November, 08, 2021 Tuesday, November, 09, 2021 Wednesday, November, 10, 2021 Thursday, November, 11, 2021 Friday, November, 12, 2021 Saturday, November, 13, 2021 Sunday, November, 14, 2021 Monday, November, 15, 2021 Tuesday, November, 16, 2021 Wednesday, November, 17, 2021 Thursday, November, 18, 2021 Friday, November, 19, 2021 Saturday, November, 20, 2021 Sunday, November, 21, 2021 Monday, November, 22, 2021 Tuesday, November, 23, 2021 Wednesday, November, 24, 2021 Thursday, November, 25, 2021 Friday, November, 26, 2021 Saturday, November, 27, 2021 Sunday, November, 28, 2021 Monday, November, 29, 2021 Tuesday, November, 30, 2021 How can i display above dates in a template? Thank you! -
"JSON parse error - Expecting property name enclosed in double quotes: line 1 column 2 (char 1)"
I am creating a project with Django Rest Framework and I ran into some problems and im not able to fix them. So, I have a URL for post method and when I post there using postman, I get an error: { "detail": "JSON parse error - Expecting property name enclosed in double quotes: line 1 column 2 (char 1)" } This is the data im sending: {username:"REQUAB", password:"REQUAB", emailId:"requab@gmail.com"} And just to check if i had some problem in the serializer or the model, i did a normal get request and i got correct output. my models.py: from django.db import models # Create your models here. class User(models.Model): emailId = models.EmailField(max_length=50) username = models.CharField(max_length=20) password = models.CharField(max_length=50) recipes = models.IntegerField(default=0) def __str__(self): return self.username my serializers.py: from rest_framework import serializers from .models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'emailId', 'password', 'recipes'] my urls.py: from django.urls import path from .views import UsersList, UsersDetail urlpatterns = [ path('', UsersList.as_view()), ] my views.py: from django.http import Http404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from users.models import User from .serializers import UserSerializer # Create your views here. class UsersList(APIView): def … -
Calculate Sub Table Django
I'm new on Django, I try to calculate sub table of related table. I have two models Transaction and Detail. here is my models: class Transaction(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) code = models.CharField(max_length=50) class Detail(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) transaction = models.ForeignKey(Transaction, related_name='details', on_delete=models.CASCADE) qty = models.DecimalField(max_digits=10, decimal_places=2, null=False, blank=False) price = models.DecimalField(max_digits=10, decimal_places=2, null=False, blank=False) I want to get sum of calculation (Detail.qty * Detail.price) on a single query like this: datas = Transaction.objects.all().annotate(sum=sum(qty*price)) How to do that on Django ORM? -
ckeditor toolbar not getting displayed in django-admin form
Guess I am doing something wrong here, but I have followed the most part from docs , little help here , Am i missing something , thanks in advance Admin.py class ArticleAdminForm(forms.ModelForm): article_text = RichTextField(blank=True) class Meta: model = Article fields = '__all__' class ArticleAdmin(admin.ModelAdmin): form = ArticleAdminForm autocomplete_fields = ('tags',) class TagsAdmin(admin.ModelAdmin): search_fields = ('name',) Settings.py CKEDITOR_UPLOAD_PATH = "ck_uploads/" CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Advanced', 'width': 758, 'height': 300, }, } Models.py class Article(models.Model): date_published = models.DateTimeField(auto_now_add=True) article_text = models.TextField() title = models.CharField(max_length=100,null=True,blank=True) topic = models.ForeignKey(Topic,on_delete=models.SET_NULL,null=True) tags = models.ManyToManyField(Tags) date_updated = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = 'Articles' def __str__(self): return "{} title {}".format(self.title,self.article_text[:4]) if self.title else " not topic for {}".format(self.article_text) -
Django Dynamically Calculate Average
I've multiple fields in my model, and I need to remove the average of only the columns user inputs Could be How can I do it dynamically? I know I can do mean = results.aggregate(Avg("student_score")) This is one, I want to add multiple Avg statements dynamically I tried making a loop as well to get all names and add all fields given by user one by one eg - Avg('students'), Avg('playtime'), Avg('grade'), Avg('sales') But I get QuerySet.aggregate() received non-expression(s): <class 'django.db.models.aggregates.Avg'>('students'), <class 'django.db.models.aggregates.Avg'>('sales'). I've even tried raw query, but it needs a unique ID because of which that isn't working Any workaround ideas? I am using MySQL DB