Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django In Production: Static files not serving?
I have deployed a project in digital ocean ubuntu 20.04 server Everything is working but static files are not being served. My project is in the root directory. There are also static and media folders which hold their respective files in the root directory. Plus the locations of STATICFILES_DIRS also contain the same files. project/settings.py STATIC_URL = '/static/' MEDIA_URL = '/media/' STATICFILES_DIRS =['/root/templates/colorlib-regform-6'] STATIC_ROOT = '/root/static' MEDIA_ROOT = '/root/media' etc/nginx/sites-available/project server { listen 80; server_name 104.131.89.148; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root / ; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } I have restarted gunicorn and Nginx then also run : python3 manage.py collectstatic After running this command, static files are also collected. But, while running the server, static files are not served. I think the issue is with settings.py or nginx conf. Any ideas or suggestions will be appreciated. -
django mongoDB boolean field get query has DATABASE ERROR
i am using Donjo for mongoDB for django. and getting error while fetching data from boolean field. settings.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'seartzDB' } } model.py class DynamicForm(models.Model): name = models.CharField(max_length=250) email = models.EmailField(max_length=250) is_email = models.BooleanField(default=False) ... view.py @api_view(['POST', ]) def get_form_view(request): email_data = DynamicForm.objects.filter(is_email=True) email_list = [] for i in email_data: email_list.append(i.email) return Response({'data': email_list}, status=200) urls.py urlpatterns = [path('email/get/', get_form_view, name="get_form"),] while i am fetching data from table with boolean field the it gives an error. DatabaseError at /api/v1/blog/comment/create/3/ No exception message supplied Request Method: POST Request URL: http://localhost:8000/api/v1/blog/comment/create/3/ Django Version: 3.1.4 Exception Type: DatabaseError Exception Location: /home/singham/anaconda3/envs/pythonenv/lib/python3.8/site- packages/djongo/cursor.py, line 59, in execute Python Executable: /home/singham/anaconda3/envs/pythonenv/bin/python Python Version: 3.8.5 Python Path: ['/media/singham/e1e50bd4-08fa-4ffd-a015-a73c293eaafe/lepy- backup/lokesh/seartz/mongodb/seartz', '/home/singham/anaconda3/envs/pythonenv/lib/python38.zip', '/home/singham/anaconda3/envs/pythonenv/lib/python3.8', '/home/singham/anaconda3/envs/pythonenv/lib/python3.8/lib-dynload', '/home/singham/anaconda3/envs/pythonenv/lib/python3.8/site-packages'] Server time: Sat, 12 Dec 2020 13:00:40 +0000 -
How to download uploaded files with django
I have seen many solutions for this on here but I can't seem to get any working as I am also new to django. Essentially as of now my files are uploading correctly by a user to media/documents but when I try to download the files from the directory, in terminal I get 404 and I end up downloading an empty file. Say the original file is "test.txt", right now it is downloading an empty "documents_test.txt". As of right now this is what I have for my code and how I am trying to download within my template. models.py class Program(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) description = models.CharField(max_length=128) upload = models.FileField(upload_to='documents/') category = models.ForeignKey(ProgramCategory, on_delete=models.CASCADE) is_public = models.BooleanField() views.py def programs(request): # Create some default categories if there aren't any. if (not ProgramCategory.objects.all()): ProgramCategory.objects.create(category="Hobby") ProgramCategory.objects.create(category="School") ProgramCategory.objects.create(category="Work") '''if (request.method == "GET" and "toggle_completed" in request.GET): id = request.GET["toggle_completed"] task = Task.objects.get(id=id) task.is_completed = not task.is_completed task.save()''' if (request.method == "GET" and "delete" in request.GET): id = request.GET["delete"] Program.objects.all().filter(id=id).delete() return redirect("/programs/") if (request.method == "POST"): try: user_profile = UserProfile.objects.filter(user=request.user).get() except: user_profile = UserProfile() user_profile.user = request.user #user_profile.tasks_view_hide_completed = False #form = HideCompletedTasksForm(request.POST, instance=user_profile) if (form.is_valid()): form.save() user_profile = UserProfile.objects.filter(user=request.user).get() #hide_completed_form_data = HideCompletedTasksForm(instance=user_profile) … -
Returning data to a AJAX get request without reloading page
I am using django. I need to update a page without refreshing, I know how to use the AJAX get request but I am unable to return a response without reloading the page from my views.py, please help. Thank you. -
Adding Javascript to Wagtail StreamField blocks on pages
I thought a TabsBlock would be nice for the StreamField to add a JQuery tab interface. I have created two block models based on StructBlock, one is called TabsBlock which is the toplevel tab interface and TabPageBlock which are the individual content children of TabsBlock. class TabPageBlock (blocks.StructBlock): """A tab page used by TabsBlock""" name = blocks.CharBlock () content = blocks.StreamBlock ([ ('heading', HeadingBlock ()), ('paragraph', blocks.RichTextBlock ()), ('image', ImageChooserBlock ()), ('linked_image', LinkedImageBlock ()), ('embed', EmbedBlock ()), ]) class TabsBlock (blocks.StructBlock): """A JQuery tabs block type""" html_id = blocks.CharBlock () pages = blocks.ListBlock (TabPageBlock) class Meta: template = 'blocks/tabs.html' The blocks/tabs.html template looks like this: {% load wagtailcore_tags %} <div id="{{ value.html_id }}"> <ul> {% for p in value.pages %} <li><a href="#tabs-{{ forloop.counter }}">{{ p.name }}</a></li> {% endfor %} </ul> {% for p in value.pages %} <div id="tabs-{{ forloop.counter }}"> {% include_block p.content %} </div> {% endfor %} </div> <script> $(function () { $("#{{ value.html_id }}").tabs (); }); </script> Here is where the problem lies. I would like to add the Javascript code at the end of this template to the page content (after jquery and jquery-ui are loaded), to enable the tab interface. Adding it to the block template … -
How do I get a hyperlinked foreign key in Django REST Framework serializer?
I am trying to serialize a model in my DRF project. The model contains 2 foreign key fields and some simple data type fields. One of the foreign key fields is to my CustomUser model and this field appears as a hyperlink in my API output which is expected. The other foreign key field is to a different model (shown below). I have been cycling through the same few errors over the past several hours as I've tried various solutions recommended in other StackOverflow threads. Could someone please show me how to get this second foreign key to appear as a link in my API output? When my code files appear as they do below, I get this error when trying to access the localhost:8000/trade/create/ and localhost:8000/trader-accounts/ URLs: django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "traderaccount-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. Of course, I Googled this error messages and portions thereof several times, and went down several DRF rabbit holes trying various things. trades/models.py class Trade(models.Model): trade_owner = models.ForeignKey(CustomUser, related_name='owners', on_delete=models.RESTRICT) trade_account = models.ForeignKey(TraderAccount, related_name='trades', on_delete=models.RESTRICT) trader_account/models.py class TraderAccount(models.Model): account_owner … -
OSError: MoviePy error: the file Hello.mp4 could not be found
On Models.py here's what I had. from django.db import models from .utils import image_modify from .utils import video_modify import cv2 as cv from moviepy.editor import * from PIL import Image import numpy as np from io import BytesIO from django.core.files.base import ContentFile class ImageModel(models.Model): title = models.CharField(max_length=50) image = models.ImageField(upload_to='images') #action = models.CharField(max_length = 50, choices = ACTION_CHOICES) updated = models.DateTimeField(auto_now = True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) def save(self, *args, **kwargs): #can be deleted pil_img = Image.open(self.image) #convert image to array cv_img = np.array(pil_img) img = image_modify(cv_img) #comvert back to pil_image im_pil = Image.fromarray(img) #save buffer = BytesIO() im_pil.save(buffer,format='png') image_png = buffer.getvalue() self.image.save(str(self.image),ContentFile(image_png),save=False) super().save(*args,**kwargs) class VideoModel(models.Model): name= models.CharField(max_length=500) #we have two columns, max length is most characters you can write videofile= models.FileField(upload_to='users/seosoojin2003/downloads/barbiegirls/media/videofile/', blank=True) #, null=True, verbose_name="") #next field is videofile and where you upload the video. #filename = instance.videofile.path def __str__(self): return self.name + ": " + str(self.videofile.name) #name represents the name of the video. def save(self, *args, **kwargs): orig_video = VideoFileClip(self.videofile.name) #thumbnail = VideoFileClip(self.videofile.name) edited = video_modify(orig_video) #save buffer = BytesIO() edited.save(buffer,format='mp4') video_mp4 = buffer.getvalue() self.video.save(str(self.videofile.name),ContentFile(video_mp4),save=False) super().save(*args,**kwargs) #image = models.ImageField(upload_to='users/%Y/%m/%d/', blank=True) And on my views.py from django.shortcuts import render #erndering a template; therefore, we import render … -
IntegrityError at /posts/new/
I am new on this field and i am currently learning django and i come up with this problem. I am working on a project which is a social clone project and this project you can only post when you are in a group and i've encountered this problem when i post. The first post is working fine but the second post i get this error message called IntegrityError i've tried to delete my migrations and database and migrate and makemigrations again but does not fix the problem and now i am stuck and i hope someone will help me. This is the actual error Posts Models ########################## ## POSTS MODELS.PY FILE ## ########################## from django.contrib.auth import get_user_model from django.db import models from groups.models import Group from misaka import html from django.urls import reverse from django.conf import settings User = get_user_model() class Post(models.Model): user = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) group = models.ForeignKey(Group, related_name='posts', null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return self.message def save(self, *args, **kwargs): self.message_html = html(self.message) super().save(*args, **kwargs) def get_absolute_url(self): return reverse( 'posts:single', kwargs={ 'username': self.user.username, 'pk': self.pk } ) class Meta: ordering = ['-created_at'] unique_together = ['user', 'group'] Posts Views.py … -
django creating view filter for fast filtering
I have a specific filter I use on my database for 90% of the times. It takes 1 - 2 minutes to filter that from 5M rows. I heard of something called "view" where it saves all match's id, and return it really fast. Please assist. -
What permissions and ownership should the 'static' folder have in production/
This is something I face everytime I deploy a Django app.. permissions. Which group and user should own the static directory and what should the permissions look like? I currently have: drwxr-xr-x 7 www-data www-data 4096 Dec 11 05:29 static My css files are getting a 403 response code when I visit my website so something must be wrong. -
jquery returning POST http://127.0.0.1:8000/like/ 404 (Not Found)
In my Project, I have an application called Score where users can upload Images, I am trying to add the Like functionality to these posts, using Ajax and Jquery to prevent the images from being refreshed. The like option is working fine but still must be refreshed so that the updates appear. In the console I am getting jquery.min.js:2 POST http://127.0.0.1:8000/like/ 404 (Not Found) send @ jquery.min.js:2 ajax @ jquery.min.js:2 (anonymous) @ (index):241 dispatch @ jquery.min.js:2 v.handle @ jquery.min.js:2 Although it is supoosed to be http://127.0.0.1:8000/score/like/ My question is how to handle this error? Worth to mention that I have another application that I am using the same Like Functionality but the application is used for completely different purposes. Models.py class Post(models.Model): title = models.CharField(max_length=100, unique=True) designer = models.ForeignKey(User, on_delete=models.CASCADE, related_name="post") date_posted = models.DateTimeField(default=timezone.now) likes = models.ManyToManyField( User, related_name='liked_designs', blank=True) num_likes = models.IntegerField(default=0, verbose_name='No. of Likes') LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike') ) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,related_name="liked_designs_users") post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=8) Here is the post detail views.py class PostDetailView(ObjectViewMixin, DetailView): model = Post template_name = "score/post_detail.html" # <app>/<model>_<viewtype>.html def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, slug=self.kwargs['slug']) comments = … -
CORS on One Endpoint Django
I am new to Django and I have 2 endpoints in a REST API: api.myapp.com/PUBLIC/ api.myapp.com/PRIVATE/ As suggested by the names, the /PUBLIC endpoint is open to anyone. However, I want the /PRIVATE endpoint to only accept calls from myapp.com (my frontend). How can I do this? Thanks! -
My django Fantasy Football Project. How to display the scores of other users to each user?
I've built a very basic fantasy football app in django that allows a user to select and delete players for their team and then the players'individual scores are totaled up into a team score. What I'd really like to add to the app is to be able to see other users'total scores so that everyone can compare how they are doing against each other. I'm pretty new to django so I've been sitting around in my free time these past few days thinking of a way to do that, but I'm really not sure how ( or even how to ask clearly about how it's done ). One idea I had was to create a new model object that can contain a user's total team score, but I'm really not sure how to get the team score variable into that model object in the first place. Right now, my models.py only has User and player position classes. from django.contrib.auth.models import AbstractUser from django.db import models import datetime class User(AbstractUser): pass class Quarterback(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=20, blank=True) score = models.IntegerField(blank=True, null=True) ...rest of the player-position objects repeat... I've got a function in views.py that calculates a … -
How can I link/or combine my three Django models to better maximize relationship and efficency
Im trying to model out my dB for my Django app. I'm pretty content with that I have so far, only I have two questions regarding my models. Here's a quick run-through of them. UserBuckets contains every bucket a user has created. TotalBuckets contains the total number of buckets a user has created. Bucket Contains information for whats inside each user bucket. class UserBuckets(models.Model): username = models.ForeignKey(UserModel.username) bucket_name = models.CharField() def get_all_buckets(self): all_buckets = UserBuckets.objects.all('bucket_name') return all_buckets def __str__(self): return self.bucket_name class TotalBuckets(models.Model): username = models.ForeignKey(UserBuckets.username) total_buckets = models.IntegerField(blank=True, null=True) def total_buckets_calc(self): self.total_buckets = TotalBuckets.objects.aggregate(Sum('bucket_name', distinct=True)) self.save() def __str__(self): return self.total_buckets class Bucket(models.Model): owner = models.ManyToManyField(UserBuckets.username) bucket = models.ForeignKeyField(UserBuckets.bucket_name, on_delete=models.CASCADE) stocks = ArrayField(models.CharField(max_length=6),size=10) stocks_in_bucket = models.IntegerField(blank=True, null=True) created = models.DateField(auto_now_add=True) slug = models.SlugField(unique=True, blank=True) def total_stocks_calc(self): self.stocks_in_bucket = Bucket.objects.aggregate(Sum('stocks_in_bucket', distinct=True)) self.save() def get_absolute_url(self): return reverse("bucket:bucket-view", kwargs={"slug": self.slug}) def __str__(self): return self.stocks Here are my two questions: 1.I can see the argument of combining UserBuckets + TotalBuckets, however my only problem with that is the repeating the same datapoint for every new object that gets created. To keep things "clean", I separated them. Is this the "correct" procedure? 2. How can I properly reference that each bucket is an object based … -
Get a list of related objects in model's __str__
I have two models with One-to-Many relationship; Listing, and Bids. Is it possible to retrieve and display a list of Bid objects' bid_price in Listing's str method? The code provided below crashes the server and I am not sure of the correct keywords to search for. I understand how listing.bid_set works in the Shell or view, but I am not sure how to make it work here. class Listing(models.Model): title = models.CharField(max_length=64) def __str__(self): bid_objects = Bid.objects.all().filter(listing__id=self.id) price_list = [] for bid_object in bid_objects: price_list.append(bid_object.bid_price) return f"{self.title}, {price_list}" class Bid(models.Model): listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="listing_bids") bid_price = models.DecimalField(max_digits=6, decimal_places=2) Thanks for your help. -
Django - Add Nearest Monday to Queryset
I have an Order model like so: class Order(models.Model): created_at = models.DateTimeField(...) An order can be created at any time, but all orders get shipped out on the following Monday. How can I add an extra field to my orders queryset called assembly_date that reflects the next Monday (date the order should be shipped)? I tried creating a custom OrderManager like so, but am not sure how to correctly set the assembly_date: class OrderManager(models.Manager): def get_queryset(): return self.super().get_queryset().annotate( assembly_date = ... # need help with logic here ) Keep in mind, I want to be able to filter all orders based on their assembly_date. -
Can't install mysqlclient in CentOS 7
First of all... not, it's not a repeated thread. Believe me, I read all similar threads and tested all answers before post this. I just have a new CentOS 7 server installation, with basic configuration (the same I used several times before, but magically, this time does not work) yum -y update yum -y groupinstall development yum -y install gcc yum -y install zlib-devel yum -y install openssl-devel rpm -ivh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm yum -y install mariadb-devel Python3.6 yum -y install python36 yum -y install python36-devel However, once I create my virtual environment with: python3 -m venv test and try to install mysqlclient using pip... Simply doesn't work. The error I have is: ERROR: Command errored out with exit status 1: command: /var/www/test/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-pn9v4w46/mysqlclient_d62f41676e4049d6a292a9525c56d5c9/setup.py'"'"'; __file__='"'"'/tmp/pip-install-pn9v4w46/mysqlclient_d62f41676e4049d6a292a9525c56d5c9/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-7ethj5wf/install-record.txt --single-version-externally-managed --compile --install-headers /var/www/test/include/site/python3.6/mysqlclient cwd: /tmp/pip-install-pn9v4w46/mysqlclient_d62f41676e4049d6a292a9525c56d5c9/ Complete output (31 lines): running install running build running build_py creating build creating build/lib.linux-x86_64-3.6 creating build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-3.6/MySQLdb creating build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying … -
how to render response in parent window instead of popup
I have a template that shows a list of items. When you click to edit one of the items, it will be opened in a popup window. However, if there is an error when processing in the view to display that popup, I am returning the result used to create the parent 'list' page but with an error message. That displays the parent page again in the popup window with the error, so I know that part works. In this case though, I would like to close the popup window, before it displays anything, and have the response displayed on the parent tab. Is this possible? -
Can you use a regular expression in a Django template conditional?
Is it possible to determine if a template variable in a Django template satisfies a regular expression? In the following template, I want to set the CSS class for the paragraph tag that contains the help text based on whether or not the help text for that field satisfies a regular expression. Here is the template with some pseudocode thrown in: {% for field in form.visible_fields %} <div class="form-group"> {{ field.errors }} {{ field.label_tag }} {{ field }} {% if field.help_text %} {% if field.help_text|lower (BEGINS WITH SOME STRING) %} # Pseudocode <p class="select-help-text">{{ field.help_text|safe }}</p> {% else %} <p class="help-text">{{ field.help_text|safe }}</p> {% endif %} {% endif %} </div> {% endfor %} For example, if the help_text as defined in the associated form starts with the text string "Hold down Ctrl", then the CSS class should be set to select-help-text, otherwise it should just be set to help-text. I understand that Django regular expressions are based on Python regexes, but Python regex evaluations always seems to be done using the re module which isn't accessible in a Django template. I also looked through the Django documentation but couldn't find a way to do this. -
I want to filter the def 'getAmountRating(self):' function
I built the class Restaurant where you can find the 'def getAmountRating(self):' function. This function should be used as a keyword in my django_filter. class Restaurant(models.Model): restaurant_picture = models.ImageField(null=True, default='dashboard-BG.jpg') name = models.CharField(max_length=200, null=True) address = models.CharField(max_length=128, blank=True) houseNumber = models.IntegerField(default=1) city = models.CharField(max_length=64, default="") state = models.CharField(max_length=64, default="") zip_code = models.CharField(max_length=5, default="86444") tags = models.ManyToManyField(Tag) affordability = models.FloatField(validators=[MaxValueValidator(3), MinValueValidator(1)], null=True) objects = models.Manager() def getAverageRating(self): comments = Comment.objects.all() avg = 0 count = 0 for i in comments: if i.restaurant == self: avg += i.ratings if count is 0: count += 1 else: avg = avg / 2 if avg is not 0: avg = round(avg) return avg In the filter class RestaurantFilter(django_filters.FilterSet): rating = NumberFilter(field_name="getAverageRating", lookup_expr="gte") class Meta: model = Restaurant fields = '__all__' exclude = ['location', 'restaurant_picture', 'address', 'houseNumber', 'state'] I already had to accept that this is not working as I'd like to. As a fix I looked up some solutions but those solutions did not work. For example I built an other class containing the def getAverageRating function and referenced this class in Restaurant as a - averageRating = RestaurantRating() - which did not work. I don't think its relevant but here is the views.py … -
Why am I getting a Django NoReverseMatch error?
I am trying to send an activation email to users when signing up, but I keep getting a NoReverseMatch error when trying to render the URL in the template. The error I get is: Reverse for 'user_activation' with keyword arguments '{'uidb64': 'MiC', 'token': 'aeue9g-3a31bdff969c41c0bb1d3775a1fa98ac'}' not found. 1 pattern(s) tried: ['account/activate/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'] urls.py from .views import * from django.urls import re_path urlpatterns = [ re_path(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', user_activation_view, name='user_activation'), # user activation view ] template.txt {% autoescape off %} To activate your account ({{ user.email }}), please click the link below: {{ protocol }}://{{ domain }}{% url 'user_activation' uidb64=uid token=token %} If clicking the link above doesn't work, you can copy and paste the URL in a new browser window instead. If you did not make this request, please ignore this email. {% endautoescape %} -
Django: How do I print values from a checkbox to a new template?
I am creating a web application that will serve as a grocery store. The way I set it up is so the customer can come onto the website, click on the items that they would like to purchase, and then click a submit button on the bottom of the page to purchase those items. The problem I am struggling with is how to take the selected values from the checkboxes and print them onto a different page. """models.py""" class Post(models.Model): title = models.CharField(max_length=100) Price = models.DecimalField(max_digits=4, decimal_places=2,default=1) Sale = models.DecimalField(max_digits=4, decimal_places=2,default=1) quantity = models.IntegerField(default=1) author = models.ForeignKey(User, on_delete=models.CASCADE) category = TreeForeignKey('Category',null=True,blank=True, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) views.py class PostListView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' def inventory(request): products = request.POST.getlist('products') for product in products: a = Post.objects.get(title=products) a.quantity = a.quantity -1 a.save() print(products) return redirect('list') urls.py path('user/<str:username>', UserPostListView.as_view(), name='user-posts'), path('inventory', views.inventory, name='inventory'), home.html {% extends "blog/base.html" %} {% block content %} <form action="{% url 'inventory' %}" method="POST" id="menuForm"> {% csrf_token %} {% for post in posts %} {% if post.quantity > 0 %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2">{{ post.category }}</a> </div> <h2><a class="article-title" >{{ post.title … -
Django ORM - Aggregate by Decorator
I am trying to use the Django ORM to aggregate by a field and SUM up the value returned by a decorator. I'm new to the Django ORM so forgive me if I'm missing something. Here is my class: class Payroll(models.Model): job = models.ForeignKey(Job, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) ClockIn = models.DateTimeField() ClockOut = models.DateTimeField(null=True, blank=True) @property def time_worked(self): return self.ClockOut - self.ClockIn I want to aggregate by user, and sum up the time_worked decorator. If I were writing the SQL myself it would be: SELECT user, SUM(time_worked) FROM payroll GROUP BY user When I try users_time_worked = Payroll.objects.aggregate(Sum('time_worked')) the page crashes and the Django debug screen says: "Cannot resolve keyword 'time_worked' into field." Is it possible to sum a timdelta field created by a decorator using the Django ORM? Is this something I should calculate within the view? -
Is it intensive to get a model instance's property in Django
I am new to Django and have the following model: Person: - height - weight - name In one of my functions, I get person.height 5 times. Would it be better (from a computation perspective) to just store height = person.height and reference that? -
Django logging errors occuring in admin page [closed]
I face the following issue: I want to add a new instance of a model in the django admin page, but I do get an 500 error. I works for all other models, but not that specific one. Therefore I want to log errors occuring in the djnago admin page. I do know how to log for all non admin views. I could not find any documentation on how to get the logs of the admin page. Is there a way to get the logs of all errors in the admin page ? Thanks for any advice!