Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin Tabural Inline Throwing Error
I have created a Category and Product model when In the product model I have created a category field which is foreign key relation to the category model. class Category(models.Model): name = models.CharField(max_length=100) icon= models.ImageField(upload_to='CategoryIcons/', blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name Here is the Product Model - class Product(models.Model): title = models.CharField(max_length=200) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products') productImages = models.ManyToManyField(ProductImages) price = models.IntegerField() qty = models.IntegerField(default=0) shortDescription = models.TextField(blank=True, null=True) active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.title}{ self.category}' Now when I try to use Django tabural Inline class with it says SystemCheckError: System check identified some issues: ERRORS: <class 'shop.admin.CategoryInline'>: (admin.E202) 'shop.Category' has no ForeignKey to 'shop.Product'. admin.py file code - from django.contrib import admin from .models import Category, ProductImages, Product, Order, Shipping, OrderItem # Register your models here. class CategoryInline(admin.TabularInline): model = Category readonly_fields = ('id', 'created_at') extra = 2 class ProductAdmin(admin.ModelAdmin): inlines = [ CategoryInline, ] admin.site.register(Category) admin.site.register(ProductImages ) admin.site.register(Product, ProductAdmin) admin.site.register(Order) admin.site.register(Shipping) admin.site.register(OrderItem) I am confused that where I am doing wrong as in most of the places I see the same formate and code. Please help me out. -
form.as_p displays only one first input in Django template
I'm trying to use my form in django template but only one input displaying on the page Template <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Save"> </form> Screenshot from page Form class JournalRecordForm(forms.ModelForm): class Meta: model = JournalRecord fields = ('shutdown_datetime', 'approximate_turn_on_datetime', 'shutdown_type', 'shutdown_reason', 'additional_information') Model class JournalRecord(models.Model): record_creation_datetime = models.DateTimeField(verbose_name='Дата і час запису', auto_now_add=True, null=False, blank=False) record_close_datetime = models.DateTimeField(verbose_name='Дата і час відміни заяви', default=None, null=True, blank=True) ...... additional_information = models.TextField(verbose_name='Додаткова інформація', null=True, blank=True) View class JournalRecordCreateView(CreateView, LoginRequiredMixin, PermissionRequiredMixin): permission_required = ('dispatcher.add_journalrecord') model = JournalRecord form_class = JournalRecordForm fields = '__all__' I have no idea what is wrong. I tried: manually pass JournalRecordForm() to template context change class based CreateView to View. -
when django-adminplus is used , authentication and authorization section is not available in the django menu
When we add adminplus in django to add custom views, the authentication and authorization section disappears. Why? -
Django own templatestags
I have a question. I created own tags in django like this: from django import template from my_app.models import Post register = template.Library() @register.simple_tag def last_create_members(last=5): return Post.objects.order_by('created')[:5] And I wanted to displayed it. So when I display it this way: {% last_create_members %} everything is good and I see 5 Posts. But when I want to add tag in loop : {% for p in last_create_members %} <p>{{ p }}</p> {% endfor %} I can't see anything (empty space). What am I doing wrong? and can I add tag in loop that way? -
Unable to set cookie in React by using Django
I created a React website that uses API to communicate with the Django backend. I use djangorestframework to create API. I need to set cookie to react but there is no update cookie on React site. views.py class Test(generics.CreateAPIView): def post(self,request, *args, **kwargs): response = Response() response.set_cookie('test_cookie', 'MY COOKIE VALUE') return response How to fix this problem? What topic should I know to fix that problem? -
Django: get model's fields name
I am trying to create a table in react that uses as table information from a django backend. I would like to fetch the table's columns from the API, so I tried updating the model: class Activity(models.Model): aid = models.AutoField(primary_key=True) uid = models.ForeignKey(USER_MODEL, default=1, verbose_name="Category", on_delete=models.SET_DEFAULT, db_column="uid") rid = models.IntegerField() action = models.TextField(max_length=254, blank=True, null=True) time = models.TextField(max_length=254, blank=True, null=True) table = models.TextField(max_length=254, blank=True, null=True) class Meta: managed = False db_table = "activity" @property def fields(self): return [f.name for f in self._meta.fields] I am trying to use fields() as the method to get all the model's "column" names, so that I can place them in the API's response, but it does not work. How can I get a django model's field names from the model's meta? -
How to use model and serializer in Python to connect to various databases using the mysql connector?
I need to connect multiple instances (nearly 100). Is there a way to connect multiple instances of mysql connector python without using a cursor? I already tried using cursor. common Django methods? connection_pool = pooling.MySQLConnectionPool( pool_name=dbname, pool_size=1, pool_reset_session=True, host=host, database=dbname, user=os.getenv("DYNAMIC_DB_USERNAME"), password=os.getenv("DYNAMIC_DB_PASSWORD"), ) connection_object = connection_pool.get_connection() with connection_object .cursor(buffered=True) as cursor: cursor.execute("""select * from employee""") row = dictfetchall(cursor) I'll need to do the same thing with the model and serializer methods. Is it possible to rewrite in -
Reverse for 'save-review' not found. 'save-review' is not a valid view function or pattern name
I have error in Django: "django.urls.exceptions.NoReverseMatch: Reverse for 'save-review' not found. 'save-review' is not a valid view function or pattern name." I study django through YouTube, I do everything as in the video, but I get an error. When there is no authorization and "Add review" button is hidden, the page works fine. But when "Add review" button is shown, the product page doesn't load and throws an error. product-detail.html <div class="col-md-6"> <h3 class="my-3">Обзоры - 4.5/5 <i class="fa fa-star text-warning"></i> {% if user.is_authenticated %} <button type="button" data-toggle="modal" data-target="#productReview" class="btn btn-warning bt-sm float-right">Add review</button> {% endif %} </h3> <div class="card"> <div class="card-body" style="max-height: 400px; overflow; auto;"> <!-- Detail --> <blockquote class="blockquote text-right"> <small>Good product</small> <footer class="blockquote-footer">John Lenon <cite title="Source Title"> <i class="fa fa-star text-warning"></i> <i class="fa fa-star text-warning"></i> <i class="fa fa-star text-warning"></i> <i class="fa fa-star text-warning"></i> </cite> </footer> </blockquote> </div> </div> </div> </div> {% if user.is_authenticated %} <!-- Product Review --> <div class="modal fade" id="productReview" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Product Review</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form id="addForm" method="post" id="addForm" action="{% url 'save-review' data.id %}"> {% csrf_token %} <table class="table table-bordered"> {{form.as_table}} <tr> <td colspan="2"> <button type="submit" class="btn … -
is it possible to register only a view in django admin and not any model? using django 3.2 version
The requirement is to register views in the django admin interface just like the models, which will serve as hyperlink and execute some code in the views to display some on-screen data. Is it possible. Looks like adminplus doesnt work with this version of django for t he same. Any other tool to serve this purpose? -
Refused to apply style due to unsupported MIME type
Refused to apply style from 'http://127.0.0.1:8000/plugins/font-awesome-4.7.0/css/font-awesome.min.css'%20%7D' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. ``STATIC_URL = 'static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]`` STATIC_ROOT = os.path.join(BASE_DIR, 'assets') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') `` -
is there a way to make this filter in Django [closed]
I don't know what is the name of this filter method , but I want to do such like it in my project , and don't even know its name Such like this filter such like categories and every category , I could the products inside it or not , or such like this picture . -
how to solve this problem I don't know how to make a user with his login can enter the application
in login user.save() ^^^^ UnboundLocalError: cannot access local variable 'user' where it is not associated with a value [21/Feb/2023 09:52:15] "GET /login HTTP/1.1" 500 63809 where is the problem -
Django MongoDB configuration works but throw CLI error
I'm trying to configure Mongo DB with Django and works, the database was created, migrations are done, the documents appears and i can save elements, but migrations command throws and error. The Django settings: DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': MONGO_NAME, 'CLIENT': { 'host': MONGO_URL, 'username': MONGO_NAME, 'password': MONGO_PASSWORD, 'authSource': 'admin', 'authMechanism': 'SCRAM-SHA-1', }, 'ENFORCE_SCHEMA': False } } The CLI error bash-5.0# python manage.py makemigrations order Migrations for 'order': order/migrations/0001_initial.py - Create model Order bash-5.0# python manage.py migrate order Operations to perform: Apply all migrations: order Running migrations: Applying order.0001_initial...This version of djongo does not support "NULL, NOT NULL column validation check" fully. Visit https://nesdis.github.io/djongo/support/ Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/djongo/cursor.py", line 51, in execute self.result = Query( File "/usr/local/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 784, in __init__ self._query = self.parse() File "/usr/local/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 876, in parse raise e File "/usr/local/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 857, in parse return handler(self, statement) File "/usr/local/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 928, in _insert query = InsertQuery(self, self.db, self.connection_properties, sm, self._params) File "/usr/local/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 340, in __init__ super().__init__(*args) File "/usr/local/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 62, in __init__ self.parse() File "/usr/local/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 410, in parse self._fill_values(statement) File "/usr/local/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 368, in _fill_values raise SQLDecodeError djongo.exceptions.SQLDecodeError: Keyword: None Sub SQL: None FAILED SQL: ('INSERT INTO "django_migrations" … -
How to extend DRF generic views to generate Open API schema?
I'm trying to generate Open API schema with Django Rest Framework and DRF Spectacular, The option 2 works well and return component schema well but but i would like to use option 1 to customize parent class of child views. Option 1: urls.py: path( 'learningmaterialcategory/', LearningMaterialCategoryListApiView.as_view( model=LearningMaterialCategory ), name='learningmaterialcategory_list' ), views.py: class BaseApiView(APIView): serializer_class = None def setup(self, request, *args, **kwargs): self.app_name = self.model._meta.app_label super().setup(request, *args, **kwargs) def get_serializer_class(self): if self.serializer_class is None: serializer_class_name = self.model.__name__ + 'Serializer' self.serializer_class = getattr(__import__(f'{ self.app_name }.api.serializers', fromlist=[serializer_class_name]), serializer_class_name) return self.serializer_class class GenericListApiView(BaseApiView, generics.ListAPIView): model = None permission_classes = (permissions.AllowAny,) def setup(self, request, *args, **kwargs): super().setup(request, *args, **kwargs) filter_class_name = self.model.__name__ + 'Filter' self.filterset_class = getattr(__import__(f'{ self.app_name }.filters', fromlist=[filter_class_name]), filter_class_name) def get_queryset(self): return self.model.objects.all() class LearningMaterialCategoryListApiView(GenericListApiView): pass schema.yaml: /api/services/learningmaterialcategory/{id}/detail/: ... responses: '200': description: No response body Option 2: urls.py: path( 'learningmaterialcategory/', LearningMaterialCategoryListApiView.as_view(), name='learningmaterialcategory_list' ), views.py: class LearningMaterialCategoryListApiView(generics.ListAPIView): queryset = LearningMaterialCategory.objects.all() serializer_class = LearningMaterialCategorySerializer schema.yaml: ... components: schemas: LearningMaterialCategory: type: object properties: id: type: integer readOnly: true title: type: string maxLength: 50 required: - id - title -
adding limit for a models choices in Django
I have a model for order status, this model creates a table with a foreign key to order model and saves a status for order ( like pending, accepted, failed, sending and received ) and a time of the status added it is auto generate in with pending when the order is created and other ones have an API with post method for each order now, I wanna limit the choices for API in this form: If there is a pending status when getting order status list the choices need to limited to accepted and failed If there is a accepted status when getting order status list the choices need to limited to sending and received If there is a failed status when getting order status list the choices need to limited to pending and accepted If there is a sending status when getting order status list the choices need to limited to received this is the order status model: class OrderStatus(models.Model): order = models.ForeignKey(Order, on_delete=models.PROTECT, related_name='status') ORDER_STATUS_PENDING = 'P' ORDER_STATUS_ACCEPTED = 'A' ORDER_STATUS_FAILED = 'F' ORDER_STATUS_SENDING = 'S' ORDER_STATUS_RECEIVED = 'R' ORDER_STATUS_CHOICES = [ (ORDER_STATUS_PENDING, 'Pending'), (ORDER_STATUS_ACCEPTED, 'Accepted'), (ORDER_STATUS_FAILED, 'Failed'), (ORDER_STATUS_SENDING, 'Sending'), (ORDER_STATUS_RECEIVED, 'Received') ] status = models.CharField( max_length=1, … -
djano support nested or flat values for a single field using single serializer
I have a DateRangeSerializer serializer that validates a payload. import rest_framework.serializers as serializer from django.conf import settings class ValueNestedSerializer(serializer.Serializer): lower = serializer.DateTimeField(input_formats=settings.DATETIME_INPUT_FORMATS, required=True) upper = serializer.DateTimeField(input_formats=settings.DATETIME_INPUT_FORMATS, required=True) class DateRangeSerializer(serializer.Serializer): attribute = serializer.CharField(default="UPLOAD_TIME", allow_null=True) operator = serializer.CharField(default="between_dates") value = ValueNestedSerializer(required=True) <---- this could be set to `False` to address the issue # lower = serializer.DateTimeField() # upper = serializer.DateTimeField() timezone = serializer.CharField(default="UTC") timezoneOffset = serializer.IntegerField(default=0) The respective payload: "date_range": { "attribute": "date_range", "operator": "between_dates", "value": { "lower": "2023-01-06T00:00:00Z", "upper": "2023-02-05T23:59:59Z" } } Here value field is nested. But there are few implementations where lower and upper are flat values and not nested. Like: "date_range": { "lower": "2023-01-21T00:00:00Z", "upper": "2023-02-21T23:59:59Z" } Now, I can set the value required=False and add lower/upper as flat fields like I've mentioned in the comments above. But I want to enforce it more "properly". Is there any other way where I can handle both payloads for nested and flat lower-upper values? -
django equivalent for mysql's JSON_OVERLAPS
i basically have a model named as Teachers and my table look something like this Teachers id - int student_ids - jsonfield ( eg - [1,2,3,4]) so now my usecase is something like this i have a student_list - [12,213,43,123,345,43,1] so now i want to get all teachers that have these students in their student_ids list so if we are talking about raw sql, then it can be easily acheived with JSON_OVERLAPS, something like JSON_OVERLAPS('teachers.auction' , student_list) but as i am currently using django 3.2 and mysql 8, i want to know how can we do similar thing in DJANGO ORM itself i know about __contains and all in django, but it will not work in my usecase ( from what i undestand , json_Contains will search that every element in student_list is present in teacher.student_ids or not), instead i want which teacher.students_ids contains any of the element in student_list -
Context variables not being passed to template in Django class-based view
Banging my head against a wall.. I'm trying to return a table of Job objects, with views separated by month. I'm passing 'year' and 'month' variables through get_context_data, yet in my template they're returning blank strings. Even ChatGPT can't find anything wrong lol. Can anyone spot something? Here's my view: class pipelineMonthView(SingleTableMixin, MonthMixin, ListView): model = Job table_class = JobTable form_class = JobForm bulk_actions = PipelineBulkActionsForm template_name = "main_app/pipeline_by_month.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['job_form'] = self.form_class context['bulk_actions'] = self.bulk_actions context['year'] = 2023 #hardcoded for debugging context['month'] = 2 #hardcoded for debugging return context def get_queryset(self): queryset = super().get_queryset() print(f'the result of self.get_month: {self.get_month()}') queryset = queryset.filter(job_date=self.get_month()) return queryset My URL, including URLs from main_app: path('pipeline/<int:year>/<int:month>/', views.pipelineMonthView.as_view(model=Job), name="pipeline-by-month"), And my URL tag: {% url 'main_app:pipeline-by-month' year month %} Here's the traceback: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/handlers/base.py", line 204, in _get_response response = response.render() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/template/response.py", line 105, in render self.content = self.rendered_content File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/template/response.py", line 83, in rendered_content return template.render(context, self._request) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/template/base.py", line 170, in render return self._render(context) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/template/base.py", line 162, in _render return self.nodelist.render(context) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/template/base.py", line … -
Solution for handle many request to run deep learning on web server Python Django
After I build a service to process video with a Yolo model on Django server. (Detect humans in the video then show the detected video) I realized that every time I send a request to the server for process, it will create a new thread and run Yolo source code again. A lot of resources will need every time deep learning runs. I only want one processing request run at one time. My first idea to handle this case saves the status to Database then when a new request comes, check if the last record is Complete which means there is no deep learning process running now. But I guess there are better solutions with more advantages to solve my case. -
Django Models: showing object doesn't exists for the object created a moment before
Django Showing object doesn't exist error for the object created a moment before. You can go through the my models, admin Models. After sleeping for 1 sec, I'm getting the expected output. models.py from django.db import models class MyModel(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) status = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return f"{self.user.username}" class Action(models.Model): action = models.TextField() action_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return f"{self.action}" admin.py from django.contrib import admin import threading from time import sleep def test_method(action_obj_id): print(f"Action obj ids (external method): {action_obj_id}", list(models.Action.objects.values_list("id", flat=True))) sleep(1) print(f"Action obj ids (external method after sleep): {action_obj_id}", list(models.Action.objects.values_list("id", flat=True))) @admin.register(models.MyModel) class MyModelAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): action_obj = models.Action.objects.create( action=f"my Action", action_by=request.user, ) action_obj_id = action_obj.id print(f"Action obj ids (inside): {action_obj_id}", list(models.Action.objects.values_list("id", flat=True))) threading.Thread(target=test_method, args=(action_obj_id)).start() Output: Action obj ids (inside): 5, [1, 2, 3, 4, 5] Action obj ids (external method): 5, [1, 2, 3, 4] Action obj ids (external method after sleep): 5, [1, 2, 3, 4, 5] -
Django postgresql setup using 189Gig of ram and 144 core cpu fully with just a few users. How to debug?
Hey we are using Django + Postgresql with nginx to run our app. The problem is - as soon as there are few hundred users on the app; we start getting errors like : failed (24: Too many open files) We have already increased our ulimit -Hn and ulimit -Sn. I am also attaching a screenshot of htop As you can see in the screenshot: postgres is using too much CPU, which should not happen as we have a very powerful machine. How can we debug the problem with postgresql with django? By the way our max_connections are 700 and shared_buffers is 8080MB What can we do next? -
Search filter for stringrelated field foreign key
I'm currently trying to implement a social media like web app in which users can filter through a user data base based on interests, hobbies and types of lifestyle in Django. Interests, hobbies and lifestyle are all foreign key objects that are saved as stringrelatedfields as 1 user can have hobbies etc. As of right now I can only filter by 1 hobby at a time (Ex: Can only filter users who enjoy soccer, however I don't know how to search for users that like soccer + basketball) here is my models.py class Account(models.Model): username = models.CharField(max_length=20, null=True) account_type = models.CharField(max_length=30, null=True) first_name = models.CharField(max_length=30, null=True) last_name = models.CharField(max_length=30, null=True) email = models.EmailField(max_length=254, null=True) class PersonalTrait(models.Model): trait = models.CharField(max_length=200, null = True) listing_account = models.ForeignKey(ListingAccount, related_name='personal_traits', on_delete=models.CASCADE, null=True) def __str__(self): return f"{self.trait}" class Interest(models.Model): interest = models.CharField(max_length=200, null=True) listing_account = models.ForeignKey(ListingAccount, related_name='interests', on_delete=models.CASCADE, null=True) def __str__(self): return f"{self.interest}" class Lifestyle(models.Model): lifestyle = models.CharField(max_length=200, null=True) listing_account = models.ForeignKey(ListingAccount, related_name='lifestyle', on_delete=models.CASCADE, null=True) def __str__(self): return f"{self.lifestyle}" serializers.py class ListingAccountSerializer(serializers.ModelSerializer): personal_traits = serializers.StringRelatedField(many=True) interests = serializers.StringRelatedField(many=True) lifestyle = serializers.StringRelatedField(many=True) class Meta: model = ListingAccount fields = ['id', 'username', 'first_name', 'last_name', 'email', 'phone_number', 'personal_traits', 'interests', 'lifestyle'] def to_internal_value(self, data): return data views.py class AccountFilterViewSet(generics.ListAPIView): … -
crash django admin text field with edit persian character
I have a problem with models.CharField() when we typing persian string into this field and try editing that with drag cursor with mouse(from RTL) and select part of that string then command+x or ctl+x, panel crashes and hangs. can somebody help me. Thanks -
how to use Sendgrid, dj-rest-auth on Django
I am currently working on developing a password reset function for my project, and I want to use Sendgrid as my email backend and dj-rest-auth. Specifically, I am trying to override the email template with my custom template, but Django is still sending me the default email. I have no idea how to fix this issue and need your help. here is the libraries Django django-sendgrid-v5 dj-rest-auth django-allauth dj-rest-auth here is my code SENDGRID_API_KEY = 'my api key here' EMAIL_BACKEND = "sendgrid_backend.SendgridBackend" REST_AUTH_SERIALIZERS = { 'PASSWORD_RESET_SERIALIZER': 'accounts.serializers.CustomPasswordResetSerializer', } from dj_rest_auth.serializers import PasswordResetSerializer class CustomPasswordResetSerializer(PasswordResetSerializer): def get_email_options(self): return { 'domain_override': 'https://example.com', 'html_email_template_name': '/template/password_reset.html' } urlpatterns = [ path("password-reset/confirm/<uid>/<token>/", TemplateView.as_view(template_name="password_reset_confirm.html"), name='password_reset_confirm'), path("dj-rest-auth/", include("dj_rest_auth.urls")), ] I override get_email_options method and try to specify which email template should be used -
ModuleNotFoundError: No module named 'django.utils'
I was trying to setup one of the open source project,During this when I run make postgres cmd on ubuntu terminal then I am getting following error -> Configure PostgreSQL database -> Create database user 'vulnerablecode' sudo -u postgres createuser --no-createrole --no-superuser --login --inherit --createdb vulnerablecode || true createuser: error: creation of new role failed: ERROR: role "vulnerablecode" already exists sudo -u postgres psql -c "alter user vulnerablecode with encrypted password 'vulnerablecode';" || true ALTER ROLE -> Drop 'vulnerablecode' database sudo -u postgres dropdb vulnerablecode || true -> Create 'vulnerablecode' database sudo -u postgres createdb --encoding=utf-8 --owner=vulnerablecode vulnerablecode make[1]: Entering directory '/mnt/c/Users/admin/Desktop/pankaj/About Code NextB/vulnerablecode' -> Apply database migrations venv/bin/python manage.py migrate Traceback (most recent call last): File "/mnt/c/Users/admin/Desktop/pankaj/About Code NextB/vulnerablecode/manage.py", line 6, in <module> command_line() File "/mnt/c/Users/admin/Desktop/pankaj/About Code NextB/vulnerablecode/vulnerablecode/__init__.py", line 22, in command_line from django.core.management import execute_from_command_line File "/mnt/c/Users/admin/Desktop/pankaj/About Code NextB/vulnerablecode/venv/lib/python3.10/site-packages/django/__init__.py", line 1, in <module> from django.utils.version import get_version ModuleNotFoundError: No module named 'django.utils' make[1]: *** [Makefile:92: migrate] Error 1 make[1]: Leaving directory '/mnt/c/Users/admin/Desktop/pankaj/About Code NextB/vulnerablecode' make: *** [Makefile:103: postgres] Error 2 In the above error,the main thing to emphasis is No module named 'django.utils' but after seeings I tried to install it using sudo-apt-get install django-utils then I am …