Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
failed to connect with Postgres container in Django
django.db.utils.OperationalError: connection to server at "db" (172.18.0.2), port 5432 failed: FATAL: the database system is starting up I have an issue connecting to the Postgres contaner. I was trying in different ways like setting passwords only in the docker-compose file. Still am stuck. docker-compose.yml version: '3' services: db: image: postgres:alpine environment: - POSTGRES_PASSWORD=password - POSTGRES_USER=user - POSTGRES_DB=userdb volumes: - django_db:/var/lib/postgresql/data container_name: db singup: build: . command: python manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 container_name: singup depends_on: - db volumes: django_db: database setting DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'userdb', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'db', } } -
Why i'm unable to autherize in my django app?
i'm testing my api. if the user is authenticated then he can able to see the projects otherwise return not authorizated response. I'm passing my jwt token in header but still unable to autherize...? class ListProjectAPIView(generics.ListAPIView): """This endpoint list all of the available Projects from the database""" permission_classes = [IsAuthenticated,] queryset = Project.objects.get_all() serializer_class = serializers.ProjectSerializer -
django forms non_field_errors customizing
I want to have my own errors in django forms but I cant . as you can see I define my own error_messages but django is still using Its own errors. app account / forms.py: from django import forms error_messages_email = { 'required': 'please Fill-out this field', 'invalid': 'invalid format for email', 'max_length': 'max length is 40 chars', } error_messages = { 'required': 'please Fill-out this field', 'invalid': 'fields format is not valid', 'max_length': 'max_length is 30 chars', 'min_length': 'password should be at least 8 Chars', } class LoginForm(forms.Form): username = forms.CharField(error_messages=error_messages, max_length=30, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Username'})) password = forms.CharField(error_messages=error_messages, min_length=8, max_length=30, widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password'})) class SignupForm(forms.Form): username = forms.CharField(error_messages=error_messages, max_length=30, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Username'})) email = forms.EmailField(error_messages=error_messages_email, max_length=40, widget=forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'Email'})) password = forms.CharField(error_messages=error_messages, min_length=8, max_length=30, widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password'})) and this is my apps template / signup.html: {% extends 'main.html' %} {% block title %} Join {% endblock %} {% block content %} <form action="" method="post"> {% csrf_token %} {{ form.non_field_errors }} {{ form.username.errors }} <label for="{{ form.username.id_for_label }}">Username:</label> {{ form.username }}<br> {{ form.email.errors }} <label for="{{ form.email.id_for_label }}">E-mail:</label> {{ form.email }}<br> {{ form.password.errors }} <label for="{{ form.password.id_for_label }}">Password:</label> {{ form.password }}<br> <input type="submit" value="signup" class="btn … -
VueJS 3 / Django : Uncaught TypeError: Failed to resolve module specifier "@revolist/vue3-datagrid". Relative references must start with either "/"
I use Django 4.0 and a Vue JS 3 on an app where I need a Vue Module called @revolist/vue3-datagrid. On the documentation, this is how I'm supposed to call it into my template file (doc here). <template> <div id="app"> <v-grid theme="compact" :source="rows" :columns="columns" ></v-grid> </div> </template> <script> import VGrid from "@revolist/vue3-datagrid"; export default { name: "App", data() { return { columns: [{ prop: "name" }, { prop: "details" }], rows: [{ name: "1", details: "Item 1", }] }; }, components: { VGrid, }, }; </script> When I copy pasted it into my template file on my Django App, I've got this error : Uncaught TypeError: Failed to resolve module specifier "@revolist/vue3-datagrid". Relative references must start with either "/", "./", or "../". After some searches, I've found that adding could help. It didn't work for me. I guess that the documentation is written for Node.JS or pure Vue JS 3 apps, not Django-like ones. I think that Vue is not able to find "@revolist/vue3-datagrid", since my node_modules files is in /static/node_modules/@revolist/vue3-datagrid directory. So, I tried to call the import that way : import VGrid from "/static/node_modules/@revolist/vue3-datagrid/dist/vgrid.js"; But I've got this error : Uncaught SyntaxError: The requested module '/static/node_modules/@revolist/vue3-datagrid/dist/vgrid.js' does not … -
How to use single nested serializer's data in more than one variable of parent serializer with single db call in DRF?
How can I get or store data of EmployeeSerializer somewhere so that I can use it again for getting active members count instead of making a new database call for getting count of active members? class ProjectSerailizer(serializers.ModelSerializer): members = EmployeeSerializer(many=True)#returns all members of a project active_members_count = serializers.SerializerMethodField()# get count of members which are having status active class Meta: model = Project fields = ('id','name','members','active_members_count') def get_active_members_count(self,obj): #How can I omit this extra db call? as i am already having data in members variable from EmployeeSerializer, can i loop over members variable somehow and count the active ones? count = obj.members.filter(status='Active').count() return count -
Django model form data not being save in the database
I'm new to programming and django. The model form data is not being save in the database I can't figure out why. I've tried different ways to validate the form but it just doesn't work. Here's my views.py: @login_required(login_url ='/seller/login') @seller() def addProductsView(request): pform = ProductForm(request.POST or None, request.FILES or None) if pform.is_valid(): pform.save() else: messages.warning(request, 'Oops! Something went wrong') return render(request, 'Shop/product-form.html', {'pform':pform}) And this is my models.py: class Products(models.Model): seller = models.ForeignKey(SellerProfile, on_delete = models.CASCADE) title = models.CharField(max_length = 255) product_category = models.CharField(choices = CATEGORY_CHOICES, max_length = 100, default = 'eBooks') description = models.TextField() price = models.FloatField(max_length= 5) discounted_price = models.FloatField(max_length= 5, default = 0.00) thumbnail = models.ImageField(upload_to = 'media/thumbnail/',null=True) files = models.FileField(upload_to = 'media/product_files/', null = True) slug = models.SlugField(max_length = 255, unique = True, null = True, blank = True) is_featured = models.BooleanField(default = False) is_published = models.BooleanField(default = True) And this is the forms.py: class ProductForm(ModelForm): class Meta: model = Products fields = ['title', 'product_category', 'description', 'price', 'discounted_price', 'thumbnail', 'files'] Any help will be really helpful. Thank You -
How to structure django quries while using function based views
I am creating an app where I have to query a lot. Also, I am using function-based views the issue is when I query something in views.py. The code gets very messy and feels like If some person who will come after me to add something in this code he won't understand because there are just too many queries inside the views file. Now I want to know is there any way I can set up all the queries inside some files and import them into our views file? can you guys please some links to articles where I can learn this thing. -
How to get the image url from an ImageField in a Django model with a JsonResponse?
I have this Model in a Django app class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) say = models.CharField(max_length=250) date = models.DateTimeField(auto_now_add=True) photo = models.ImageField(null = True, blank = True) def serialize(self): return { "user": self.user.username, "say": self.say, "date": self.date.strftime("%a-%d-%b-%Y , %H:%M:%S %p"), "photo": self.photo } and this function in the views.py @login_required(login_url = 'login')#redirect when user is not logged in def all_comments(request): all_comments = Comment.objects.order_by("-date").all() return JsonResponse([comment.serialize() for comment in all_comments], safe=False) and finaly this part of code in my javascript file document.addEventListener('DOMContentLoaded', function() { fetch('/all_comments') .then(response => response.json()) .then(all_comments => { do somethings with the data... and when i run this i'm getting the error: TypeError: Object of type ImageFieldFile is not JSON serializable If i remove the line "photo": self.photo from the serialize function inside the mode everything goes fine and im getting the data that i need. How can i retrieve images url, with the JsonResponse as well, in order to display it with the other data? Ihave tryied many things i found here and there but i cant find any solution. Thanks so much in advance -
How i can deploy a Django application on another port (not 8000) note that the default file configuration there was just the port 80
I want to deploy a Django application on a linux server on nginx, and i have a problem because I already i have an application running on the port 8000 and what i know that in the defaukt configuration of nginx file the port is 80, so what i should do to deploy my application on the linux server on nginx with another port. So How i can deploy a Django application on another port (not 8000) note that the default file configuration there was just the port 80 and what's the port number that i should choose? -
How to create a "save and add another" button and show on Wagtail admin model page
Was wondering if it is possible to add a custom button within a Wagtail model page that will allow me to save (create) the current data fields and move on to another page. The "save and add another" button was already available in django and I want to have something like that on the Wagtail model page. Thanks. -
How to make analytics of likes from one time period to another
Analytics about how many like's was made. Example url/api/analitics/?date_from=2021-03-03 &date_to=2021-03-20. API should return analytics aggre gated by day. models.py class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='likes', null=True, blank=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True, blank=True) object_id = models.PositiveIntegerField(default=0, null=True, blank=True) content_object = GenericForeignKey('content_type', 'object_id') date = models.DateTimeField(verbose_name='Дата создания', auto_now_add=True, null=True, blank=True) #date_from = django_filters.DateTimeFilter(field_name='date', lookup_expr='gte') #date_to = django_filters.DateTimeFilter(field_name='date', lookup_expr='lte') @property def day(self): return self.date.count() serializers.py class LikesSerializer(serializers.ModelSerializer): #days_since_joined = serializers.SerializerMethodField() date = serializers.DateTimeField() likes = serializers.IntegerField() class Meta: model = models.Like fields = ('date', 'likes')#, 'days_since_joined') views.py class LikesView(ModelViewSet): queryset = models.Like.objects.extra(select={'date': " date(posts_like.date)"}).annotate(likes=Count('pk')).order_by('-date') serializer_class = serializers.LikesSerializer conclusion [ { "date": "2022-01-05", "likes": 1 }, { "date": "2022-01-05", "likes": 1 }, { "date": "2022-01-05", "likes": 1 } ] But it is necessary that all 3 likes are summed up in 1 and so on from different users [ { "date": "2022-01-05", "likes": 3 }, ] -
Django-unittest-OneToOne relation between two app models
I have two applications in my project which are login and approval. When I give username for login that user should be available in approval Employee table. In my login user table i have employee field which has onetoone relation with Employee table. I have tried I dont get proper solutions. Here, when i write test code for login it will search that employee instance. I could not create that instance also. In this case what should i do?? How can i test my code??? Expecting guidance from anyone,... -
Count foreignkey objects in django
suppose class Product(models.Model): user = models.ForeignKey(User,...) ... class Sold(models.Model): post = models.ForeignKey(post,...) buyer = models.ForeignKey(User,...) Now how do i get no of items sold using User model Something like User.objects.all().annotate(nbuy=Count("?")) Putting "sold" at place of "?" gives number of items user have bought. What should i do to get no of items user have sold? -
Djangos data cannot be imported into the database, is my code wrong?
I am new to Django, and I'd like to ask some questions I used the model layer to create the model with fields in it,it can create user_id,movie_id field in the database. class Rating(models.Model): user_id = models.CharField(max_length=16) movie_id = models.CharField(max_length=16) rating = models.DecimalField(decimal_places=2, max_digits=4) rating_timestamp = models.DateTimeField() type = models.CharField(max_length=8, default='explicit') def __str__(self): return "user_id: {}, movie_id: {}, rating: {}, type: {}"\ .format(self.user_id, self.movie_id, self.rating, self.type) class Cluster(models.Model): cluster_id = models.IntegerField() user_id = models.IntegerField() def __str__(self): return "{} in {}".format(self.user_id, self.cluster_id) Execute this statement using Python xxx.py,I want to populate the database but it doesn't work import os import urllib.request import django import datetime import decimal from tqdm import tqdm os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') django.setup() from analytics.models import Rating def create_rating(user_id, content_id, rating, timestamp): rating = Rating(user_id=user_id, movie_id=content_id, rating=decimal.Decimal(rating), rating_timestamp=datetime.datetime.fromtimestamp(float(timestamp))) rating.save() return rating def download_ratings(): URL = 'https://gitee.com/zhangyoushang/wokkk/blob/master/latest/ratings.dat' response = urllib.request.urlopen(URL) data = response.read() print('download finished') return data.decode('utf-8') def delete_db(): print('truncate db') Rating.objects.all().delete() print('finished truncate db') def populate(): delete_db() ratings = download_ratings() for rating in tqdm(ratings.split(sep="\n")): r = rating.split(sep="::") if len(r) == 4: create_rating(r[0], r[1], r[2], r[3]) if __name__ == '__main__': print("Starting MovieGeeks Population script..." ) populate() But I found that my database was empty and there was no data in it. … -
How to fix using raw function MAX in queryset API not getting maximum marks?
views.py class MaxMarks(generics.ListAPIView): queryset = Marks.objects.raw('select student_id, subject_id, sem_marks, id, internal_marks, MAX(total_marks) from collegedetails.college_marks ') serializer_class = MarksSerializers I'm trying to figure out max marks using raw funtion in views.py after mapping to URL pattern and start run server but it getting only one record but still there more records which haveing max marks, Can any one suggest me what to do? -
request.POST data not in forms' cleaned_data
When creating a new instance of my model I fail to transfer the data from request.POST into the forms clean method on is_valid(): class cView(TemplateView): template_name = "store/new_product.html" def post(self, request, *args, **kwargs): print(request.POST) # correctly prints <QueryDict: {'number': ['8'], 'name': ['myproduCT'], 'price': ['2']}> obj = Product.objects.create(number = request.POST["number"], data = {}) form = ProductForm(request.POST, product = obj) form.is_valid() # validates to True The form looks like: class ProductForm(forms.Form): class Meta: model = Product fields = ["id", "number", "data"] def __init__(self, *args, **kwargs): product = kwargs.pop("product") super().__init__(*args, **kwargs) self.fields["number"] = forms.IntegerField(required = True) for key in product.data.keys(): self.fields[key] = forms.Charfield(requiered = False) def clean(self): cleaned_data = super().clean() print(cleaned_data) # only prints {'number': 8} ... Why is the rest of the request.POST data not in cleaned_data? Is this happening because the forms __init__() method gets an empty product.data attribute? How would I avoid this, when the Product is just now created and not filled with (validated) data? Product looks like this: class Product(models.Model): data = models.JSONField() number = models.PositiveIntegerField() -
Django download the right file from model
I created a web app that allows users to extract geometrical and other data from a 3D model in ifc format. So the user uploads the 3D model, the app gives him some basic info about the model and lets the user decide which data he wants to download in which format (xlsx or csv) For the uploaded file I have an upload form from the model. And then when the user decides what he wants to download I retrieve the uploaded file using the objects.latest query. But that can lead to problems, right? If multiple users are uploading files at the same time it can lead to a mismatch. What would a better practice of solving this problem be? How do I associate the page visitor withe the file he uploaded? -
Should I use Django or Flask for a microservice? I want to convert or generate any website into apk through microservices in python
Sir, I want to convert any website in apk through microservices in python, could you suggest to me which platform I'll used? and any suggention about microservices, please advice me cos I'm beginner in microservices..! -
how to check username exit or not two different table in djnago rest framework
while register new user in Tempdriver table need to varify username already exist or not in tempdriver table and appuser table, if check tempdriver table username its working but if i check appuser table getting error, pls someone help me out. models.py- add models Tempdriver and Appuser class Tempdriver(BaseModel): name = models.CharField(max_length=255) username = models.CharField(max_length=20,unique=True,null=True, blank=True) mobile = models.CharField(max_length=20,unique=True,null=True, blank=True) password = models.CharField(max_length=100) class AppUser(BaseModel): username = models.CharField(max_length=50) seriliazers.py class TempDriverUserSerializer(serializers.ModelSerializer): class Meta: model=Tempdriver fields=('username','mobile') def validate(self,username): user=Tempdriver.objects.filter(username=username) user_exists = AppUser.objects.filter(username=username) if user.exists() and user_exists.exists(): raise serializers.ValidationError("UserName already exists") def validate_mobile(self, mobile): mobile=Tempdriver.objects.filter(mobile=mobile) if mobile.exists(): raise serializers.ValidationError("Mobile Number already exists") views.py class Tempuserapi(APIView): parser_classes=(MultiPartParser,FormParser) def post(self, request, format=None): serializer = TempDriverUserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=HTTP_200_OK) else: return Response(serializer.errors, status= HTTP_200_OK) trace report ERROR Internal Server Error: /api/tempusercheck/ Traceback (most recent call last): File "E:\10dec_everestfleet\everest_jarvis\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "E:\10dec_everestfleet\everest_jarvis\env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "E:\10dec_everestfleet\everest_jarvis\env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\10dec_everestfleet\everest_jarvis\env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "E:\10dec_everestfleet\everest_jarvis\env\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "E:\10dec_everestfleet\everest_jarvis\env\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "E:\10dec_everestfleet\everest_jarvis\env\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File … -
How to apply other bootstrap and html properties to Django form fields
{{ form.firstname|as_crispy_field}} I want to know how further I can add bootstrap classes to this Django form field and also I want to add a placeholder thank you -
Django CheckConstraints to check start_date greater than or equal today
from django.db.models.functions import Now, TruncDay class Foo(models.Model): start_date = models.DateTimeField() end_date = models.DateTimeField() class Meta: constraints = [ name="start_date must be greater than or equal today", check=CheckConstraints(start_date__gte=TruncDay(Now())) ] like above code, I want to add CheckConstraint to check whether start_date is greater than or equal with today. but, after makemigration and migrate, error happened. functions or expression 'CURRENT_TIME' cannot be userd in check clause How can I check start_date with today? -
How to group data in Django serializer?
I have two models one for Collection and the other for Services and what I want is to return each collection with its services. Here is my code: class Collection(models.Model): name = models.CharField(max_length=50, verbose_name=_('Name')) enabled = models.BooleanField(default=True, verbose_name=_('Enabled')) def __str__(self): return self.name class Meta: verbose_name_plural = _('Collection') class MoreWorks(models.Model): collection = models.ForeignKey(Collection, on_delete=models.PROTECT) title = models.CharField(max_length=50, verbose_name=_( "Title"), blank=True, null=True) description = models.TextField( verbose_name=_('Description'), validators=[MaxLengthValidator(1000)], blank=True, null=True ) image = models.ImageField( verbose_name=_("Image"), upload_to='more_works/' ) enabled = models.BooleanField(default=True, verbose_name=_("Enabled")) class Meta: verbose_name_plural = _('More Works') I want to return each collection with its services using DRF. -
Stripe: 'payment_intent.succeeded' is also triggered when subscription gets renewed
I have two APIs for Stripe webhooks in my backend (Django). "Subscription" webhook: /api/subscriptions/webhook/ "Add Balance to Wallet" webhook: /api/wallet/webhook/ In the subscription webhook, I listen for invoice.paid and invoice.payment_failed events and in the wallet webhook I listen for payment_intent.succeeded event. The problem is whenever the subscription webhook gets called, the payment_intent.succeeded event is also triggered for the wallet webhook. I think that's because payment intents are also created for subscription as well. I need a way to differentiate these two (one-time payment [aka add balance to wallet] and subscription) so I don't end up with extra credit in user's wallet whenever their subscription get renewed. -
How do you return a complete url with get_success_url(self) in django?
How do you return a url using get_success_url(self) in django without using reverse for a generic view? Basically, I want to have something as below. def get_success_url(self): url = self.object.url # This is a charfield with "https://stackoverflow.com/questions/ask" return url I know that people often use reverse when returning a url, but I would like do it like above. Thank you, and please write any questions you have. By the way, I never tested the above code, but I don't know if it will work properly. -
Can we check whether a user is part of an Organizational Units instead of Groups in Django LDAP?
In my LDAP directory, Users are added to Organizational Units instead of groups. How can I check whether a user is a part of an Organizational Unit using Django LDAP ? My settings.py file: AUTH_LDAP_SERVER_URI = 'ldap://qwery' AUTH_LDAP_BIND_AS_AUTHENTICATING_USER = True AUTH_LDAP_BIND_DN = 'dndndn' AUTH_LDAP_BIND_PASSWORD = 'pwdpwd' AUTH_LDAP_USER_SEARCH = LDAPSearchUnion( LDAPSearch('ou=abbb,dc=xxx,dc=net', ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)"), LDAPSearch('ou=ammmm,dc=xxx,dc=net', ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)"), LDAPSearch('ou=addddd,dc=xxx,dc=net', ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)"), LDAPSearch('ou=ahhhhh,dc=xxx,dc=net', ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)"), ) AUTH_LDAP_CACHE_TIMEOUT = 0 AUTHENTICATION_BACKENDS = [ 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ] # Populate the Django user from the LDAP directory. AUTH_LDAP_USER_ATTR_MAP = { "name": "cn", "username": "sAMAccountName", "department":"distinguishedName" } AUTH_LDAP_GROUP_SEARCH = LDAPSearch( "OU=addddd,DC=xxx,DC=net", ldap.SCOPE_SUBTREE, "(objectClass=*)") AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_GROUP_TYPE = GroupOfNamesType() AUTH_LDAP_ALWAYS_UPDATE_USER = True AUTH_USER_MODEL = 'login.Account' AUTH_LDAP_USER_FLAGS_BY_GROUP= { "is_it": "OU=IT,OU=ahhhh,DC=xxx,DC=net", } Thank you