Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Automating Celery monitoring for abnormal queue length
I'm using Django/Celery/Redis to handle tasks that import large amounts of data into my db. Occasionally, something will go wrong and the workers seemingly hang -- I'm curious if there's a way for me to monitor the size of my queues inside of my Django application so that I can create a custom alert. For example, if my queue grows above 100, I'd like to create an alert. Right now, I'm just periodically checking the queues via the Redis CLI, but that is not sustainable. I realize that this question may be vague since there's no code, but I'm just not sure where to start here. -
Add a new attribute in serializer but doesn't appear
I want to add a new attribute apartment_sold in the Transaction serializer, but I seem it doesn't work! serializes.py class TransactionSerializer(serializers.HyperlinkedModelSerializer): buyer = serializers.ReadOnlyField(source='buyer.username') apartment_sold = serializers.HyperlinkedRelatedField(view_name='sold-detail', read_only=True) class Meta: model = Transaction fields = [ 'id','buyer','apartment_sold','timestamp' ] views.py class SoldViewSet(viewsets.ReadOnlyModelViewSet): queryset = Apartment.objects.filter(issold=True).order_by('-timestamp') serializer_class = ApartmentSerializer class TransactionViewset(viewsets.ModelViewSet): queryset = Transaction.objects.all().order_by('-timestamp') serializer_class = TransactionSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] def perform_create(self, serializer): transaction = serializer.save(buyer=self.request.user) transaction.apartment.issold = True transaction.apartment.save() -
how to add if condition in django with compare session value in html
I have an error when I compare the value of the session in the HTML templates error: Could not parse the remainder: '{{' from '{{' {% if {{ request.session.userinput }} == "Too low!" and {{ request.session.attempt }} < 5 %} <div class="box" style="background-color:rgb(235, 66, 66);"> <h1 class="boxh1">{{request.session.userinput}}!</h1> </div> {% elif {{request.session.userinput }} == "Too high!" and {{request.session.attempt}}< 5 %} <div class="box" style="background-color:rgb(235, 66, 66);"> <h1 class="boxh1">{{ request.session.userinput }}!</h1> </div> {% elif {{ request.session.userinput }} == {{ request.session.number }} and {{request.session.attempt}} < 5 %} <div class="box" style="background-color: rgb(119, 245, 147);"> <h1 class="boxh1">{{ request.session.number }} was the number!</h1> <a href="/destroy_session"><button class="replay-btn">Play again!</button></a> </div> {% endif %} <div id="k" class="form" > <form action="/guess" method="post"> <input class="num" type="text" name="num" required value=""/><br> <input class="btn" type="submit" value="Submit" /> </form> </div> view.py def guess(request): if request.session["attempt"]==5: request.session["attempt"]=5 if request.session["number"] == int(request.POST["num"]): request.session["userinput"] =request.session["number"] elif request.session["number"] < int(request.POST["num"]): request.session["userinput"]="Too high!" request.session["attempt"] += 1 elif request.session["number"] > int(request.POST["num"]): request.session["userinput"]="Too low!" request.session["attempt"] += 1 context ={ "attempt":request.session["attempt"], "userinput":request.session["userinput"], "number":request.session["number"] } return render(request,'index.html',context) Is correct the way that I compare session values in HTML? -
Confused about the import syntax in django for Render()
Im trying to understand the period in from django.shortcuts import render Does it mean from the django directory in the shortcuts file? Or does it mean from the django directory, from the shortcuts directory, import the render file? -
TypeError: 'ModelBase' object is not iterable when trying to use Exclude
I have the following two models: class Listings(models.Model): CATEGORY = [ ("Miscellaneous", "Miscellaneous"), ("Movies and Television", "Movies and Television"), ("Sports", "Sports"), ("Arts and Crafts", "Arts and Crafts"), ("Clothing", "Clothing"), ("Books", "Books"), ] title = models.CharField(max_length=64) description = models.CharField(max_length=500) bid = models.DecimalField(max_digits=1000000000000, decimal_places=2) image = models.URLField(null=True, blank=True) category = models.CharField(max_length=64, choices=CATEGORY, default=None) user = models.ForeignKey(User, on_delete=models.CASCADE, default="") class CloseListing(models.Model): listings = models.ForeignKey(Listings, on_delete=models.CASCADE, default="") user = models.ForeignKey(User, on_delete=models.CASCADE, default="") I want to be able to query through all the objects of every listing that is not in the CloseListing model. How can I do this? def index(request): listings = Listings.objects.all().exclude(id__in=CloseListing) return render(request, "auctions/index.html",{ "listings": Listings.objects.all() }) error message: TypeError: 'ModelBase' object is not iterable because of listings = models.ForeignKey(Listings, on_delete=models.CASCADE, default=""). -
UPS API call format with django to html
import xml.etree.ElementTree as ET from zeep import Client, Settings from zeep.exceptions import Fault, TransportError, XMLSyntaxError # Set Connection settings = Settings(strict=False, xml_huge_tree=True) client = Client('SCHEMA-WSDLs/RateWS.wsdl', settings=settings) # Set SOAP headers headers = { 'UPSSecurity': { 'UsernameToken': { 'Username': 'username', 'Password': 'password' }, 'ServiceAccessToken': { 'AccessLicenseNumber': 'asdasdasdasd' } } } # Create request dictionary requestDictionary = { "RequestOption": "Shop", "TransactionReference": { "CustomerContext": "Your Customer Context" } } # Create rate request dictionary rateRequestDictionary = { "Package": { "Dimensions": { "Height": "10", "Length": "5", "UnitOfMeasurement": { "Code": "IN", "Description": "inches" }, "Width": "4" }, "PackageWeight": { "UnitOfMeasurement": { "Code": "Lbs", "Description": "pounds" }, "Weight": "1" }, "PackagingType": { "Code": "02", "Description": "shop" } }, "Service": { "Code": "03",#3 – Standard List Rates "Description": "Service Code" }, "ShipFrom": { "Address": { "AddressLine": [ "1 toronto rd", ], "City": "North York", "CountryCode": "CA", "PostalCode": "M3J1C8", "StateProvinceCode": "ON" }, "Name": "Name" }, "ShipTo": { "Address": { "AddressLine": "15 Hillpark Trail", "City": "Brampton", "CountryCode": "CA", "PostalCode": "L6S1R1", "StateProvinceCode": "ON" }, "Name": "Name" }, "Shipper": { "Address": { "AddressLine": [ "Street Name", ], "City": "Toronto", "CountryCode": "CA", "PostalCode": "M3J1C8", "StateProvinceCode": "ON" }, "Name": "ZTL", "ShipperNumber": "+66666666" } } # Try operation try: response = client.service.ProcessRate(_soapheaders=headers, Request=requestDictionary, Shipment=rateRequestDictionary) … -
Django CORS - localhost with any port
Running into a CORS issue with my Django app. I've got it configured properly and I've narrowed the issue down to my list of URLS - settings CORS_ORIGIN_ALLOW_ALL = True fixes it. This is my current list: CORS_ALLOWED_ORIGINS = [ "http://localhost", ... ] My front end is a Flutter app, the problem is that in development Flutter runs on any random port e.g., localhost:12345, so I can't hardcode this into the CORS list. My question is this - how can I add localhost with any arbitrary port to the list? I can't seem to find docs on it, the only alternative seems to be to just allow everything which I'd prefer not to do. Thank you in advance! -
Django Template with a Dicitonary of Lists
Using django I am passing a dictionary of lists as the context for my template. The dictionary is structured as such: weather = { 'temp' : temp, 'time' : time, 'pop' : pop } Temp, time, and pop are lists of equal length with each index of those lists going together. Meaning temp[1] , time[1], and pop[1] are together and temp[2] , time[2], and pop[3] and so on. I would like to display these values like so: temp[1] time[1] pop[1] temp[2] time[2] pop[2] . . . temp[y] time[y] pop[y] #y is the length of the lists I have tried to do this by making a for loop in my template the looks like this: {%for x in weather%} <p> <span>{{weather.temp.x}}</span> <br> <span>{{weather.pop.x}}</span> <br> <span>{{weather.time.x}}</span> <br> </p> {%endfor%} But all this does is make empty lines. Could I get some help please? -
How to get access to a different object through a variable storing Django Max object?
I have a Django model called Bids with the following objects: listing, bid, and user. I am trying to get access to the user with the largest bid. How do you do that? I am currently trying: winning_bid = Bids.objects.aggregate(Max('bid')) winner = winning_bid.user -
Django Crispy Form with Toggle switch element
I am using Crispy Forms and layout helper to generate my Input form. I'd like to add a Toggle switch into the form. desired result: what I get: forms.py: class RequestForm(forms.ModelForm): on_prem = forms.CharField(widget=forms.CheckboxInput(attrs={"class": "slider form-control"})) class Meta: model = Request fields = ['on_prem'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.layout = Layout( Div( Div(Field('on_prem'), css_class='col-md-3', ), css_class='row', ), ) models.py: class Request(models.Model): on_prem = models.BooleanField(default=False) form.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} {% crispy form %} <button type="submit" class="d-block btn btn-outline-inverse mt-4 w-50 mx-auto"> Save Request </button> </form> I have seen in the Bootstrap documentation that the toggle switch effect I desire is achieved with nested css classes and I am not sure how to achieve that via the form helper. Any help would be greatly appreciated. -
django-environ can't read docker container variables
I'm using Docker containers with Django. In my container I'm using environment variables via .env file container_name: env_file: .env I have echoe'd SECRET_KEY after the container is up and it shows the correct value set in .env file. The problem is in my settings. When I do the following... import environ env = environ.Env() SECRET_KEY = env('SECRET_KEY', default='some_other_value') ... I was expecting "try to read 'SECRET_KEY' from the OS, but if you can't find it set it to 'some_other_value'. It turns out it isn't, having the following output: get 'SECRET_KEY' casted as 'None' with default '<NoValue>' On the other hand, if I do os.environ.get('SECRET_KEY') it gets the correct value. What am I doing wrong with django-environ package? -
Django: No module named 'admin'
I deleted my sqlite database and all migration folders and this happend: ModuleNotFoundError: No module named 'admin' I tried to do django.setup(), but it`s not working https://github.com/himokkk/django_images -
Docker RUN pip3 install -r requirements.txt Vs multiple RUN pip3 install?
I am using a Dockerfile in which I do : COPY requirements.txt requirements.txt RUN pip3 install -r requirements.txt In order to fasten the build phase I wanted to replace that by a succesion of RUN pip3 install library_xxx I can't figure out why, but this second way of installing doesn't produce any error in the build time, but then when launching django, django complains about not finding some libraries. Coming back to a install -r solve the issue. Any clue why these two different type of install could differ ? Here is the requirements.txt : django==3.1.2 Pillow==7.0.0 python-docx==0.8.10 django-crispy-forms==1.9.2 djangorestframework==3.12.2 python-barcode==0.13.1 uwsgi==2.0.19.1 psycopg2-binary==2.8.4 requests==2.22.0 pygraphviz==1.6.0 django-extensions==3.1.0 pafy django-colorfield django-debug-toolbar django-cors-headers factory_boy -
Django: data from context not displaying in template
i wrote a view to display top selling course, and then passed the data to the context dict to be able to access it in the template, but no data is showing in the template when i run a forloop on the queryset. views.py @login_required def dashboard(request): ... course_counts = UserCourse.objects.values("course").annotate(count=models.Count("course")).filter() sorted_courses = sorted(course_counts, key=lambda x: x['count'],reverse=True) context = { 'course_counts':course_counts, 'sorted_courses':sorted_courses, } return render(request, 'dashboard/dashboard.html', context) dashboard.html {% for course in sorted_courses %} <h1>{{ course.course_title }}</h1> {% endfor %} models.py class Course(models.Model): course_title = models.CharField(max_length=100, null=True, blank=True) course_creator = models.ForeignKey(User, on_delete=models.CASCADE) class UserCourse(models.Model): user = models.ForeignKey(User , null = False , on_delete=models.CASCADE) course = models.ForeignKey(Course , null = False , on_delete=models.CASCADE, related_name="usercourse") -
Error loading psycopg2 module after running heroku local command
I am attempting to run my Django project locally, in a virtual environment, using the heroku local command. After executing: heroku local my terminal throws the following error: django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: dlopen(/Users/anon/Desktop/anonsite/venv/lib/python3.10/site-packages/psycopg2/_psycopg.cpython-310-darwin.so, 0x0002): symbol not found in flat namespace '_PQbackendPID' Below are the projects dependencies: asgiref==3.4.1 backports.entry-points-selectable==1.1.1 distlib==0.3.3 Django==3.2.8 django-clear-cache==0.3 django-crispy-forms==1.13.0 filelock==3.3.2 pbr==5.7.0 platformdirs==2.4.0 psycopg2-binary==2.9.1 pytz==2021.3 six==1.16.0 sqlparse==0.4.2 stevedore==3.5.0 virtualenv==20.10.0 virtualenv-clone==0.5.7 virtualenvwrapper==4.8.4 I do not understanding why this is occurring, as I am able to run my project just fine with the command: python3 manage.py runserver However, my goal is to run the project using heroku. -
AttributeError: 'bool' object has no attribute 'delete'
I am receiving the above error from has_watchlists.delete() inside the if request.POST.get('close'):, but that line of code works fine inside if request.POST.get('add'):. How do I fix this? views.py #watchlist code if request.POST.get('add'): WatchList.objects.create(user=request.user, listing=listing) add_or_remove_watchlist = False elif request.POST.get('remove'): add_or_remove_watchlist = True has_watchlists.delete() #close listing code if request.POST.get('close'): CloseListing.objects.create(user=request.user, listings=listing) closeListing = True closeListingButton = False has_watchlists.delete() winner = max_bid.user return render(request, "auctions/listing.html",{ "auction_listing": listing, "comments": comment_obj, "bids": bid_obj, "closeListingButton": closeListingButton, "closeListing": closeListing, "closedMessage": "This listing is closed.", "winner": winner }) else: closeListing = False return redirect('listing', id=id) -
Annotating an annotated field in Django
I am trying to Count on a field that is generated by a previous Count in Django. Here is a simplified model: class CountryUpdate(models.Model): country = models.CharField() date = models.DateTimeField() There is a new entry every time some country is updated. Computing the number of updates per country is fairly documented: CountryUpdate.objects.values("country").annotate(total=Count("country")) What I would like to do now is count how many country has been updated X times. Basically, if I had the following entries: Country Date Germany 2021 Germany 2022 France 2021 Italy 2021 Spain 2021 I would like the following output: Number of updates Count 1 3 2 1 I tried annotating the previous queryset but it does not work. value = ( CountryUpdate.objects .values("country") .annotate(total=Count("country")) .values("total") .annotate(global_total=Count("total")) ) This gives the error Cannot compute Count('total'): 'total' is an aggregate This SQL query outputs exactly what is needed but I don't manage to put it in Django: SELECT total, count(total) from (SELECT "country_update"."country", COUNT("country_update"."country") AS "total" FROM "country_update" GROUP BY "country_update"."country") as t group by total; -
How to fix Django.core.exceptions.fieldError: Unknown field(s) in Modles.py
Hello I've run into a problem whilst working on my models.py file. As far as I can see the following seems right however it clearly isn't so I was wondering is anyone could direct me to the offending issue. The issue only started after I added the save function to the Command_Form. So I've included that as it may be relevant. Error Message In Question File "C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\models.py", line 327, in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (current_commands) specified for Command_Node Relevant Models.py class Command_Node(models.Model): host_id = models.ForeignKey(Beacon, on_delete=models.CASCADE) current_commands = models.CharField(choices=CHOICES, max_length=50, null=True), def __str__(self): return str(self.host_id) class EC_Node(models.Model): Command_node = models.ForeignKey(Command_Node, on_delete=models.DO_NOTHING) command = models.CharField(choices=CHOICES, max_length=50, null=True) def __str__(self): return str(self.Command_node) Relevant Forms.py class Command_Form(ModelForm): class Meta: model = Command_Node fields = ('host_id','current_commands') host_id = forms.ModelChoiceField( required=True, queryset=Beacon.objects.all(), widget=forms.SelectMultiple( attrs={ 'class': 'form-control' }, ) ) current_comamnds = forms.ChoiceField( required=True, choices=CHOICES ) def save(self, **kwargs): EC_Node.objects.create( command=self.cleaned_data["current_commands"], Command_node=self.instance ) return super().save(**kwargs) -
File "C:\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run(self)
Am trying to run a django server so I can program but when I ran 'python manage.py' run server I get this traceback. File "C:\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() please assist <3 -
Django model design pattern - get yougest related object
Django lets you follow relations link, but none of the filter methods let you get youngest/oldest, or max/min, afaik. Laravel has "has one of many", and I wish that Django had something similar without requiring window functions, that have their own limitations. Annotations despite being promising, are also a dead end. Therefore I wonder what the best design is for the following situation: I have "model A", whose instances will pass through several statuses during their lifecycle ("created", "processing", "complete"). I want to know what status an instance of model A currently has, but also have a record of when each status was in effect. I don't want to parse logs. I thought a good approach was to create a status model (model B) whose foreign key is a model A instance. it becomes easy to see when each status was started and stopped. However if I want to get the current status (an instance of model B) for all my model A instances, I need to do n+1 database queries. This seems sub-optimal. What are some alternatives? -
How to upload a text file from local storage into the server and access it from my website?
Im completely new to django, im working on a task to upload a text file from my local storage into server and access that file on my website from the server. Any guidance in that regard would be helpful. -
Update or create data from file CSV with unique field in Django
I would like to update or create data in my database by importing a CSV file. I tested and when I import the CSV file when the "plants" have not already been created it works but when there are the same name of the plants in my database I have an integrity error: IntegrityError : duplicate key value violates unique constraint "perma_plants_plant_name_key" DETAIL: Key (name)=(Test bis) already exists. So my update_or_create method does not work because in my model the name field must be unique. How can I do to solve this problem? Here is my model : class Plant(models.Model): name = models.CharField(max_length=150, unique=True) def __str__(self): return self.name Here is my view : class UploadFileView(generics.CreateAPIView): serializer_class = FileUploadSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) file = serializer.validated_data['file'] reader = pd.read_csv(file) for _, row in reader.iterrows(): Plant.objects.update_or_create( name=row['Name'], ) return Response({"status": "Success : plants created"}, status.HTTP_201_CREATED) Thank you for your answers -
upload a file while having a one to one relationship in django
sorry for all the code given but i have tried so hard for a day still ending up with a problem when passing stage_id as a parameter in the form action url I have a class Rapports that holds a file (i prefer pdf files) and have a 1to1 relationship with an other class from an other application, i'm sending the stage.id from a html page in Stages app and it's working the id is passed and i can pass it to an other html page but when i write the code i nedd and passe the same url pattern in the action attribute of the template i want to show(rapport/test.html down below) it return NoReverseMatch and i can't figure out why. Is it because i'm trying to upload a file or is it something else? (1st time working with files) {% block rpt %} <li class="nav-item"> <a class="nav-link" href="{% url 'rapport:depo' stages.id %}"> déposer le rapport </a> </li> {% endblock rpt %} rapport.Rapports from django.db import models from satges.models import Stages class Rapports(models.Model): stage=models.OneToOneField( Stages, on_delete=models.CASCADE, primary_key=True, ) src=models.FileField( ("rapport"), upload_to='rapports/', max_length=100 ) r_soummit=models.DateTimeField( auto_now=False, auto_now_add=False, ) satges.Stages class Stages(models.Model): #Stages attrs that are saved so i think no … -
How can I make my navigation bar to scroll to page I need?
Well,i have this part of my html code: <div class="upper-menu"> <ul> <li id="hope">Hope Lake</li> <li><a href="#Contact">Contact</a></li> <li><a href="#Services">Services</a></li> <li><a href="#About">About</a></li> <li><a href="#upper-menu">Home</a></li> </ul> <div class="photo-container"> <img src="images/image1.jpg" width="1440" height="740"/> <div class="centered">My Business</div> <div class="lower-centered">Creative solutions, creative results.</div> </div> </div> When I press the button(for example) 'Contact',it must to scroll to this part of my site, where I can read info about it.How can I realise it? -
Faster API for front end data table page?
I'm using Django to feed a front end web page built with React. I have an API that gets the necessary data with some formatting, but it's pretty slow. Any suggestions on how to build a faster API? It's currently returning 8 records which takes >3 seconds. def deployed_data(request): deployments = deployment.objects.filter(LAUNCH_DATE__isnull=False).filter(HISTORICAL=False) res = [] for dep in deployments: crt_dep = { "FLOAT_SERIAL_NO":dep.FLOAT_SERIAL_NO, "PLATFORM_NUMBER":dep.PLATFORM_NUMBER, "PLATFORM_TYPE":dep.PLATFORM_TYPE.VALUE, "DEPLOYMENT_CRUISE_ID":dep.DEPLOYMENT_CRUISE_ID, "DEPLOYMENT_PLATFORM":dep.DEPLOYMENT_PLATFORM.VALUE, "LAUNCH_DATE":dep.LAUNCH_DATE.strftime("%Y-%m-%d"), "status":dep.status, "last_report":dep.last_report.strftime("%Y-%m-%d %H:%M"), "next_report":dep.next_report.strftime("%Y-%m-%d %H:%M"), "days_since_last":dep.days_since_last, "last_cycle":dep.last_cycle, "age":dep.age.days } res.append(crt_dep) return JsonResponse(res, status = 200, safe=False)