Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create an asynchronous REST API in DJango?
I have a DJango application and am using djangorestframework for my API. Now the problem is I want to create a report which takes about 5 minutes to generate. So what is the best way to create an endpoint which when requested will give the user a status (in progress, completed) of the job and return the final file once its completed? I am confused between using Celery, RabbitMQ, Amazon SQS, Kafka, etc. -
Fetch API post data not receiving in Django view
What I am trying to do ? I am trying to send a post request with data to a Django view using fetch API like this: javascript: const data = { search_text: "", months: 6, property_type: "all" }; const headers = { 'Accept': 'application/json', 'Content-Type':'application/json', 'X-Requested-With':'XMLHttpRequest' } fetch("some-url", { method: "POST", headers: headers, body: JSON.stringify(data) }) .then((response) => response.json()) .then((data) => console.log(data)); view: class MyView(View): def post(self, request, *args, **kwargs): print("request: ", request.POST) # do stuff with post data urls: re_path(r"^my_view/$", login_required(csrf_exempt(MyView.as_view())), name="my_view"), Problem When I try to access the post data in my Django view I get empty QueryDict and the output of the terminal is this: request: <QueryDict: {}> [06/Jan/2022 06:48:19] "POST /my_app/my_view/ HTTP/1.1" 200 114 Forbidden (CSRF token missing or incorrect.): /inbox/notifications/api/unread_list/ [06/Jan/2022 06:48:22] "{"search_text":"","months":"6","property_type":"all"}GET /inbox/notifications/api/unread_list/?max=5 HTTP/1.1" 403 12291 I have tried looking it up and nothing seems to work. We are using react and i know axios can also be used but it should work with fetch api why isn't it working please help. -
How to prevent user from creating new content until currently created content is verified by admin
So i have this CreateShopView a view for seller type users to simply register their shops. the Shop model has a status field which is set to 'processing' by default, and obviously i didn't include the field in my ShopCreateForm so every time a seller registers a shop it's saved in the database with the status of 'processing'. my question is how can i prevent sellers from registering new shops while they still have a shop with 'proccesing' status. thanks in advance. -
Can't render template, getting page not found (404) Django
I can't seem to find the error, site works fine but when I request http://127.0.0.1:8000/test I get the 404 error, I feel so stupid I'm really stuck on this, please help:( Error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/test Using the URLconf defined in project4.urls, Django tried these URL patterns, in this order: admin/ [name='index'] login [name='login'] logout [name='logout'] register [name='register'] posts-json/ [name='posts-view-json'] ^network/static/(?P<path>.*)$ ^media/(?P<path>.*)$ The current path, test, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. This is my urls from django.urls import path from django.conf import settings from django.conf.urls.static import static from . import views from .views import post_view_json, profile_test_view urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("test/", profile_test_view, name="test"), # endpoints path("posts-json/", post_view_json, name="posts-view-json") ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) It's a social website and I'm trying to render the posts and user's profiles on a page. My views from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect from django.http.response import JsonResponse from … -
Django Unit Test Case for Models, Serializers, URL's & Views
I'm a newbie to Unit testing. As I need to perform test case for following models, serializers, views & urls. Can anyone please help. Models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth import get_user_model # Create your models here. class User(AbstractUser): """This Class is used to extend the in-build user model """ ROLE_CHOICES = (('CREATOR','CREATOR'),('MODERATOR','MODERATOR'),('USERS','USERS')) GENDER_CHOICES = (('MALE','MALE'),('FEMALE',"FEMALE"),('OTHER','OTHER')) date_of_birth = models.DateField(verbose_name='Date of Birth', null=True) profile_image = models.ImageField(upload_to='media/profile_images', verbose_name='Profile Image', default='media/profile_images/default.webp', blank=True) bio = models.TextField(verbose_name='Bio') role = models.CharField(max_length=10, verbose_name='Role', choices=ROLE_CHOICES) gender = models.CharField(max_length=6, verbose_name='Gender', choices=GENDER_CHOICES) Serializers.py class UserSerializer(serializers.ModelSerializer): following = serializers.SerializerMethodField() followers = serializers.SerializerMethodField() class Meta: model = User fields = ('first_name','last_name','username','password','email','date_of_birth', 'profile_image','bio','role','gender', 'following','followers') extra_kwargs = {'is_active':{'write_only':True}, 'password':{'write_only':True}} def create(self, validated_data): logger.info('Information Incoming!') return User.objects.create_user(**validated_data) def update(self, *args, **kwargs): user = super().update( *args, **kwargs) p = user.password user.set_password(p) user.save() return user def get_following(self, obj): return FollowingSerializer(obj.following.all(), many=True).data def get_followers(self, obj): return FollowersSerializer(obj.followers.all(), many=True).data Views.py class UserAPI(viewsets.ModelViewSet): serializer_class = UserSerializer queryset = User.objects.all() # permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope] I tried implementing unit test case but getting an error self.assertEquals(user.get_last_name(), "Johnson") - AttributeError: 'User' object has no attribute 'get_last_name' tests.py class UserTests(TestCase): def setUp(self): User.objects.create( first_name='Louis',last_name='Johnson',username='louis.johnson', email='louis@mail.com',date_of_birth='1994-12-12', bio='Hello I am Louis', role='MODERATOR',gender='MALE') def test_users_model(self): user = User.objects.get(first_name='Louis') self.assertEquals(user.get_last_name(), "Johnson") self.assertEquals(user.get_username(), … -
Select time field dynamically in django forms
I am working on a project of a website to reserve football fields by using Django. In the project, I have 3 models: football field (name, address), team (information about the captain of the team) and reservation (football field, team, date and time of reservation): class Team(models.Model): team_name = models.CharField('Team Name', max_length=60) captain_first_name = models.CharField('Captain Name',max_length=30) captain_second_name = models.CharField('Captain Second Name', max_length=30) captain_email = models.EmailField('User Email', blank = True) captain_phone = models.CharField('Captain Phone', max_length=9) def __str__(self): return self.team_name class Football_Field(models.Model): name = models.CharField('Field name', max_length=120) address = models.CharField('Field address', max_length=120) def __str__(self): return self.name class Reservation(models.Model): team = models.ForeignKey(Team, blank = True, on_delete = PROTECT) football_field = models.ForeignKey(Football_Field, blank = True, on_delete = PROTECT) reservation_date = models.DateField('Reservation Date') reservation_time = models.TimeField('Reservation Time', default=dt.time(00, 00)) I create a reservation form as well, like this: class ReservationForm(ModelForm): class Meta: model = Reservation fields = "__all__" labels = { 'team': 'Select your team', 'football_field': 'Select football field', 'reservation_date': 'Select reservation date', 'reservation_time': 'Select time of reservation' } widgets = { 'team' : forms.Select(attrs={'style': 'width:500px', 'class': 'form-select'}), 'football_field' : forms.Select(attrs={'style': 'width:500px', 'class': 'form-select'}), 'reservation_date' : forms.DateInput(attrs={'class': 'form-control', 'style': 'width:200px', 'type': 'date'}), 'reservation_time': forms.Select(choices=HOUR_CHOICES, attrs={'format':'%H', 'class': 'form-control', 'style': 'width:200px', 'type': 'time', 'required step':"3600"}) } The … -
How to group these base on same address?
{'street_number': '3', 'street_name': 'Raycraft', 'street_type': 'Dr', 'municipality': 'Amherstview', 'postal_code': 'K7N1Z1', 'type_of_reports': 'Valuation'}, {'street_number': '3', 'street_name': 'Raycraft', 'street_type': 'Dr', 'municipality': 'Amherstview', 'postal_code': 'K7N1Z1', 'type_of_reports': 'Inspection'} Group these values by address ? for example output should be like: {'street_number': '3', 'street_name': 'Raycraft', 'street_type': 'Dr', 'municipality': 'Amherstview', 'postal_code': 'K7N1Z1', 'type_of_reports': ['Valuation',Inspection]} -
Django - for each field value
I have a question. In my view, I return a dataset which includes: Category Product Price I want to say something like the below, where I show UI elements related to a category as a whole. is it possible? {% for item.category in products %} -
Can't submit image via forms (django)
I'am trying to submit a form and register it on database but imagefield is not working. Everytime i try to upload an image and hit save it just refreshes and tells me that 'This field is required'. Here is my code: models.py: from django.db import models class Photos(models.Model): title = models.CharField(max_length=50) description = models.TextField(blank=True, null=True) photo = models.ImageField(upload_to='images/') forms.py: from django import forms from .models import Photos class PhotosForm(forms.ModelForm): class Meta: model = Photos fields = [ 'title', 'description', 'photo' ] views.py: from django.shortcuts import render from .models import Photos from .forms import PhotosForm def photo_create_view(request): form = PhotosForm(request.POST, request.FILES or None) if form.is_valid(): form.save() context = { 'form': form, } return render(request, "photos/photo_create.html", context) setting.py: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' template: {% extends 'home.html'%} {% block content %} <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Save" /> </form> {% endblock %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>website</title> </head> <body bgcolor="pink"> {% block content %} {% endblock %} </body> </html> also my filetree photo: https://i.stack.imgur.com/dmyDM.png -
Save file as zip through django-storage
I am able to store file in S3 but i want to store .zip files instead of file Reference for django-storage : https://testdriven.io/blog/storing-django-static-and-media-files-on-amazon-s3/ storage_backends.py class PrivateMediaStorage(S3Boto3Storage): location = 'private' default_acl = 'private' file_overwrite = False custom_domain = False Model.py class Upload(models.Model): upload_file = models.FileField(storage=PrivateMediaStorage()) using ClearableFileInput field in Admin.py, I am able to upload and download the file but I want to create a .save() method in model to convert my file to zip first and then save to field so it store as zip in S3 bucket -
Not able to install django-allauth in ubuntu 18.04.6 LTS
I'm trying to add social authentication in my project but when I try to install django-allauth it is giving me error I've tried this post but no luck it's giving me another error related to setuptools_rust I've given commands I've tried and errors related to each command. $ pip3 install django-allauth Error : Complete output from command python setup.py egg_info: Traceback (most recent call last): File "", line 1, in File "/tmp/pip-build-7e3fgl32/cryptography/setup.py", line 14, in from setuptools_rust import RustExtension ModuleNotFoundError: No module named 'setuptools_rust' =============================DEBUG ASSISTANCE========================== If you are seeing an error here please try the following to successfully install cryptography: Upgrade to the latest pip and try again. This will fix errors for most users. See: https://pip.pypa.io/en/stable/installing/#upgrading-pip =============================DEBUG ASSISTANCE========================== ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-7e3fgl32/cryptography/ Then I tried to install setuptools_rust as it causing error $ pip3 install setuptools_rust This package does not give me any error it installed successfully Then I've tried to install some commands from this post $ sudo apt-get install build-essential libssl-dev libffi-dev python-dev It did not change anything check response of command Reading package lists... Done Building dependency tree Reading state information... Done build-essential is already the newest … -
What are the setting we can specify in the dajngo setting file for multi-tenant testcses?
I want to run the testcase of multi-tenant without using default schema.So please anyone can help? -
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?