Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) -
How to render from a string-based template to string without configuration in Django?
I just want to use Django template language without setting up Django. So far, the only way I figured out was this: from django.template import Context, Engine greetings = "Hello, {{name}}!" rendered = (Engine() .from_string(greetings) .render(Context({"name":"Django"})) ) assert rendered == "Hello, Django!" Is there any better way to achieve the same? -
How to create a function for organising objects on the template
I am trying to create a template for a blog landing page. While the politics object is less than four, I want the first for loop to be executed. **political.html {% extends 'index.html' %} {% block content %} {% for politics in politics %} <div class="post-entry-1 col-lg-4 box mx-1"> <a href="single-post.html"><img src="{{politics.image.url}}" alt="" class="post_img"></a> <div class="post-meta"><span class="date">{{politics.category}}</span> <span class="mx-1">&bullet;</span> <span>{{politics.created_at}}</span></div> <h2 class="mb-2"><a href="single-politics.html">{{politics.title}}</a></h2> <span class="author mb-3 d-block">Ole Pundit</span> <p class="mb-4 d-block">{{politics.body|truncatewords:75}}</p> </div> {% if politics > 4 %} {% for politics in politics %} <div class="post-entry-1 border-bottom"> <div class="post-meta"> <span class="date">Culture</span> <span class="mx-1">&bullet;</span> <span>Jul 5th '22</span> </div> <h2 class="mb-2"> <a href="single-post.html">How to Avoid Distraction and Stay Focused During Video Calls? </a> </h2> <span class="author mb-3 d-block">Jenny Wilson</span> </div> {% endfor %} {% endif %} {% endfor %} {% endblock %} But once the count of the political posts exceeds 4 I want the second for loop to be executed. Ideally, the function is supposed to help me organise where the posts appear on the landing page. **view.py from django.shortcuts import render from .models import Post, Politics from django.views.generic import DetailView # Create your views here. def index(request): return render(request, 'index.html') def allposts(request): posts = Post.objects.all() return render(request, 'allposts.html', {'posts':posts}) def … -
UWSGI - Different Flask UPLOAD_FOLDER for each worker/process running
Is it possible to have a different UPLOAD_FOLDER for every UWSGI worker? app-python | WSGI app 0 (mountpoint='') ready in 16 seconds on interpreter 0x558d526ffae0 pid: 8 (default app) app-python | >>> Files will be uploaded in: /app-python/upload app-python | WSGI app 0 (mountpoint='') ready in 16 seconds on interpreter 0x558d526ffae0 pid: 10 (default app) app-python | >>> Files will be uploaded in: /app-python/upload app-python | WSGI app 0 (mountpoint='') ready in 16 seconds on interpreter 0x558d526ffae0 pid: 9 (default app) app-python | >>> Files will be uploaded in: /app-python/upload app-python | WSGI app 0 (mountpoint='') ready in 16 seconds on interpreter 0x558d526ffae0 pid: 1 (default app) To explain further, I would like each worker to have a separate upload folder, app-python/upload1 , app-python/upload2 and so on. The reason I'm asking for this request is I think this is causing some files to be overwritten and the output I get from the app doesn't make any sense, and the only logical reason is that the workers are overwriting each other's files. Please let me know if I'm right, and if I am, please tell me if I can set a different upload folder for each worker. I'm also going to … -
How do I increase database variable by 1 using put method is JS?
I am making a web app similar to twitter that allows users to like a post. In order to make changes to the database, I created an API that allows one to use GET, PUT, or POST methods in order to access or make changes to the database. I am using a Django Framework database and am using javascript to send fetch requests to the API. My problem is that I am trying to use a put method to set the "likes" attribute of a post equal to 1 more than the previous number of likes the post had. I don't know how to do this. Below is my javascript function that runs once a post is liked. I tried to access the number of likes a post has and set it equal to a variable. However, that is not working. function likePost(postID){ var postLikes; fetch('/posts/' + postID) .then(response => response.json()) .then(post => { postlikes = post.likes }) fetch('/posts/'+postID, { method: 'PUT', body: JSON.stringify({ likes: postLikes++, liked: true }) }) console.log(postLikes) } For some reason, the console.log returns NotaNumber, meaning that postlikes is not set equal to post.likes and is never instantiated. Thus, "likes" is never set equal to postLikes++ … -
how to make the same button in a django html page turn on different LEDs
I have built a web application using django framework and put it in a raspberry pie 3 b+ in order to controle LEDs to indicate the location of specific products in the stock and make finding them easy and more efficient. my problem is that right now the button used to light up the LEDs is hadcoded with the url of a single LED, this the only way that I managed to make it work. I want to make the button dynamically change the LED that is going to light up for example based on the the Refrences id. html page list_references.html <div class="jumbotron"> <div class="header">{{header}}</div> <form method='POST' action=''>{% csrf_token %} {{form|crispy}} <input type="submit" value='Search'/> <br><br> <a href="/Ajouter_references"><div class="btn btn-primary mybutton">Ajoute Référence</div></a><br><br> </form> <br> <table class='table'> <thead> <tr> <th>REF</th> <th>DESIGNATION</th> <th>INDICE</th> <th>EMPLACEMENT</th> <th>NUM</th> <th>CLIENT</th> <th>LOCATION</th> <th>ETAT</th> <th>SUIVI</th> <th>SUPPRIMER</th> </tr> </thead> {% for instance in queryset %} <tr> <td><a href="{% url 'update_ref' instance.id %}">{{instance.Ref}}</a></td> <td>{{instance.Designation}}</td> <td>{{instance.Indice}}</td> <td>{{instance.Emplacment}}</td> <td>{{instance.Num}}</td> <td>{{instance.Client}}</td> <td><a href="{% url 'led1' %}"><BUTTON onclick="",>INDIQUER POSITION</BUTTON></a></td> <td>{{instance.Statut}}</td> <td><a href="{% url 'suivi_ref' %}"><BUTTON>SUIVI L'ECRAN</BUTTON></a></td> <td><a href="{% url 'delete_ref' instance.id %}"><img src="{% static 'img/del.png' %}"></a></td> </tr> {% endfor %} </table> </div> </main> views.py led1,led2,led3= 3,5,7 rpi.setwarnings(False) rpi.setmode(rpi.BOARD) rpi.setup(led1, rpi.OUT) rpi.setup(led2, rpi.OUT) rpi.setup(led3, rpi.OUT) … -
How to set xframe options properly to display a pdf
So I get this error when trying to render a pdf in html with Refused to display 'http://127.0.0.1:8000/' in a frame because it set 'X-Frame-Options' to 'deny'. I already tried Setting X_FRAME_OPTIONS = 'SAMEORIGIN' Using @xframe_options_sameorigin as decorator to my view Removed the xframe package in the settings nothing seems to work so I don't know what to do anymore. -
Django test with fixtures gives ForeignKeyViolation or IntegrityError
I am trying to write test cases for the Django RestAPI that we have but I have an issue with the fixtures loading. Everything works correctly when I have only one TestCase but when I add a second TestCase in a second django app I get django.db.utils.IntegrityError. My original intention was to create a general TestCase where I set up the most used objects in the setUpTestData function and make the other tests inherit from that one. Things I have tried: Using APITestCase from rest_framework and TestCase from django Not using inheritance, and having both files using TestCase from django Using setUp method instead of setUpTestData Using call_command from django.core.management in the setUpTestData method instead of creating the fixtures in each class in the class variable Declaring the fixtures only in the TestCase that is executed first (this makes the other TestCase have an empty DB, so it it clear that for each TestCase info is recreated) Changed the order of the files in the fixtures variable When I comment one of the test files the other works and vice-versa. When I used the call_command with verbose=2, the fixtures in the first file executed work perfectly, and it breaks just … -
How to I get the path to a file with Django?
I am currently using Django's forms to create a FileField that allows the user to upload a file. However, after I select the file, it creates an object of type django.core.files.uploadedfile.InMemoryUploadedFile, which is a copy of the original file. How would I go about to get the original path of this file so I can either modify or replace it? # forms.py class UploadFile(forms.Form): file = forms.FileField(label="Select File: ", required=True) # views.py def get_path(response): context = {} if response.method == "POST": form = UploadFile(response.FILES) if form.is_valid(): file = form.cleaned_data["file"] # Is there a way to get the original file path or should I just not use FileField? print("The File Path Here") -
How to query objects from parent table along with data from related model
I have a model 'Product' to upload products. class Product(BaseModel): ... ... class Meta: db_table = TABLE_PREFIX + "product" I have another table with product as foreignkey. class ProductImage(BaseModel): product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True) image = models.ImageField(upload_to='product') class Meta: db_table = TABLE_PREFIX + "product_image" In home page i want to display these products. I have the home view as def home(request): category_obj = Category.objects.all() product_obj = Product.objects.all().order_by('-id') context = { "title": "Home", "product_obj": product_obj, "category_obj": category_obj, } return render(request, "home/index.html", context) In the template I want to display the products along with the images. I am able to display all the details in the template except images. <div class="dFlex product-list-wrap"> {% for product in product_obj %} <div class="img-wrap"> <img src="" alt="Product Image"> </div> <h4>{{ product.name}}</h4> <p>{{ product.description}}</p> {% endfor %} </div> How do i display images on my template? How can I query images also while querying products? Thank you -
How to test two django forms that are in the same view
So I have a view that handles two different forms in the same POST request. Previously the testing was easy because i had only one form so it would be something like: def test_post_success(self): response = self.client.post("/books/add/", data={"title": "Dombey and Son"}) self.assertEqual(response.status_code, HTTPStatus.FOUND) self.assertEqual(response["Location"], "/books/") If i have a second form with a 'prefix' how would i construct the data object of the request. Im thinking of: form_1_data = {foo} form_2_data = {bar} response = self.client.post("/books/add/", data={form_1_data, form_2_data) But it clearly does not work -
Trigger events in dropdowns using "Select2" library from Django Forms
I'm using the "select2" library to work with model-bound, related and dependent dropdowns and I want to handle various events like: change, click, blur and focus; however, only the change event is executed, but, when I use a regular dropdown, all four events work properly. How can I handle the dropdown events, noted above, in conjunction with the "select2" library? The idea is populate "Office" drop-down with previous selection of "Corporation" and "Division" drop-down, and those dropdowns obey the four events. dropdowns: coporation > division > office # forms.py class NewEmployeeForm(forms.ModelForm): class Meta: model = Employee fields = '__all__' widgets = { 'coporation': forms.Select( attrs={ 'class': 'form-control select2', 'style': 'width: 100%', }, ), 'division': forms.Select( attrs={ 'class': 'form-control select2', 'style': 'width: 100%', }, ), 'office': forms.Select( attrs={ 'class': 'form-control select2', 'style': 'width: 100%', }, ), # template.html <!-- form --> <form method="post" id="empleado_form" data_offices_url="{% url 'employees:ajax_get_offices' %}" novalidate> <fieldset> {% csrf_token %} <div class="col-sm-4 form-group {% if form.corporation.errors %}has-error{% endif %}"> {{ form.corporation.label }} {{ form.corporation }} <div class="text-danger"> {{ form.corporation.errors }} </div> </div> <div class="col-sm-4 form-group {% if form.division.errors %}has-error{% endif %}"> {{ form.division.label }} {{ form.division }} <div class="text-danger"> {{ form.division.errors }} </div> </div> ... </form> <script> $(function() … -
how to fix "can't compare offset-naive and offset-aware datetimes" in python
Here I'm using Django and comparing timing. But I'm unable to do that. In the following code. wts value which is time value coming as a string. If it comes in string type then first I convert that in regular time after that I subtract 5 hours from it. and then compare if it is less than current or not.. if not wts: raise ValueError('When to send(wts) require ') if type(wts) is str: wts_compare = parser.parse(wts) print("wts time type ->>>" ,type(wts_compare),wts_compare) wts = wts_compare - timedelta(hours=5) if wts_compare <= timezone.now(): raise ValueError('when to send (wts) must be a future date-time') else: wts = wts-timedelta(hours=5) if wts <= timezone.now(): raise ValueError('when to send (wts) must be a future date-time')