Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter by reverse lookup count of related field in django query
In my Django project, I have models for User, Player, and Game. A User can be a Player in any number of Games. There is a user statistics view (in this case, we are talking about finished games), that can be filtered and ordered by many different attributes. Example: each Game is played on a specific map. In the view, the map can be filtered; then, for each user, only the games are considered that were played on the filtered map. I want to do the same thing for number of players in the game; consider only the games played with e.g. 2 players in the statistics. There is no attribute players in the model Game; it's a reverse foreign key from model Player. To build the statistics per User: I start with User.objects.all() Create a player_filter containing the set parameters, e.g. player_filter = Q(player__game__map='O') Then apply annotations (e.g. users.annotate(high_score=Max('player__score', filter=player_filter)) Then display these values somehow in the view. However, to filter player from games with X number of players, I would need to do something like player_filter = Q(COUNT(player__game__player_set)=2) (not a working syntax of course). How can I do this? I kind of need to annotate the related player__game … -
Why the django signal receiver is not being executed?
I have the following code: signals.py: from django.dispatch import Signal, receiver new_device_signal = Signal() src/controller.py: from django.dispatch import receiver from domotic.signals import new_device_signal class Controller(MQTTClient): @receiver(new_device_signal) def handle_new_device_signal(self, sender, name, is_sensor, **kwargs): print('Añadiendo nuevo dispositivo: ' + name) if is_sensor == True: self.sensors.append(name) else: self.switches.append(name) def __init__(self, host, port): super().__init__(host, port, CONTROLLER_ID) self.rules = [] self.switches = [] self.sensors = [] #Lee todos los devices que hay registrados en la base de datos for device in Device.objects.all(): if device.is_sensor == True: self.sensors.append(device.name) else: self.switches.append(device.name) #Lee y procesa todas las normas que hay en la base de datos for rule in RuleText.objects.all(): self.rules.append(loadRule(rule.name)) new_device_signal.connect(self.handle_new_device_signal) views.py: from domotic.models import Device, RuleText from domotic.signals import new_device_signal class DeviceCreateView(CreateView): model = Device template_name = 'app/device/new.html' fields = ['uid', 'name', 'is_sensor'] success_url = reverse_lazy('app:devices') def form_valid(self, form): response = super().form_valid(form) new_device_signal.send(sender=self.__class__, name=self.object.name, is_sensor=self.object.is_sensor) return response apps.py: from django.apps import AppConfig class DomoticConfig(AppConfig): name = 'domotic' def ready(self): import domotic.signals settings.py: INSTALLED_APPS = [ "domotic.apps.DomoticConfig", 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', init.py: default_app_config = 'domotic.apps.DomoticConfig' I don't understand why even though the send in views.py is being executed the handler is not I tried to follow every post regarding this matter but i could not solve … -
Why clean_data works with or without self?
Why clean_data works with or without self ? Because I tested my project and whether I put a self or not, it doesn't change anything at all thks with def clean(self): cleaned_data = super().clean() quantity = self.cleaned_data.get("quantity") if quantity > self.instance.ticket.stock: raise forms.ValidationError(f"Il ne reste que {self.instance.ticket.stock} tickets en stock") return cleaned_data without def clean(self): cleaned_data = super().clean() quantity = cleaned_data.get("quantity") if quantity > self.instance.ticket.stock: raise forms.ValidationError(f"Il ne reste que {self.instance.ticket.stock} tickets en stock") return cleaned_data **Complete code : ** class OrderForm(forms.ModelForm): # je modifie le widget utilisé # modifier la qté dans le panier : quantity = forms.IntegerField(max_value=100, min_value=1) # supprimer un article du panier : delete = forms.BooleanField(initial=False, required=False, label='supprimer') class Meta: model = Order fields = ["quantity", 'delete'] def clean(self): cleaned_data = super().clean() quantity = self.cleaned_data.get("quantity") if quantity > self.instance.ticket.stock: raise forms.ValidationError(f"Il ne reste que {self.instance.ticket.stock} tickets en stock") return cleaned_data # relier le delete avec save def save(self, *args, **kwargs): # récupérer les données de mon formulaire : # avec cleaned_data qui est un dictionnaire, données de mon formulaire après qu'il ait été validé if self.cleaned_data['delete']: # if self.cleaned_data['delete'] is True: return self.instance.delete() return super().save(*args, **kwargs) I just know and understand why self is optionnal. thks -
Not able to send the comment to db and getting "IntegrityError at /add-comment NOT NULL constraint failed: core_comment.post_id"
models.py This was the model I created : class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) user = models.CharField(max_length=100) image = models.ImageField(upload_to='post_images') caption = models.TextField() created_at = models.DateTimeField(default=datetime.now) no_of_likes = models.IntegerField(default=0) def __str__(self): return self.user class Comment(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.post.user, self.name) views.py I am not able to create object at the backend. would be helpful if anyone knew how to call post and add it to the views. @login_required(login_url='signin') def add_comment(request): if request.method == 'POST': # import pdb # pdb.set_trace() user = request.user.username comment = request.POST['comment'] new_comment = Comment.objects.create(name=user, body=comment) new_comment.save() return redirect('/') else: return redirect('/') index.html : along with forms <!-- Comment section --> <form action="add-comment" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div> <!-- Comment section typing box --> <div class="bg-gray-100 bg-gray-100 rounded-full rounded-md relative "> <!-- <a href="/add-comment?post_id={{post.id}}"> --> <input type="text" placeholder="post a comment" class="bg-transparent max-h-10 shadow-none" name="comment" id="comment"> <div class="absolute bottom-0 flex h-full items-center right-0 right-3 text-xl space-x-2"> <button class="button bg-blue-700" type="submit">submit</button> </div> </div> </form> I am not able to bring the comment to the backend as I am new to django. comment section looks like this tracebackcall -
How to do type checking while using Django?
There are linters that support type checking, however they become a mess in a Django project. Is there any way to have type checking for where I define type hints, but not do it for all the Django bits and pieces? I'm using Conda and VS Code. -
In DRF's generics.UpdateAPIView perform_update, why are changes to the instance still reflected if those changes happen after the instance is saved?
I'm a little confused about why this code block is still updating the database correctly, despite us not saving the instance after the changes were made. In fact, the changes happened after the instance was saved. What gives? class ProductUpdateAPIView(generics.UpdateAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer lookup_fields = 'pk' def perform_update(self, serializer): instance = serializer.save() if not instance.content: instance.content = instance.title # why do we not save it here? This code was taken from https://youtu.be/c708Nf0cHrs?t=7030 and the author, unfortunately, did not expand upon it. Can someone explain it, please? Thank you in advance! -
I am unable to upload big file with NGINX, NGINX max upload has no effect
I'm learning Django, Docker and Nginx. For this, I am using nginx proxy but it is throwing 413 Request Entity Too Large when uploading images but the image size is not significant. I added client_max_body_size 1024M; in htttp, server and location in nginx.conf and default.conf but it did not solve my problem Do I need to do any thing to uwsgi? -
Internal Server Error: TypeError in Django Rest Framework viewset
I am building an API using Django Rest Framework for managing assignments. I have a viewset for Assignment model that allows to create new assignments via a POST request to /api/assignment/Assignment/. However, when I make the request, I get an "Internal Server Error" with the following traceback: Internal Server Error: /api/assignment/Assignment/ Traceback (most recent call last): File "D:\project\Assignments-Api\.venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "D:\project\Assignments-Api\.venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\project\Assignments-Api\.venv\Lib\site-packages\django\views\decorators\csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) File "D:\project\Assignments-Api\.venv\Lib\site-packages\rest_framework\viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "D:\project\Assignments-Api\.venv\Lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "D:\project\Assignments-Api\.venv\Lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "D:\project\Assignments-Api\.venv\Lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception return int(value) TypeError: int() argument must be a string, a bytes-like object or a real number, not 'DeferredAttribute' It seems that the error occurs in the views.py file of Django Rest Framework, but I cannot figure out the root cause of the issue. What could be causing this error and how can I resolve it? But Data saved in the model as expected. -
Django dataabse problem: (fields.E300) and (fields.E307)
Could you help me to fix this problem? I know i can't import abstract class into database, but i have no idea how to fix my code :) https://github.com/ichecinski/chess_guide i have an error: chess.Ruch.figura: (fields.E300) Field defines a relation with model 'Figura', which is either not installed, or is abstract. chess.Ruch.figura: (fields.E307) The field chess.Ruch.figura was declared with a lazy reference to 'chess.figura', but app 'chess' doesn't provide model 'figura'. your text I tried to delte abstract class or change the ForeignKey, but it didn't work for me. -
Read one side of the association
Let's say we have two models in our Django app: class Member(models.Model): name = models.CharField() class Project(models.Model): name = models.CharField() Normally, for a many to many field I would make an intermediary table and just query that: class ProjectMember(models.Model): project = models.ForeignKey(Project) member = models.ForeignKey(Member) Is there a way to retrieve a queryset to list only the projects for a member? I tried ProjectMember.objects.filter(member=member).only('project') but I still get the ProjectMember object list with only the project field populated. I was wishing to retrieve a list of Project objects. -
Unable to create a sqllite test database in django
I am building a laboratory management software right now as a passion project, and I am getting stuck trying to test the Django backend of my application. I am trying to create a test database to use with pytest. I am using MySQL on PlanetScale as the default database, but if I were to create a second database for testing, I would have to upgrade from the free version. If possible, I want to avoid this, so I'm trying to use a SQLite database for testing. I need to figure out how to run my pytests using a second sqlite database. To begin, I run pytest using my dockerfile FROM python:3.11-alpine ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN apk update \ && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add --no-cache mariadb-dev RUN pip install -r requirements.txt RUN apk del build-deps COPY . /code/ RUN pytest -v Once it starts running the pytests I receive an error, and all errors I receive from any test are the same. An example test would be @pytest.mark.django_db def test_create_user_serializer_save(valid_user_data): serializer = CreateUserSerializer(data=valid_user_data) assert serializer.is_valid() == True user = serializer.save() assert User.objects.filter(email=valid_user_data['email']).exists() == True assert user.name == valid_user_data['name'] … -
Using Django-simple-history with postgresql
So i was django simple history on my local server and using sqlite to test it out to see how I liked it. I decided to keep it for production, but I'm wondering if there is anything special needed to use simple history with postgress as that is what I am using for production. I migrated my changes with simple history over but it doesnt seem to want to show any kind of history for changes made. Is there something I need to do like save it? Reading documents online but I am not seeing much -
RegisterUserView creates user but doesn't log in user
I am trying to make a class-based registration view equivalent of my old function based registration view. When I register as a new user, a user is created but is not logged in after registration, and this bug only happens when I use class-based registration view. Form doesn't return any errors also. So views.py class-based (doesn't log in after registration) from django.contrib import messages from django.contrib.auth import login from django.urls import reverse_lazy from django.views.generic import CreateView from .forms import NewUserForm class RegisterUserView(CreateView): form_class = NewUserForm success_url = reverse_lazy('home') template_name = 'users/register.html' def form_valid(self, form): user = form.save() login(self.request, user) return super().form_valid(form) def form_invalid(self, form): messages.error(self.request, form.errors) return super().form_invalid(form) views.py function-based (does log in after registration) from django.contrib import messages from django.contrib.auth import login from django.shortcuts import redirect, render from .forms import NewUserForm def register_user(request): if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect('home') messages.error(request, form.errors) form = NewUserForm(request.POST) context = { "form": form } return render(request, "users/register.html", context) models.py from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): email = models.EmailField(unique=True) forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from .models import CustomUser class NewUserForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model … -
Paginating Django query results in a table
I am having issues with paginating my query results. When I use the query without pagination it works as intended, but once I add the pagination to the query I am seeing results on the last page that do not match what was defined in the search. For example, if I search a date like april 5th, 2023 I get 53 as my last page, after clicking on 53 to view the page 54 appears in the pagination as the last page. If you navigate to 54 it has items from later dates. Also I noticed if you navigate to a page in the query then try to navigate back to the first page the table then shows results from earlier dates. I have tried researching and fixing this but I am at a loss, any help would be greatly appreciated. models.py: class Package(models.Model): barcode = models.AutoField(primary_key=True) barcode_img = models.ImageField(upload_to='images/', null=True) origin = models.CharField('Origin Location', max_length=50, choices=[(location.locations, location.locations) for location in Location.objects.all()]) destination = models.CharField('Destination Location', max_length=50, choices=[(location.locations, location.locations) for location in Location.objects.all()]) description = models.CharField('Description', max_length=50) date_created = models.DateTimeField('Date Created', default=timezone.now) employee = models.ForeignKey(Employee, on_delete = models.CASCADE, default=320557) status = models.CharField('Status', default='Created', max_length=50) views.py: def search(request): form = SearchForm() … -
Django, Integrity error with PK, but new objects are still working fine
So here's my view def add_tutorial(request): if request.method == 'POST': User = request.POST.get('user') # other properties lang = request.POST.get('lang') new_tutorial = Tutorial.objects.create( User=User, ..., lang=lang) context = { 'page_title': 'create tutorial', } return render(request, "add-tutorial.html") I do create a tutorial with forms, it all works well, I can see the tutorial where it needs to be, but for some reason I get integrity error regarding the pk IntegrityError at /add_tutorial. UNIQUE constraint failed: main_tutorial.id The Id in the db is correct (i use sqlight). Before I used to specify the id in the create function, but now it shouldn't be any problem since I've dropped that db and (properly) undone all migrations; nothing changed [the only meaningful traceback that i get is to the Tutorial.objects.create(...) line] -
Return response not downloading through pandas Django
I want to export the query data if the form is valid after submitting two dates from a modal form. I don't understand why the return response is not working here. Any help would be appreciated. def load_date_range_ajax(request): data = dict() template_name ='date_range_modal.html' if request.method == 'POST' and request.is_ajax(): form = DateRangeForm(request.POST) if form.is_valid(): data['form_is_valid'] = True start_date = form.cleaned_data['start_date'] end_date = form.cleaned_data['end_date'] with connection.cursor() as cursor: cursor.execute('''qry_string;''') rows = cursor.fetchall() response = HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="Location Date.xlsx"' df = pd.DataFrame(rows, columns=[col[0] for col in cursor.description]) df.to_excel(response, index=False, header=True) return response else: data['form_is_valid'] = False else: form = DateRangeForm() data['html_form'] = render_to_string(template_name, context={'form': form}, request=request) return JsonResponse(data) -
Django "This field is required." error every time I fill out my video post form
As the title says, I'm getting this error and I'm not really sure why am I getting it. Here's my models.py for the video upload form: class Video(models.Model): title = models.CharField(max_length=100) thumbnail = models.ImageField(upload_to='videos/thumbnails/', null=True) video = models.FileField(upload_to='videos/video/', validators=[FileExtensionValidator(allowed_extensions=["mp4", "mov"])]) date = models.DateTimeField(auto_now=True) slug = models.SlugField(unique=True) user = models.OneToOneField(User, related_name='user',on_delete=models.PROTECT) description=models.TextField(validators=[MinLengthValidator(10)], blank=True) category= models.ForeignKey(Category, on_delete=models.CASCADE, blank=True) game = models.ForeignKey(Igdb, on_delete=models.PROTECT, null=True,blank=True) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Video, self).save(*args, **kwargs) def __str__(self): return self.title Here's my forms.py: class videoupload(forms.ModelForm): title = forms.CharField(max_length=100, widget= forms.TextInput (attrs={'placeholder':'Title'})) thumbnail = forms.ImageField() video = forms.FileField(widget= forms.FileInput (attrs={'class':'videobox'})) description = forms.Textarea() category = forms.Select() game = forms.Select() class Meta: model = Video fields = ['title', 'description', 'thumbnail', 'video','category', 'game'] exclude = ("date","user", "slug") And here's my views.py: def uploadpage(request): if request.method == "POST": form = videoupload(request.POST,request.FILES or None) if form.is_valid(): video = form.save(commit=False) video.user = request.user video.save() return redirect("home") else: form = videoupload() return render(request, "glavna/upload.html", {"form": form}) I'm trying to have it post a video, username would be automatically filled out. -
How to give AbstractUser permissions to a users' group?
I have user model inherited from AbstractUser called CustomAbstractUser. When I try to assign the permissions of this model to a user group, nothing is done. No trace of the assignment in the database. When I go through the administration interface, it works without problem. But programmatically not. content_type = ContentType.objects.get_for_model(CustomAbstractUser) add_user = Permission.objects.get( codename="add_customabstractuser", content_type=content_type ) change_user = Permission.objects.get( codename="change_customabstractuser", content_type=content_type ) ... admin, _ = Group.objects.get_or_create(name="AdminUser") ... admin.permissions.set([add_user, change_user, view_user]) By following this procedure with other models, it works without any problem. Also note that CustomAbstractUser is in a different application than the other models. -
What is the difference between save() and clean() method in django? Who is the first to be called when instantiating a model? [closed]
I want to make a blog in Django I have an Article table and a Blogger table I would like the number of blogger articles to be incremented with each record. However, it should not be incremented if it is an update. I tried to overload the clean() method but with each update the number of blogger articles also increases. I tell myself that if I understand how these two work I would know how to use them better that'is what i have tried from django.utils.text import slugify from django.conf import settings from django.db import models import uuid import datetime from django.shortcuts import reverse from user_cust.models import Blogger class Articles(models.Model): """Attributes list of my articles""" blogger = models.ForeignKey( Blogger, on_delete=models.CASCADE, primary_key=False, default="", verbose_name="Auteur:", editable=True, ) id = models.UUIDField( unique=True, primary_key=True, default=uuid.uuid4, ) title = models.CharField(max_length=200, verbose_name="Titre") slug = models.SlugField(default="", max_length=200, blank=True) body = models.TextField(blank=False, null=False, default="") created_at = models.DateTimeField(auto_now_add=True, verbose_name="Cree le:") update_at = models.DateTimeField(auto_now=True, verbose_name="Mis a jour le: ") image = models.ImageField(upload_to="article_images", blank=True) def __str__(self): return f"{self.title}" def save(self, *args, **kwargs): value = self.title self.slug = slugify(value=value, allow_unicode=True) if self.blogger.nb_articles == 0: self.blogger.nb_articles += 1 self.blogger.save() super().save(*args, **kwargs) def clean(self): """Try to avoid that an update action add a number … -
import all sections of the connected user's profile on LinkedIn using the LinkedIn API
I want to import all sections of the connected user's profile on LinkedIn using the LinkedIn API in Python. I used the REST API to retrieve profile information by sending a GET request to the URL: https://api.linkedin.com/v2/me, using the obtained access_token. However, I want to import the education and experience sections, and I am unsure of what to add to the URL to achieve this. What parameters do I need to add to the URL to retrieve the education and experience sections of the connected user's profile using the LinkedIn API in Python?" i tried this url " api_url = 'https://api.linkedin.com/v2/me?projection=(id,firstName,lastName,headline,profilePicture(displayImage~:playableStreams),educations,experience)' " but when i execute this url form : response = oauth.get(api_url) profile_data = response.json() the profile_data contain only the name , image profil and emailAdress . -
how we can connect two table in django model
**I am new to django i am working on a project where I have 4 usertype 1- super admin 2- sub admin 3 - clinic 4 - patient Now I want to make the login for all the 4 usertype** right now I have create a model like this import django from django.db import models from django.contrib.auth.models import AbstractUser class Registered_user(AbstractUser): is_clinic = models.BooleanField(default=False) is_patient = models.BooleanField(default=False) token = models.CharField(max_length=120, default=None, null= True) forgot_token = models.CharField(default=None, max_length=120, null=True), email = models.EmailField(unique = True, max_length=254, verbose_name='email address') updated = models.DateTimeField(auto_now=True) published = models.DateTimeField(default=django.utils.timezone.now) #clinic clnc_name = models.CharField(max_length=255) clnc_phone = models.BigIntegerField(null= True) clnc_contact_name = models.CharField(max_length=255) clnc_Job_Title = models.CharField(max_length=255) clnc_address_line1 = models.CharField(max_length=255) clnc_address_line2 = models.CharField(max_length=255) clnc_county = models.CharField(max_length=255) clnc_postcode = models.CharField(max_length=255) clnc_town_city = models.CharField(max_length=255) clnc_created_at = models.DateTimeField(auto_now_add=True) clnc_status = models.BooleanField(default=False) #Patient punique_number = models.CharField(max_length=20) pname= models.CharField(max_length=255) patient_adddress = models.TextField(max_length=500) pphone_number = models.IntegerField(null=True) phome_number = models.IntegerField(null=True) pwork_number = models.IntegerField(null=True) pdob = models.CharField(max_length=255,null=True) relative_name = models.CharField(max_length=255,null=True) relative_phone = models.CharField(max_length=255,null=True) relation = models.CharField(max_length=255,null=True) pgender = models.CharField(max_length=20) pcreated_at = models.DateTimeField(auto_now_add=True) ptnt_status = models.BooleanField(default=False) **I want them to be seperated I know this is not the right way to do this I also tried to use the foreign key but i got null value error Please let me … -
dj-rest-auth/registration return http 204 no content
I were following the book Django for APIs by William.S.Vincent. In Chapter 8: User Authentication, I make Implementing token authentication and use dj-rest-auth and django-allauth to make registration. In the book after register the http return 201 created, it created new account and return API auth key token, save that in db. With my it return http 204 no content( not return API auth key token ), it still created a new account but don't create key token for account. My url.py urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include("posts.urls")), # v1 for api version 1. (Name for each api route) path('api-auth/', include('rest_framework.urls')), # build-in log in/out rest path("api/v1/dj-rest-auth/", include("dj_rest_auth.urls")), #url for dj_rest_auth path("api/v1/dj-rest-auth/registration/", include("dj_rest_auth.registration.urls")), ] My settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', #3party "rest_framework", "corsheaders", "rest_framework.authtoken", "allauth", "allauth.account", "allauth.socialaccount", "dj_rest_auth", "dj_rest_auth.registration", #local 'accounts.apps.AccountsConfig', 'posts.apps.PostsConfig',] REST_FRAMEWORK = { # new "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.IsAuthenticated", ], "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.SessionAuthentication", "rest_framework.authentication.TokenAuthentication", ],} I compared with github files both author and found no difference. github:https://github.com/wsvincent/restapiswithdjango/tree/master/ch8-blog-user-auth Has there been any change to the version? Thank for you time. -
WeasyPrint server error 500 on render.com
im having a 'server error 500' in my project when i tried to use Weasyprint (im not having any error when i use local host), I deploy my project on render.com it's a django app with postrgres. here is the code: html_template = get_template('printinfo.html') html_string = html_template.render({'person': passanger}) html_string = html_template.render(context) pdf_file = HTML(string=html_string).write_pdf() response = HttpResponse(pdf_file, content_type='application/pdf') response['Content-Disposition'] = f'filename="{passanger.passanger.name} Reservation.pdf"' return response Im thinking its an enviroment error but i installed my requirements.txt in render.com which has weasyprint on it. I tried to find a way to install gtk or pango in render.com but i couldnt find the way... -
Django not identifying User custom model
Error: django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'users.User' that has not been installed settings.py INSTALLED_APPS = [ ... 'apps.users', ... ] AUTH_USER_MODEL='users.User' Resolver o erro. Sem mudar o nome do app no INSTALLED_APPS -
How to annotate a Django queryset with a boolean value for "is older than n days"?
Given the toy example of a model: class Article(models.Model): title = models.CharField(max_length=64) published = models.DateTimeField() How might you get a queryset such that you can tell whether the article was published over 2 years ago? I was thinking something like this, but it didn't pan out: Article.objects.all().annotate( is_relevant=ExpressionWrapper( timezone.now() - F("start") > timedelta(days=365 * 2), output_field=BooleanField(), ) ) Basically, I want to be able to iterate over the list of articles and access article.is_relevant in the template to decide how I might render it.