Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Disqus comment section in Django blog not showing but only in 1 post
I can create new posts and Disqus comments will appear as well as in my old posts But for some reason not in this one. They all use the same code, It doesn't have sense to me. Didn't find any info on this issue. https://gsnchez.com/blog/article/El-var-como-medida-del-riesgo-de-mercado. This is the url, u can check it online. <div id="disqus_thread"></div> <script> /** * RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS. * LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/ var disqus_config = function () { this.page.url = gsnchez.com{{ request.get_full_path }}; // Replace PAGE_URL with your page's canonical URL variable this.page.identifier = {{post.id}}; // Replace PAGE_IDENTIFIER with your page's unique identifier variable }; (function() { // DON'T EDIT BELOW THIS LINE var d = document, s = d.createElement('script'); s.src = 'https://gsnchez.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })(); </script> -
Django query merge
I have two model classes on the "models.py" file. Signup & Notes from django.contrib.auth.models import User from django.db import models # Create your models here. class Signup(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) contact = models.CharField(max_length=10, null=True) branch = models.CharField(max_length=30) campus = models.CharField(max_length=30) role = models.CharField(max_length=15) def __str__(self): return self.user.username class Notes(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) uploadingdate = models.CharField(max_length=30) branch = models.CharField(max_length=30) subject = models.CharField(max_length=30) topic = models.CharField(max_length=200) notesfile = models.FileField(null=True) filetype = models.CharField(max_length=30) description = models.CharField(max_length=300, null=True) status = models.CharField(max_length=15) def __str__(self): return self.user.username + " " + self.status on my function i uses notes = Notes.objects.all() & users = User.objects.all() to get them. here is the funtion def indexnotes(request): notes = Notes.objects.all() users = User.objects.all() d = {'notes' : notes,'users' : users} return render(request,'indexnotes.html',d) I am using a for loop to show the values on a datatable. The code is like this <tbody > {% for i in notes %} <tr> <td>{{forloop.counter}}</td> <td>{{i.user.first_name}} {{i.user.last_name}}</td> <td>{{i.uploadingdate}}</td> <td>{{i.campus}}</td> <td>{{i.subject}}</td> <td><a href="{{i.notesfile.url}}" class="btn btn-success" download>Download</a></td> <td>{{i.filetype}}</td> <td>{{i.description}}</td> <td>{{i.status}}</td> <td><a href="{% url 'assign_status' i.id %}" class="btn btn-success" >Assign&nbsp;Status</a></td> <td><a href="{% url 'delete_notes' i.id %}" class="btn btn-danger" onclick="return confirm('Are you sure?')">Delete</a></td> </tr> {% endfor %} </tbody> Now the problem is some value of the table … -
Can I use pytesseract in a WebApp?
I am developing a WebApp with Django that allows users to upload an image, and "read" the text present in the image.I am using pytesseract to do this task. Everything worked well on my local machine, however when deploying this app on Linode (Ubuntu 18.04 LTS server) I keep getting an error. I am curious if this is due to my code, or due to the nature of linode/pytesseract. I have read online that some hosting companies have anti-virus software that could hinder the use of such packages. Does anyone have advice or any insight on this topic? I am fairly new to web dev. so any advice will help... -
Clone an object from a model to another
I need to automatically generate a new element into copyModel when an element is created inside the mainModel. This new element into copyModel must be the copy of the relative element from mainModel. This is only an excercize. I've developed my two models: class mainModel(models.Model): ''' main table ''' text = models.CharField(max_length=250) class copyModel(models.Model): ''' completely copied datas from mainModel ''' main = models.ForeignKey(mainModel, on_delete=models.CASCADE) text_copy = models.CharField(max_length=250) def save(self, *args, **kwargs): self.text_copy = mainModel.text_copy super(copyModel, self).save(*args, **kwargs) I'm using a simple admin site to make my tests: from django.contrib import admin from .models import copyModel, mainModel admin.site.register(copyModel) admin.site.register(mainModel) When I create a new object in mainModel it isn't copied into copyModel. Probably I've misundestanding the use of save method, but what is the right way to do my aim? -
Custom authentication middleware not working when objects is not overridden in model definition
Following the question I asked here I have a custom authentication middleware that does not work anymore if I do not override the objects. The models.py looks like this: class Person(AbstractUser): company_id = models.IntegerField(null=True, blank=True, default=None) role = models.CharField(max_length=255) def __str__(self): return "{last}, {first} ({id})".format( last=self.last_name, first=self.first_name, id=self.id ) If I leave the code like this, the authentication never takes place (and I end up in an infinite loop of redirections). Now, if I update my model by adding: objects = models.Manager() All of the sudden, the authentication takes place and it is (at least this part) is working fine. I know that the custom authentication middleware is updating the database when the user logs in. However, I can't figure out why I should override objects -
Stop AWS CloudFront stripping custom domain when re-directing
I have CloudFront caching a Django Lambda (Zappa) deployment. Everything is working fine except that when I visit my custom domain such as www.example.com it is re-directing to the Lambda execution URL like https://1234xb7gmc.execute-api.eu-west-2.amazonaws.com/ rather than keeping the custom domain. I think the flow is as follows: Custom Domain > CloudFront Domain > Lambda Domain I just want it so that at the end, the user is still using the custom domain and not the Lambda one (even though behind the scenes they're being invoked). Is there a name for this behavior? -
socket.gaierror: [Errno 11001] getaddrinfo failed in django
I am trying to build an ecommerce store with python and django. I am currently building a pay_on_delivery option, and for that, I am sending an email to myself from the email of the user. Here is my OrderForm: class OrderForm(forms.Form): name = forms.CharField(max_length=30) email = forms.EmailField() city = forms.CharField(max_length=100) address = forms.CharField(widget=forms.Textarea()) zip_code = forms.CharField(min_length=6,max_length=6) product = forms.CharField(max_length=200,widget=forms.TextInput(attrs={'placeholder':'Copy and paste the exact same name of the product you want to purchase'})) phone = forms.CharField(min_length=10,max_length=10) def save(self): cleaned_data = self.cleaned_data send_mail( "Product {cleaned_data['product']} ordered by {cleaned_data['name']}", "A product from our bakery has been ordered. Address: {cleaned_data['address']}. Zip code: {cleaned_data['zip']}. Phone: {cleaned_data['phone']}", cleaned_data["email"], ["rjain1807@gmail.com"], fail_silently=False, ) And my view function that handles the form submission: def buy(request,id): product = Product.objects.get(id=id) form = OrderForm() if request.method == 'POST': form = OrderForm(data=request.POST) if form.is_valid(): form.save() return HttpResponse("Your order has been successfully placed!!") context = { 'form':form, 'product':product, } return render(request, 'buy_page.html',context) Now, when I try to place an order, I get this traceback error upon the form submission: Internal Server Error: /products/1/buy/ Traceback (most recent call last): File "C:\Users\Dell\Desktop\Django\apnibakery\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Dell\Desktop\Django\apnibakery\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Dell\Desktop\Django\apnibakery\bakery\apnibakeryy\views.py", line 33, in buy … -
I got an error like this when pushing my django website to heroku
ModuleNotFoundError: No module named 'django_filters' i was working on my first e commerce website on django, when i almost finish and want to push my file to heroku I got this error, i was tring so many times and i cant find whats wrong about my codes, can someone find what wrong in my file requerements.txt: asgiref==3.3.1 astroid==2.4.2 autopep8==1.5.4 colorama==0.4.4 Django==3.1.4 django-bootstrap-form==3.4 django-crispy-forms==1.10.0 django-filter==2.4.0 django-shortcuts==1.6 django-tastypie==0.14.3 djangorestframework==3.12.2 gunicorn==20.0.4 isort==5.6.4 lazy-object-proxy==1.4.3 mccabe==0.6.1 Pillow==8.0.1 pycodestyle==2.6.0 pylint==2.6.0 python-dateutil==2.8.1 python-mimeparse==1.6.0 pytz==2020.4 six==1.15.0 sqlparse==0.4.1 toml==0.10.2 whitenoise==5.2.0 wrapt==1.12.1 this is my error: $ git push heroku master Enumerating objects: 158, done. Counting objects: 100% (158/158), done. Delta compression using up to 4 threads Compressing objects: 100% (151/151), done. Writing objects: 100% (158/158), 6.06 MiB | 211.00 KiB/s, done. Total 158 (delta 15), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing python-3.9.0 remote: -----> Installing pip 9.0.2, setuptools 47.1.1 and wheel 0.34.2 remote: -----> Installing dependencies with Pipenv 2018.5.18… remote: Installing dependencies from Pipfile.lock (68efdd)… remote: -----> Installing SQLite3 remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "/tmp/build_5aa9deac/manage.py", line 22, in <module> remote: main() remote: … -
Overriding a queryset for the Django Admin interface
I'm trying to limit the items available to choose from a dropdown list in the admin panel for a given model. At the moment, I overrode the save method to throw a valueerror if conditions are not met, but this is an ugly solution IMO. At the time I wrote that, I was not aware of proxy models, which seem like the solution, at least according to this answer. I have a model Entry, so I created a proxy model like so: class ApprovedEntries(Case): class Meta: proxy = True verbose_name = 'Entry' verbose_name_plural = 'Entries' def get_queryset(self, request): qs = Entry.objects.filter(assigned_contestant__approved='True', assigned_contestant__active='True') return qs Then in my admin.py I replaced the existing entry to register the Entry model with: admin.site.register(ApprovedEntries) However, this seems to have no effect. Only the unfiltered list of Entry objects is returned. Is something additional needed to 'activate' a proxy model? Is there a better solution to my problem? -
Content Object of model returning None when trying to access Generic Foreign key attribute
I have a few related models (truncated models for relevancy): class Product(models.Model): style = models.CharField(max_length=20, unique=True, primary_key=True, null=False, blank=False, verbose_name="Style ID") class Shipment(models.Model): shipment_id = models.CharField(max_length=9, blank=True, verbose_name="Shipment ID") status = models.CharField(max_length=3, verbose_name="Status") class InventoryItem(models.Model): unique_sku = models.SlugField(blank=True, verbose_name="Inventory System SKU") Shipment = models.ForeignKey(CastleShipment, blank=True, null=True, on_delete=models.SET_NULL) # GenericForeignKey fields for SKU models content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT) object_id = models.CharField(max_length=50) content_object = GenericForeignKey('content_type', 'object_id') class CSKU(models.Model): ShoeProduct = models.ForeignKey(Product, verbose_name="Style", on_delete=models.CASCADE) sku = models.CharField(max_length=50, verbose_name="SKU") upc = models.CharField(max_length=25, null=True, blank=True, verbose_name="UPC") def get_style(self): return "{0}".format(self.Product.style) When I try: inv = InventoryItem.objects.first() inv.content_object.get_style It returns error: 'NoneType' object has no attribute 'get_style_id' And inv.content_object returns nothing, however inv.content_type returns <ContentType: oms | csku> and inv.object_id returns '603' (both correct.) I'm able to access other attributes of generic foreign key relationships with .content_object.attribute so is there any reason why I wouldn't be able to here? -
Django-tables2 specifying verbose_name for column header has no effect
This seems like a very simple issue with no apparent cause. I'm trying to set a verbose name in a Django Tables2 table to change the column header. The documentation indicates this is the correct way to do this. My table is simple, like so: class ContestantsTable(tables.Table): id = tables.Column(verbose_name='Contestant ID') full_name = tables.Column(verbose_name='Name') class Meta: model = Contestant template_name = "django_tables2/bootstrap.html" fields = ("id", "full_name") The verbose name setting is completely ignored. If I set verbose_name on the field in the model it works, but I want to do this at the table level and not on the model (The name I want for the column won't be used elsewhere). I have another table where I am trying to set default="Unassigned which also does not reflect in the table for fields where there is no entry. I'm not sure why such a simple thing is failing. -
Why "Error: That port is already in use."
Yes obviously I run the command: killall -9 python But not working again same error Error: That port is already in use. Well, I can also use other port like 8001 instead of 8000 and BOOM!, but please explain why this happens ? -
Django query on datetime fields is correct on local postgres but returns incorrect result when deployed to heroku
I'm using django and I have this model from django.db import models class ViewTime(models.Model): start = models.DateTimeField() end = models.DateTimeField() I then query the sum of all the view times for each day with the following query. from .models import ViewTime from django.db.models import Sum, F ViewTime.objects.all() .values("start__date") .annotate(count=Sum(F("end") - F("start"))) .order_by("start__date") On my local postgres server is returns the expected query set in the format [{start__date, count}]. However I deployed to heroku and the query returns only one item in the query set with count being a time vector of 0 and date being the most recent object in the database. My files are all up to date on heroku. Other queries are performed succesfully. I am also running the same version of python as my deployment on heroku. I have not changed my timezone settings leaving them as LANGUAGE_CODE = "en-us" TIME_ZONE = "UTC" USE_I18N = True USE_L10N = True USE_TZ = True Please let me know if there is any other information that would be useful. -
Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding, when trying to start uwsgi
I am trying to start my uwsgi server, but after I added plugin python3 option I get this error every time: !!! Python Home is not a directory: /home/env3/educ !!! Set PythonHome to /home/env3/educ Python path configuration: PYTHONHOME = '/home/env3/educ' PYTHONPATH = (not set) program name = '/home/env3/educ/bin/python' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = '/home/env3/educ/bin/python' sys.base_prefix = '/home/env3/educ' sys.base_exec_prefix = '/home/env3/educ' sys.executable = '/home/env3/educ/bin/python' sys.prefix = '/home/env3/educ' sys.exec_prefix = '/home/env3/educ' sys.path = [ '/home/env3/educ/lib/python38.zip', '/home/env3/educ/lib/python3.8', '/home/env3/educ/lib/python3.8/lib-dynload', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x00007efe89db8780 (most recent call first): <no Python frame> Here is my uwsgi.ini file: [uwsgi] base = /home/env3/educ projectname = educ plugins = python3 master = true virtualenv = /home/env3/%(projectname) pythonpath = %(base) env = DJANGO_SETTINGS_MODULE=%(projectname).settings.pro module = %(projectname).wsgi:application socket = /tmp/%(projectname).sock chmod-socket = 666 I use Python 3.8.5 I am trying to use Django + uWSGI + nginx + Postgresql If you need more details I will give it Thank you -
what is the use of this package 'django-tenant-users'?
I want to know how to access a Django multitenant user in a single login(my-domain.com/login). After logging in it should be redirected to a specific tenant subdomain(tenant1.my-domain.com). 'django-tenant-users' this package is helpful or not for multiple tenants in single login. https://github.com/Corvia/django-tenant-users Please give me a solution to that. -
AssertionError: First parameter to ForeignKey must be either a model, a model name, or the string 'self'
I just created a model like this : from django.db import models # Create your models here. class Category: title = models.CharField(max_length=50) slug = models.CharField(max_length=200) cat_image = models.ImageField(upload_to='images/') def __str__(self): return self.title class Brand: title = models.CharField(max_length=50) slug = models.CharField(max_length=200) brand_image = models.ImageField(upload_to='images/') def __str__(self): return self.title class UOM: title = models.CharField(max_length=100) def __str__(self): return self.title class Product_Images: multi_images = models.ImageField(upload_to='images/') class Product: name = models.CharField(max_length=100) slug = models.CharField(max_length=200) category = models.ForeignKey(Category, on_delete=models.CASCADE) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) price = models.IntegerField(null=True, blank=True) height = models.IntegerField(null=True, blank=True) weight = models.IntegerField(null=True, blank=True) length = models.IntegerField(null=True, blank=True) color = models.IntegerField(null=True, blank=True) stock = models.BooleanField() SKU = models.CharField(max_length=150) def __str__(self): return self.name class Customer: phone_number = models.CharField(max_length=11) first_name = models.CharField(max_length=10) last_name = models.CharField(max_length=10) email = models.CharField(max_length=20) password = models.CharField(max_length=10) def __str__(self): return self.first_name class Order: customer = models.ForeignKey(Customer, on_delete=models.CASCADE) invoice = models.CharField(max_length=16, null=True, blank=True) phone = models.CharField(max_length=12) address = models.CharField(max_length=150) But facing this error dont have any idea why i am getting this kind of error. I cant even makemigrations if i delete some fields. It says no change detected but i changed some fields still getting this kind of error can some one solve this issue for me. and please explain why ia magetting … -
Django User Model AttributeError: 'str' object has no attribute 'objects'
I am using django as my backend for a project but anytime i perform queries on my User model, i get the error AttributeError: 'str' object has no attribute 'objects' But this error only occurs when i import the user model from settings from django.conf import settings User = settings.AUTH_USER_MODEL but not from from django.contrib.auth.models import User Settings.py AUTH_USER_MODEL = 'users.User' User's Models.py from django.db import models from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings from rest_framework.authtoken.models import Token class UserManager(BaseUserManager): def create_user(self, email,username, password, phone, **extra_fields): if not email: raise ValueError("Email Address Is Needed") if not username: raise ValueError("Username Must Be Provided") email = self.normalize_email(email) user = self.model( email=email, username=username, phone=phone ) user.set_password(password) user.is_active = False user.save() def create_superuser(self, email,username, password,phone): email = self.normalize_email(email) user = self.model( email=email, username=username, phone=phone ) user.set_password(password) user.is_active = True user.is_admin = True user.save() class User (AbstractBaseUser): username = models.CharField(max_length=254,blank=False,null=False,unique=True) email = models.EmailField( unique=True, max_length=254, blank=False, null=False) phone = models.CharField(max_length=250,blank=False,null=False,unique=True) is_active = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email','phone'] def get_full_name(self): return f"{self.first_name} {self.last_name}" def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" … -
Can't retrieve value from Django Template (.html) to my views
I'm new to Django and I'm trying to develop an apllication that deals with learning objects metadata. One of the functions of the system is to view the L.O. metadata in browser. I have an HTML template that lists the result of the query from the database. Each result come along with a "Visualize Metadata" button, that when clicked, should display the metadata of that object in browser. So I want my button to pass the object ID back to my view, so i can make another query by the specific ID and print the results on the screen. This is my template .html {% if objects %} <ul> {% for object in objects %} <li> {{ object.General.title }} <form action='visualize' method='POST' name='id' value="{{object.General.id}}"> {% csrf_token %} <button type="submit" >Visualize Metadata </button> </form> </li> {% endfor %} </ul> {% else %} <p>No results found.</p> {% endif %} And this is my views.py function def visualize_lom_metadata(request): if request.method == 'POST': objID = request.POST.get('id') return HttpResponse(objID) For now i just want to see if that's possible by printing the objID in the screen. But when I try to do that,it just returns "None". Anyone knows how to retrieve data from template.html to … -
Django ModeForm display model field of foreign key instead object id
I am trying to show a model field in a select field in my template. I am using a foreign key which is selected in the select field. The problem is that only the object id is shown. How can I make it show a model field of my foreign key ('crt_id' from Certificate model for example) and not an object and the id? (see picture) Thank you in advance my code: Certificate model class Certificate(models.Model): crt_id = models.CharField(max_length=60) crt_expire = models.DateTimeField() crt_active = models.BooleanField(default=False) Device model class Device(models.Model): device_name = models.CharField(max_length=64) device_group = models.CharField(max_length=64) device_certificate = models.ForeignKey(Certificate, models.SET_NULL, blank=True, null=True) forms.py class DeviceForm(forms.ModelForm): device_group = forms.CharField(required=False) device_name = forms.CharField(required=True) class Meta: model = Device fields = [ 'device_name', 'device_group', 'device_certificate' ] -
How to implement orm left join
I have to following models: class A(models.Model): id = models.IntegerField(max_length=20, primary_key=True) appid = models.IntegerField(max_length=20,default=0) status = models.IntegerField(max_length=20) class B(models.Model): id = models.IntegerField(max_length=20, primary_key=True) appid = models.IntegerField(max_length=10,null=False,default='0') c = models.ForeignKey(C) a = models.ForeignKey(A) class C(models.Model): appid = models.IntegerField(default=0) ip = models.CharField(max_length=50, null=True, blank=True) Now I want a Django query: select C.ip,status from A left join C on A.appid = C.appid where appid = B.appid; Please kind people help me how to use orm to achieve -
How to pass a variable from a Django view to forms.py, to assist in overriding a query for a field?
I'm trying to pass a variable to a Django form to use as the criteria to filter my queryset by. The setup is that there are 'contestants', 'entries' and 'teams', and for a form on a page to view entries, I want to show only contestants on the same team as the logged in user. My attempt currently is with my view: def viewentry(request, urlid): entry = Entry.objects.get(id=urlid) team_id = entry.assigned_contestant.assigned_team.id form = AssignTeamContestantForm() if request.method == 'POST': form = AssignTeamForm(request.POST, instance=entry, team_id=team_id) if form.is_valid(): form.save() context = { 'entry': entry, 'urlid': urlid, 'form': form, } return render(request, 'entries/entry.html', context) and in my form: class AssignTeamContestantForm(forms.ModelForm): def __init__(self, team_id, *args, **kwargs): super(AssignTeamContestantForm, self).__init__(*args, **kwargs) self.fields['assigned_contestant'].queryset = Contestant.objects.filter(assigned_team__id=team_id) class Meta: model = Entry fields = ['assigned_contestant'] labels = {'assigned_contestant': ''} This is my latest attempt, I've been trying a lot of different things based on other answers I've found but can't seem to get anything to stick. What is the best approach for this problem with Django 3? -
What does max_retries and retry_backoff_max mean if retry_backoff is set to True in Celery?
The celery documentation gives the following example for automatically retrying a task: class BaseTaskWithRetry(Task): autoretry_for = (TypeError,) retry_kwargs = {'max_retries': 5} retry_backoff = True retry_backoff_max = 700 retry_jitter = False retry_backoff means that Celery will use exponential backoff - so in this case (according to the docs): The first retry will have a delay of 1 second, the second retry will have a delay of 2 seconds, the third will delay 4 seconds, the fourth will delay 8 seconds, and so on. However, in the example max_retries is five, and yet retry_backoff_max is 700. I would think that if max_retries is set to five, then the retries would happen at one second, two seconds, four seconds, eight seconds, and sixteen seconds. That is all, because that's five retries. The backoff never gets anywhere close to 700 seconds. Is retry_backoff_max in the given example pointless? What does max_retries of five actually mean in this example? -
Streaming zip in Django for large non-local files possible?
I've got a proxy written in Django which receives requests for certain files. After deciding whether the user is allowed to see the file the proxy gets the file from a remote service and serves it to the user. There's a bit more to it but this is the gist. This setup works great for single files, but there is a new requirement that the users want to download multiple files together as a zip. The files are sometimes small, but can also become really large (100MB plus) and it can be anywhere from 2 up to 1000 files simultaneously. This can become really large, and a burden to first get all those files, zip them and then serve them in the same request. I read about the possibility to create "streaming zips"; a way to open a zip and then start sending the files in that zip until you close it. I found a couple php examples and in Python the django-zip-stream extension. They all assume locally stored files and the django extension also assumes the usages of nginx. There are a couple things I wonder about in my situation: I don't have the files locally stored. I can … -
How to find the highest value of a ForeignKey field for a specific user in Django
I am building an app that allows users to record their workouts. First they will create an exercise, (e.g Bench Press), and then they will complete a form to show how much weight they were able to lift for that specific exercise. Their results will display below the form. There will be many workout forms, relating to many different workouts. The workouts and exercises will also be specific to each user. Here is my models.py: from django.contrib.auth.models import User class Exercise(models.Model): name = models.CharField(max_length=100) class Workout(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) weight = models.DecimalField(default=0.0, max_digits=5, decimal_places=1) exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE, default=None) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) What I now want to do is be able to show the user what their max lift was for each different workout, but can't figure out how to retrieve this information. I have searched for the answer online and it seems that using aggregate or annotate might be the way to go, but I have tried a bunch of different queries and can't get it to show what I need. Hope somebody can help. -
Static files not loaded into templates
I am new to Django and so far all I know about static files is that they are CSS, JS, and images and they should be in a directory called static within the app directory but when I use one of these files in my template like that: first I load the static files {% load static %} <!-- in the 1st line of the template --> then I link the CSS file like that <link href="{% static 'auctions/styles.css' %}" rel="stylesheet"> They don't load and the styles don't seem to appear so I just want to know what I am missing here