Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not able to display image uploaded using django
I was able to upload image using views and templates in django but was not able to display those images. I could only display images stored in static folder but not from the media folder or any other location. I have done all the steps mentioned in docs and in other solution but this is not working for me. I created a model which looks like class Product(models.Model): image = models.ImageField(upload_to='product_images/') description = models.TextField(null=True) quantity = models.IntegerField(null=True) and my forms.py is class ProductForm(forms.ModelForm): class Meta: model = Product fields = ['image', 'description', 'quantity'] my views.py is like this @login_required def display_products(request): products = Product.objects.all() return render(request, 'farmer/display_products.html', {'products': products}) @login_required def upload(request): if request.method == "GET": form = ProductForm() if request.method == 'POST': form = ProductForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('display_products') return render(request, 'farmer/my_products.html', {'form': form}) my file is like this {% load static %} {% for product in products %} <div class=""> <h2>{{ product.name }}</h2> {{product.image.url}} image: <img src="static/dry.jpeg" alt="sample"> <p>description: {{ product.description }} quantity: {{ product.quantity }} </p> </div> settings.py STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR / 'static/css', ] LOGIN_URL = 'login' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') DEBUG = True urls.py if settings.DEBUG: urlpatterns … -
loops in Django template
on my template, i have 3 pictures from products in my database i'm trying to loop through. the goal is to display in one div, the pictures of products that are marked available, and in another div, pictures of products that are not marked available. using the code below does not show any items that do not have the same availability as product1. but it shows the pictures of product1 in its appropriate div, as i switch it's availability. i don't know why this is happening, please help. ''' my model looks like class Product(ModelMeta, models.Model): user = models.ForeignKey(User, default=1, null=True,on_delete=models.SET_NULL) title = models.CharField(max_length=120) available = models.BooleanField(default=True) class SiteImage(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE,null=True) object_id = models.PositiveIntegerField(null=True) content_object = GenericForeignKey('content_type', 'object_id') image = models.ImageField(upload_to='image/', blank=True, null=True) caption = models.CharField(max_length=50, blank=True) my view looks like def home_page(request): pictures = SiteImage.objects.filter(content_type__model='product') testimonials = Testimonials.objects.all() context = {'pictures': pictures,} return render(request, 'home.html', context) my template looks like {% for picture in pictures %} {% if picture.content_object.available %} {{ picture.product.title }} {{ picture.caption }} {% endif %} {% endfor %} {% for picture in pictures %} {% if not picture.content_object.available %} {{ picture.product.title }} {{ picture.caption }} {% endif %} {% endfor %} ''' -
Django annotate method with when clouse using query key as a Value
I need to add ordering_datetime column when field=field matches. And for a Value I want to get it from "date_time_value" field. queryset = queryset.annotate( ordering_datetime=Case( When( field=field, then=Value("date_time_value") ), output_field=DateTimeField(), ) ).order_by("pk", f"{order_lookup}ordering_datetime").distinct("pk") how to get value from column that matches field=field rows. when I tried to give the column name directly as a value doesn't work. It expects a static value, not a query key -
Angular CLI Proxy + Django Backend not working with Docker
I have an Angular + Django project where I am providing an api to angular with django. When I run the two services separately everything works as expected. When I run both services together using docker compose, angular is suddenly unable to connect to the backend api service. I have seen a similar post on stack but the difference is I am using a single compose file to include two different compose files so I'm not sure how to "link" the backend services to the frontend service like the answers suggest in this post. So what can I do to make this work within docker? Error: [webpack-dev-server] [HPM] Error occurred while proxying request localhost:4200/api/project_types/ to http://api:8000/ [ENOTFOUND] (https://nodejs.org/api/errors.html#errors_common_system_errors) Project Layout: Note: I've dockerized the two services and am using one compose file in the root folder to include both the backend and frontend compose files. - root - backend - backend-compose.yml - frontend - frontend-compose.yml - docker-compose.yml Root Compose: version: '3.7' include: - ./frontend/compose.yml - ./backend/local.yml Frontend Compose: services: web: build: context: . target: builder ports: - 4200:4200 volumes: - ./angular:/app - /project/node_modules Backend Compose: (Note: built with cookiecutter django) version: '3' volumes: backend_local_postgres_data: {} backend_local_postgres_data_backups: {} services: django: build: … -
pytest-django : Invalid choice in client.post
If I print theme_1 in the begining or at the end of the test i get the theme_1 object. But theme_1 in client.post is... None ! I don't understand.. :s Can you help me ? Thank you :) @pytest.fixture def theme_1(db): return Theme.objects.create(name="dev") @pytest.mark.django_db def test_create_forum_view_post(client: Client, theme_1, user_1): client.login(username=user_1.username, password="12345678") response = client.post(reverse("forum:create-forum"), data={"name": "devforum", "theme": theme_1, "description": "Forum des devs"}) form = response.context["form"] print(form.errors) print(response) -
Choosing between Polymorphic Associations and Separate Tables
I'm working on a Django project where I need to manage generic attachments across different entities in my system. Currently, I'm using a polymorphic model as follows: class AttachmentGenericModel(BaseModel): content_type = models.ForeignKey(ContentType, on_delete=models.SET_NULL, null=True, blank=True) object_id = models.UUIDField(null=True, blank=True) content_object = GenericForeignKey('content_type', 'object_id') file = models.FileField(upload_to=upload_to_path) class ProblemStatement(BaseModel): context = models.TextField() files = GenericRelation(AttachmentGenericModel) class Proposal(BaseModel): files = GenericRelation(AttachmentGenericModel) However, I'm wondering if it's preferable to use separate tables for each entity, like ProposalFile, ProblemStatementFile, etc. My concern is that the main table AttachmentGenericModel may become complex over time as the number of entities involved grows. I'm curious if anyone has experiences or advice on which approach is more advantageous in terms of performance, maintainability, and scalability. Additionally, what considerations should be taken into account when deciding between polymorphic associations and separate tables for handling generic attachments in Django? As an illustrative example, here's an example with separate tables: class ProblemStatementFile(BaseModel): problem_statement = models.ForeignKey(ProblemStatement, on_delete=models.CASCADE) file = models.FileField(upload_to=upload_to_path) class ProposalFile(BaseModel): proposal = models.ForeignKey(Proposal, on_delete=models.CASCADE) file = models.FileField(upload_to=upload_to_path) What are the pros and cons of each approach, particularly in a future scenario where numerous new tables with file relationships may be needed? Thank you in advance for your valuable insights! -
Making a Highest Rated Albums List Based on Ratings Averages from Two Models
I have an Album model (shortened for space): class Album(models.Model): creator = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) artist = models.CharField(max_length=255) title = models.CharField(max_length=255) rating = models.IntegerField( choices=[(i, i) for i in range(1, 11)], validators=[MaxValueValidator(10), MinValueValidator(1)], default=10, ) comment = models.TextField(null=True, blank=True) And a Review model (again, shortened for space): class Review(models.Model): reviewer = models.ForeignKey(User, on_delete=models.CASCADE, null=True) album = models.ForeignKey(Album, on_delete=models.CASCADE) rating = models.IntegerField( choices=[(i, i) for i in range(1, 11)], validators=[MaxValueValidator(10), MinValueValidator(1)], default=10, ) comment = models.TextField() The Album model is for users to create an Album and add their initial review and rating. The Review model is for users to be able to add a review to an existing album, and also a rating. I have this model method attached to the Album in order to create an average rating to display in templates: def avg_rating(self): review_ratings = 0 orig_rating = self.rating review_ratings_count = self.review_set.count() if review_ratings_count > 0: for review in self.review_set.all(): review_ratings += review.rating ratings_sum = review_ratings + orig_rating ratings_count = review_ratings_count + 1 ratings_avg = ratings_sum / ratings_count avg_return = round(ratings_avg, 1) if avg_return == 10.0: avg_return = 10 else: avg_return = avg_return return avg_return else: return self.rating Sadly, avg_rating cannot be used (to my knowledge) in … -
raise ValueError, "No frame marked with %s." % fname. SyntaxError: invalid syntax at import environ in settings.py file
When building a docker container with the --platform=linux/amd64 python:3.9 image, I encounter an error: Traceback (most recent call last): File "/var/www/myapp/manage.py", line 22, in <module> main() File "/var/www/myapp/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 345, in execute settings.INSTALLED_APPS File "/usr/local/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/usr/local/lib/python3.9/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python3.9/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/var/www/newapp/myapp/settings.py", line 2, in <module> import environ File "/usr/local/lib/python3.9/site-packages/environ.py", line 114 raise ValueError, "No frame marked with %s." % fname ^ SyntaxError: invalid syntax I tried the recommended change to python3 -m pip install requirements.txt/pip3 install requirements.txt in the Dockerfile but nothing worked. The build of my container still exited with an error. What I realised is that the django-environ package as included in the requirements.txt file was either not installed or the absence of … -
Not able to retrive data from database in Django
I'm new to django. I am trying to obtain data from a profile page that I've created which exists in a app called users and I am trying to use the data in a HTML file called home that exists in an app called blog within in a templates directory within a blog directory This is how my users\model.py file looks like class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) image = models.ImageField(default='default.jpg', upload_to="profile_pics") height = models.PositiveIntegerField( null=True, blank=True) weight = models.PositiveIntegerField( null=True, blank=True) age = models.PositiveIntegerField( null=True, blank=True) def __str__(self): return f'{self.user.username} Profile' def save(self,*args,**kwargs): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width >300: output_size = (300,300) img.thumbnail(output_size) img.save(self.image.path) This is how my users\views.py file looks like def profile(request): u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated successfully!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) profile_instance = request.user.profile context = { 'u_form': u_form, 'p_form': p_form, 'height': profile_instance.height, 'weight': profile_instance.weight, 'age': profile_instance.age, } return render(request,'users/profile.html',context) Just to be sure that my Profile Page works, I checked the admin page, and it shows the data in the profile section. This is how my blog\views.py … -
Media Exposure Vulnerability
Currently, we have a configuration in Django to serve media files (these are the files uploaded by users in the system). We have a URL for this where we capture all the files in the media directory and redirect them to the serve_media view. re_path(r"^media/(?P<path>.*)$", cms.views.serve_media), This is the serve_media view: def serve_media(request, path=""): if request.user.is_authenticated: user = request.user else: return redirect("/%s?next=%s" % (settings.LOGIN_URL, "/media/" + path)) usuario = Usuario.objects.get(usuario=user) # Search for the file by its path in the media folder and check if the user # has permission to access it allowed_to_serve = False try: arquivo = Arquivo.objects.get(arquivo__contains=path) # Public image of a project on the website for projeto in Projeto.objects.exclude(id_imagem_publica=None): if projeto.arquivo_in_id_imagem_publica(arquivo.id) is True: allowed_to_serve = True break if user == arquivo.criado_por or usuario.permissao == Usuario.SUPER: allowed_to_serve = True # Entidade file if arquivo.entidade is not None and allowed_to_serve is False: if ( usuario.permissao == Usuario.ENTIDADE and user == arquivo.entidade.usuario.usuario ): allowed_to_serve = True elif ( usuario.permissao == Usuario.AGENCIA and arquivo.entidade.projeto_set.all() .filter(cidade_atuacao=usuario.cidade_atuacao) .count() > 0 ): allowed_to_serve = True # Projeto file if arquivo.projeto is not None and allowed_to_serve is False: if ( usuario.permissao == Usuario.ENTIDADE and user == arquivo.projeto.entidade.usuario.usuario ): allowed_to_serve = True elif ( usuario.permissao … -
VS Code (Python) uses wrong version of Python interpreter even after activation virtual env (Poetry)
I have two Python interpreters on my machine (3.11.6 and 3.12). My project runs with Poetry venv (3.11.6). Whenever I open a project the status bar indicates correct venv like 3.11.6("project-fd1143fd-py3.11":Poetry). When I run a project (Django) I get an import error says there is no Django package installed. I suspect there is no actual activation of venv. When I enter command python --version I always get Python 3.12.0 (tags/v3.12.0:0fb18b0, Oct 2 2023, 13:03:39) There is no any indication of activated venv near the command line (do it has to be there as I remember). The Poetry venv itself works fine as I use it in PyCharm without any issues. -
Django Auth Query
I have a django backend project for e-commerce site where I have created authentication class which is used by all the view classes for incoming requests. In one of the classes I have get_queryset, put and post functions overridden. I want the authentication class to be applied for both put and post functions but not to get_queryset. following are the code snippets, Authentication Class class JWTAuthentication(BaseAuthentication): def authenticate(self, request): print('authenticating') auth = get_authorization_header(request).split() print(auth) if auth and len(auth) == 2: token = auth[1].decode('utf-8') print('Decoded Token') print(token) id = decode_access_token(token) print(id) print(id) customer = models.Customer.objects.get(id=id) return (customer, None) raise exceptions.AuthenticationFailed('unauthenticated2') Product View class class ProductList(generics.ListCreateAPIView): ... authentication_classes = [ JWTAuthentication ] ... def get_queryset(self): ... def post(self, request): ... def put... Is there a way just to apply the authentication on put and post function but not on get_queryset function? -
Authentication logout
error screenguys i have a big problem. Now im working for tweet website with python django. Authentication steps are good runnig but logout is dont working please help me guys.... my base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script> <title>Tweet App</title> <link rel="stylesheet" href="{% static 'tweetapp/customform.css' %}"> </head> <body> <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="{% url 'tweetapp:listtweet' %}">Tweet App</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav me-auto mb-2 mb-md-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="{% url 'tweetapp:listtweet' %}">List</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'tweetapp:addtweet' %}">Add Tweet</a> </li> <!-- <li class="nav-item"> <a class="nav-link" href="{% url 'tweetapp:addtweetbyform' %}">Add Tweet By Form</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'tweetapp:addtweetbymodelform' %}">Add Tweet By Model Form</a> </li> --> <li class="nav-item"> <a class="nav-link" href="{% url 'login' %}">Login</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'logout' %}?next=/">Logout</a> </li> </ul> </div> </div> </nav> {%block content%} {%endblock%} </body> </html> my urls.py """ URL configuration for djangotweet project. The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/5.0/topics/http/urls/ Examples: Function … -
"invalid_client" Error in Django OAuth Toolkit Despite Following Documentation
I'm encountering an "invalid_client" error when attempting to obtain an OAuth token using Django OAuth Toolkit. I've been meticulously following the official documentation (https://django-oauth-toolkit.readthedocs.io/en/latest/rest-framework/getting_started.html#step-4-get-your-token-and-use-your-api) but am unable to resolve the issue. Error Details: Error Response: {"error": "invalid_client"} Server Log: Unauthorized: /o/token/ [11/Jan/2024 20:13:37] "POST /o/token/ HTTP/1.1" 401 27 Steps Taken: Repeated Documentation Steps: I've carefully followed the documentation's instructions from scratch multiple times. Verified Credentials: I've double-checked the client ID, client secret, username, and password for accuracy and typos. Inspected Request Details: I've examined the cURL command and request details to ensure they align with the server's expectations. Specific Context: OAuth Server/Library: Django OAuth Toolkit Relevant Code Snippet: Bash curl -X POST -d "grant_type=password&username=<user_name>&password=<password>" -u"<client_id>:<client_secret>" http://localhost:8000/o/token/ Request for Assistance: I'm kindly seeking guidance on potential causes and troubleshooting steps. Specific Questions: Common Pitfalls: Are there any common mistakes or configuration issues that might lead to this error in Django OAuth Toolkit? Troubleshooting Suggestions: What additional diagnostic steps can I take to pinpoint the root cause? Server-Side Considerations: Are there any server-side settings or logs I should examine? Any insights or assistance would be greatly appreciated. -
IntegrityError FOREIGN KEY constraint failed
I am trying to add a new "Eveniment" through the admin page in my app, but I get the error from the title and I don't know how to solve the issue. Only and "Utilizator" who has the "Organizator" role should be able to add one. class Utilizator(AbstractUser): ORGANIZATOR=1 CUMPARATOR=2 data_inregistrare = models.DateTimeField(auto_now_add=True) ROLE_CHOICES =( (ORGANIZATOR, 'Organizator'), (CUMPARATOR, 'Cumparator'), ) role=models.PositiveSmallIntegerField(choices=ROLE_CHOICES,blank=True,null=True) evenimente=models.ManyToManyField(to='Eveniment', blank=True) groups = models.ManyToManyField( 'auth.Group', related_name='utilizatori', verbose_name='groups', blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_query_name='user', ) user_permissions = models.ManyToManyField( 'auth.Permission', related_name='utilizatori', verbose_name='user permissions', blank=True, help_text='Specific permissions for this user.', related_query_name='user', ) def to_dict(self): return{ 'id': self.id, 'data_inregistrare': self.data_inregistrare, 'role': self.role, } class Eveniment(models.Model): nume = models.CharField(max_length=255) data = models.DateField() locatie = models.CharField(max_length=255) descriere = models.TextField() organizator = models.ForeignKey(Utilizator, on_delete=models.CASCADE, related_name='evenimente_organizate', null=True) def __str__(self): return self.nume def to_dict(self): organizator_id = self.organizator.id if self.organizator else None return{ 'id': self.id, 'nume': self.nume, 'data': self.data, 'locatie': self.locatie, 'descriere': self.descriere, 'organizator': self.organizator.id, } For now, I am just trying to add a new "Eveniment" through the admin page, but the error keeps showing up no matter the changes I've made. -
django sender to django receiver api data exchange
I have built two web applications, django_one and django_two. I would like django_one to send data (From a web form) to django_two via RESTful_framework api any other method. Please guide me on how to go about this. -
The database needs something to populate existing rows...but the table doesn't exist yet and there are no rows
I'm getting this running python3 manage.py makemigrations You are trying to add the field 'created_at' with 'auto_now_add=True' to sitemetadata without a default; the database needs something to populate existing rows. But the table doesn't exist yet, and there are no rows. How can I use makemigrations here properly? -
Hello, I wrote the program so that the user enters the form, then it is authenticated, then it is logged in, but it says failure. Can you guide me?
class Register(View): def get(self, request: HttpRequest): register_form = RegisterForm() context = {'register_forms': register_form} return render(request, "register.html", context) def post(self, request: HttpRequest): register_form = RegisterForm(request.POST) if register_form.is_valid(): email = register_form.cleaned_data['email'] username = register_form.cleaned_data['username'] if RegisterModel.objects.filter(email__iexact=email).first(): messages.error(request, "The email has already been found") elif RegisterModel.objects.filter(username__iexact=username).first(): messages.error(request, "The username has already been found") else: # new_user = register_form.save(commit=False) # new_user.is_active = get_random_string(72) register_form.save() print("", tag="success", tag_color="green", color="yellow") # Authentication the user username = register_form.cleaned_data['username'] password = register_form.cleaned_data['password'] user = authenticate(username=username, password=password) if user: login(request, user) time.sleep(2) messages.success(request, "Successfully registered and logged in!") print(register_form.cleaned_data, tag="success",tag_color="green", color="yellow") else: messages.error(request, "Invalid username or password. Please try again.") context = {'register_forms': register_form} return render(request, "register.html", context) Authenticate successfully -
Django not writing to database but print statements are working and updated
I am using Django as my Web framework. The relevant function is def addWeight(request): if request.method == "GET": form = weightForm() return render(request, "base/weight.html", {"form": form}) if request.method == "POST": try: form = weightForm(request.POST) if not form.is_valid(): return HttpResponseBadRequest("Error with your form") data = form.cleaned_data day = macro_day.objects.get_or_create(owner=request.user, date=data["date"]) print(data["weight"]) day[0].weight = data["weight"] print(day[0]) print(day[0].weight) return HttpResponse(status=204)` <form action="weight" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="SUBMIT"> </form> The form object is: class weightForm(forms.Form): date = forms.DateField(label="Date") weight = forms.IntegerField(label="Weight", min_value=0, max_value=500) day[0].weight reflects the value sent into the function by the webform but when I actually go into my database or call the object it appears that the change hasn't been made. I have another function implemented like this and I don't seem to have the same issue with it. What am I doing wrong? -
Django: While Button Pressed
I am currently working on a control for a camera (visca-over-ip) having 4 buttons that control in which direction the camera should turn. Currently I am in the testing phase and now need these 4 Buttons to set a variable in django to TRUE if the Button is held. If it was let go something else should happen. It should be something Like: index.html: <button>Left</button> camera.py button_pressed = (Code that checks if button is held down) def button_hold(): while button_pressed == True: (do something) -
Deploying django project on a 2019 windows server virtual machine (offline)
I've been working on a Django project for a while, and after completing it, I want to deploy it so my colleagues can work with it. I have a virtual machine (Windows Server 2019) that doesn't have internet connection. I copied my Django project there, but the first problem I faced was with the Python packages. Since my project has its own virtual environment, I assumed that by copying the project, everything would work. However, I had to reinstall all the packages offline using the wheel files. This has made me question the purpose of the virtual environment. I also intend to deploy it using an Apache server. When deploying a Django project with Apache, I need the mod_wsgi package. However, when I tried installing it, I encountered this error, even though I have already installed Visual Studio C++ Build Tools 14 : building 'mod_wsgi.server.mod_wsgi' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for mod_wsgi Running setup.py clean for mod_wsgi Failed to build mod_wsgi ERROR: Could not build … -
Django - Downloading a file to local downloads folder
In Django, I am trying to download an entire album into local "downloads" default folder on the client's PC. but how do I specify the target folder? currently, my code doesn't nothing. from views.py: def download_file(lfile): uploaded_file = lfile response = HttpResponse(uploaded_file.image, content_type='application/force-download') response['Content-Disposition'] = f'attachment; filename="{lfile.fname}"' return response def download_album(request, albumpk, albumowner): album = Category.objects.filter(id=albumpk) lfiles = Photo.objects.filter(category=albumpk) for lfile in lfiles: dfile = download_file(lfile) return redirect('albumlist', albumowner) -
Subtract two date fields using computed twig in Drupal 10
Would be grateful for some assistance on this. I am building a webform using the webforms module in Drupal 10 and I want to subtract two date fields and as a result display the difference between the dates. For example, {{ 2024-01-11 - 2024-01-10 }} = {TheDifferenceInDays}. Thanks I have tried using the following expression in my computed twig field however this is returning a value of 0 - is that because the date fields need to be in a specific format? {{ date1 - date2 }} -
Pagination does not work when i use generil.ListView class in Django
I want to create pagination in Django for order list. It seems everything is coded correctly but for some reason when i get to webpage, instead of links to other pages it shows 'Page of . ' Apologies for formatting of this post as it's my first time posting a question and note that there are 7 objects of order, therefore there should be a page. My code looks like this: models.py class Order(models.Model): date = models.DateField('Date', null=True, blank=True) car = models.ForeignKey(Car, on_delete=models.SET_NULL, null=True) ORDER_STATUS = ( ('p', 'Processing'), ('o', 'Ordered'), ('s', 'In service'), ('c', 'Completed'), ('t', 'Taken back by customer') ) status = models.CharField(max_length=1, choices=ORDER_STATUS, blank=True, default='p') @property def order_total_price(self): order_rows = self.order_row.all() total_price = sum(row.total_price for row in order_rows) return round(total_price) @property def order_rows(self): return ', '.join(str(el) for el in self.order_row.all()) def __str__(self): return f'{self.car}' views.py class OrderListView(generic.ListView): model = Order context_object_name = "orders" template_name = "orders.html" paginate_by = 5 urls.py from django.urls import path, include from . import views urlpatterns = [ path('index/', views.index, name="index"), path('cars/', views.cars, name='cars'), path('car/<int:pk>/', views.car_detail, name='car_detail'), path('orders/', views.OrderListView.as_view(), name='orders'), path('order/<int:order_id>/', views.order_detail, name='order_detail'), path('search/', views.search_results, name='search_results'), path('', views.index, name='index'), ] and orders.html {% extends 'base.html' %} {% block header %}Orders{% endblock %} {% … -
Random Not Found</h1><p>The requested resource was not found on this server.</p>
I'm experiencing an issue which seems to be related somehow to Gunicorn + Django and I can't find the cause of the problem. I start Gunicorn using this command: gunicorn config.wsgi --bind=0.0.0.0:5000 --timeout=300 --workers=2 --threads=4 --worker-class=gthread --name=api --log-level debug --error-logfile gunicorn_error.log --access-logfile - --capture-output and then while trying to curl for example CSS file : curl http://0.0.0.0:5000/STATIC_DIR/CSS/FILE.css?v23423424 sometimes I get the correct response and CSS file but sometimes: <h1>Not Found</h1><p>The requested resource was not found on this server.</p> interestingly, if, for example, I kill 2 of the 3 gunicorn processes, they will start again in a moment and then everything will work properly. I can't find anything in the logs which can indicate the reason. Has anyone encountered a similar problem? enable DEBUG log try different types of worker-class