Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pre-commit hook to check django migrations
I'm trying to write a pre-commit hook to my Django project that checks for missing migrations. That is, it ensures all changes are reflected in a migrations file. One way to implement this is to PASS the pre-commit hook if the makemigrations command returns no changes. $ ./manage.py makemigrations --dry-run No changes detected And to FAIL the pre-commit hook if it returns something: $ ./manage.py makemigrations --dry-run Migrations for 'myapp': myapp/migrations/0003_auto_20201213_2233.py - Alter field type on event How can I write this pre-commit hook? Is there a better approach than using makemigrations? This is what I have so far but it always passes (I think I need to parse the response): repos: - repo: local hooks: - id: pre-commit-django-migrations name: Check django migrations entry: ./manage.py makemigrations --dry-run language: system types: [python] pass_filenames: false -
Carousel Item exceeding height..or height not adjusting to carousel item
https://topqna.herokuapp.com/ The text is missing in each carousel item, each time i have to manually adjust the carousel height and add < br> to get it to work but every day's text length might be different. Is there an automatic way so that the the entire text is visible while also the gap between navbar and item is fixed. Here's the html (albeit as a django template) {% load staticfiles %} {% load static %} {% load index %} <html lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1"/> <link rel="stylesheet" href="{% static 'style.css' %}"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> </head> <body> <nav> <div class="container nav-wrapper"> <div class="flex-container"> <h class="brand-logo center"><b>Today's Q/A</b></h> <ul id="nav-mobile" class="Center"> <li><a href="/"></a></li> </ul> </div> </div> </nav> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <script> $(document).ready(function(){ $('.carousel').carousel(); }); autoplay() function autoplay() { $('.carousel').carousel('next'); setTimeout(autoplay, 4500); } </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> {#<section class="black">#} <style> html, body{ background-color: #FEDCC8; } .flex-container { display: flex; flex-direction: row; flex-wrap: wrap; justify-content: space-evenly; } </style> <div class="flex-container"> <div class="container-fluid"> <a class="btn waves-effect waves-light" href="/kiddinglol">Cute Cat Pic <3 <i class="large material-icons left">sentiment_neutral</i> <i class="large material-icons right">sentiment_very_satisfied</i> </a> </div> <div class="container-fluid"> <a class="btn waves-effect waves-light" href="/iamonceagainsaying_your_net_sucks_sry"> C O Z Y <i class="large material-icons left">favorite</i> <i class="large material-icons right">favorite</i> … -
filter user records based on their names
I simply have a django medical website where users have their medical records and can view when logged in. I have achieved the filtering based on user that is logged in, what i want is another user(doctor) to see this records based on user(patient he selects). currently the doctor can see if the record is one(using get_object_or_404, but i want loop over many records. The models.py class Medrecs(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE, related_name="meds") title = models.CharField(max_length=60, null=True) doctor = models.ForeignKey('Doctors.Doctor', null=True, on_delete=models.PROTECT) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) date = models.DateTimeField(auto_now=True, null=True) meds = models.TextField() def __str__(self): return self.title Views.py def detail(request, pat_id): patient = get_object_or_404(Patient, pk=pat_id) medrecs = Medrecs.objects.all().filter(user=request.user) return render(request, 'MyDoc/detail_pat.html', {'patient': patient}, {'medrecs': medrecs}) In the view above i can see the patient records which are single records, but the medrecs(Medical records am unable to filter them based on the user(patient), it just gives me the page with the code(the template page unexecuted ). Medrecs.objects.filter(user=request.user) same case, .get will bring the number of rows and an error multipleobjects returned. As a side note i was able to filter this records in the user's(profile page) with the view: def my_profile(request): if request.user.is_authenticated: meds = Medrecs.objects.all().filter(user=request.user) return render(request, 'MyDoc/my_profile.html', {'meds': … -
Any way to distribute load between microservice api points from inside a celery task?
I have a Django back-end which takes some data and does some heavy processing on it which might take up to one minute. There is a microservice endpoint hosted on different servers which takes in all the data and does the work. Now, I have to send a POST request from inside the celery tasks to those servers. I am facing difficulty on how to actually implement network traffic management and send different requests to different servers (all of them produce the same result). Here is a sample of the celery task: @app.task def execute(**kwargs): ... exec_args = { "code" : code, "filename" : filename, "time" : time, "mem" : mem, "compile_command" : language.compile_command, "run_command" : language.run_command } param = { "input_file_urls": input_file_urls, "input_file_hashes": input_file_hashes, "output_file_hashes": output_file_hashes, "output_file_urls": output_file_urls, "exec_args": exec_args } net_res = requests.post(executor_url, json=param) net_res = net_res.json() ... Now the problem is in the executor_url part. I have different urls how do I load balance between them. -
Model permissions via a ForeignKey relationship
How can I instruct Django that the permissions for a model are resolved via a ForeignKey relationship where those permissions are declared? from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models class ConfidentialityLevel(models.Model): """ A possible level of confidentiality of stored records. """ name = models.CharField(primary_key=True, max_length=50) class LoremRecord(models.Model): """ Lorem record. """ uuid = models.UUID(primary_key=True) class IpsumRecord(models.Model): """ Ipsum record. """ uuid = models.UUID(primary_key=True) class RecordConfidentiality(models.Model): """ A level of confidentiality for a record. """ record_type = models.ForeignKey(ContentType) record_name = models.CharField(max_length=50) record = GenericForeignKey(ct_field='record_type', fk_field='record_name') level = models.ForeignKey(ConfidentialityLevel) Each ConfidentialityLevel name is used for categorising which users may view (etc.) records. Examples might be secret, embargoed, beta, published. Each RecordConfidentiality instance represents that the particular record (which might be a LoremRecord, or IpsumRecord, etc.) should be confidential only to those users with permission to ConfidentialityLevel level. So permissions will be (for example) view_secret_record, edit_embargoed_record, delete_published_record. The intention is that these apply to any of LoremRecord, IpsumRecord, and any others which might be referenced from RecordConfidentiality. How can I implement authentication so that users can only perform an action on the record, if they have the ConfidentialityLevel permission corresponding for that record? -
Django Back and Next button in html file
I read django document, I know django has get_next_by_foo with foo is datetime and dont have not null=True. I created in model 2 function get_previous, and get_next but when I call it in html file, i doesnt show anything In my model.py class Contracts(models.Model): id=models.AutoField(primary_key=True) contract=models.CharField(max_length=255,blank=True, null=True) name=models.CharField(max_length=255,blank=True, null=True) debt=models.IntegerField(blank=True, null=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now_add=True,blank=True) objects=models.Manager() class Meta: ordering=["-created_at"] def get_absolute_url(self): return "/contract_detail/%s/" % self.contract in my view.html def next_back(request, id=None): queryset = get_object_or_404(Contracts, id=contract) the_next = queryset.get_next_by_created_at() the_prev= queryset.get_previous_by_created_at() context ={ "title": queryset.title, "instance": queryset, "the_next" : the_next, "the_prev": the_prev, } return render(request, "contract_detail.html", context) in my url.py urlpatterns = [ path('admin/', admin.site.urls), path('demo',views.showDemoPage), #path("",views.home, name='home'), path('customer/', views.index, name='index'), path('customer1/', views.list_contract, name='list_contract'), path('add_items/', views.add_items, name='add_items'), path('search/', views.searchcontract, name='search'), path('contract_detail/<str:pk>/', views.contract_detail, name="contract_detail"), url(r'^export/csv/$', views.export_search_csv, name='export_search_csv'), and in my contract_detail.html <a href="{{ the_next.get_absolute_url }}">Next</a> <a href="{{ the_prev.get_absolute_url }}">Previous</a> Do I misunderstand its concept? If I do, how can I deal with it? Thanks in advance! -
Is it possible to runserver with django without makemigrations?
I am trying to separate my project into multiple sub projects. Model for users has changed. I have only deleted some unnecessary fields. There are no newly added fields or amended field data. From the existing main project, I have done makemigrations and migrated them all. For example, the User model in the file models.py for the main project would look like this. class User(AbstractBaseUser): password = models.CharField('password', max_length=128, blank=True) username = models.CharField('username', max_length=50, unique=True) email = models.EmailField('email_address', blank=True) phone = PhoneNumberField('phone', blank=True) address = models.CharField('address', blank=True) python manage.py makemigrations and python manage.py migrate is all completed so the user model is set in my database. In the new sub project, the model would look like this. class User(AbstractBaseUser): password = models.CharField('password', max_length=128, blank=True) username = models.CharField('username', max_length=50, unique=True) email = models.EmailField('email_address', blank=True) The sub project is also connected to the same database which the main project is using. If I python manage.py runserver this sub project, ValueError: Dependency on app with no migrations: {application name} occurs. Runserver works properly if i python manage.py makemigrations. Is there any ways for me to not makemigrations and run my subproject server? I don't want to makemigrations because I am still using the … -
Python, Django: django-filter and ForeignKeys
Good morning, I would like to ask if there's a way to use django-filter with the Foreignkey? For example: models.py class Company(models.Model): name = models.Charfield(max_length=50, null=False, blank=False) location = models.Charfield(max_length=50, null=False, blank=False) class Person(models.Model): first_name = models.Charfield(max_length=50, null=False, blank=False) last_name = models.Charfield(max_length=50, null=False, blank=False) age = models.Integerfield() company = models.ForeignKey(Company, null=False, blank=False, on_delete=models.CASCADE) filters.py class PersonFilter(django_filters.FilterSet): class Meta: model = Person fields = [ 'first_name ', 'last_name ', 'company ', ] Right now, I only know how to filter for the whole company and often thats's totally fine, but is there a way to - for example - filter for the 'loaction' or any other values as long it's connected with ForeignKey? And if it's not, is there a better solution than django-filter? Thanks to all of you and a great day! -
How to embed a valid CSRF token in a Django Transactional email hyperlink
My application sends an email to a user a when a specific event occurs. I would like the user to be able to click on one of two buttons 'accept'/'decline' within the email body, and execute a request which then my Django application can receive and process. The user needs to be authenticated (its ok if link also does an auto-login). My intuition tells me that it will have to be done via a get() request, with a ton of logic that stores keys, verifies them, log's in the user etc. Is that the only way? -
How to save data in django without method post and forms?
I'm trying to save data, but i don't want to use method post or forms there's some way to do it?. I can do something like this? class Number(models.Model): data = models.PositiveIntegerField() The view from django.shortcuts import render from .models import Number def x(request): #something different happened to (if request method ==POST, GET,etc) number = Number.objects.create(data=1) #now something different happened and the view automatically do something like this. number = number +1 number.save() Can i do this with django? I appreciate your help -
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.