Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to parse file names (images) and assign them to a model?
I am relatively new in Django and building an e-commerce application. I have a folder with images (they are in the static directory), and lots of products (~15000, I pull the product data from an API.). Unfortunately I do not pull the image data from the API, instead I have a folder with all the images, and their name contains a fragment of the product.name string. e.g product.name = AH 285/55 R16 Turanza AH325 image_name = Turanza__1 What I am trying to achieve is the following pseudo code: if product.name (the string) is contained in the image_name(path of the image), save the image and associate it with the model, otherwise pass. class Product(models.Model): code = models.CharField(primary_key=True, unique=True, max_length=15, null=False, blank=False) name = models.CharField(max_length=50, null=True, blank=True) brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, null=True, blank=True) price = models.FloatField(null=True, blank=True) image1 = ... image2 = ... or class Image(models.Model): product = models.ForeignKey(Product, ...) name = models.CharField(...) How would I approach this? Maybe a model property? What is the best practice for a problem like this? Can someone point me in the right direction? -
Django + Postgres: could not open extension control file citext.control
Environment(s) Ubuntu 20.04 & Debian 10 with Python 3.8 or 3.7, respectively. Postgresql versions 11, 12, and 14 have been tried. Psycopg2-binary 2.8.0 Overview I'm attempting to install a Django project, and I'm getting this error: psycopg2.errors.UndefinedFile: could not open extension control file "/usr/share/pgsql/extension/citext.control": No such file or directory The psycopg devs informed me this is likely an issue with the postgresql-contrib libraries. Similarly, others have been able to fix this error by installing postgresql-contrib, however, this does not work for me. I've also tried installing postgresql-12. I can see that citext.control is available in /usr/share/postgresql/12/extension/citext.control, so I tried ln -s /usr/share/postgresql/12 /usr/share/pgsql with no effect. I also ran CREATE EXTENSION citext; in Postgres, also without effect. Any support with this would be greatly appreciated, as I was hoping to have this project live already! Thanks so much. Trace Running migrations: Applying core.0043_install_ci_extension_pg...Traceback (most recent call last): File "/home/user/venvs/janeway/lib/python3.8/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedFile: could not open extension control file "/usr/share/pgsql/extension/citext.control": No such file or directory The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 16, in <module> execute_from_command_line(sys.argv) File "/home/user/venvs/janeway/lib/python3.8/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File … -
Data from js to python(django) and vice versa
I have a script which make a calendar and assigns values like date to a cell. I would like to send three arguments to my function in django, such as date, current month, and current year, and get the result back. I would like everything to be done in a loop so that each cell would get a different value. Javascript script: function showCalendar(month, year) { let firstDay = (((new Date(year, month)).getDay() - 1) + 7) % 7; let daysInMonth = 32 - new Date(year, month, 32).getDate(); let tbl = document.getElementById("calendar-body"); // body of the calendar // clearing all previous cells tbl.innerHTML = ""; // filing data about month and in the page via DOM. monthAndYear.innerHTML = months[month] + " " + year; selectYear.value = year; selectMonth.value = month; // creating all cells let date = 1; for (let i = 0; i < 6; i++) { // creates a table row let row = document.createElement("tr"); //creating individual cells, filing them up with data. for (let j = 0; j < 7; j++) { if (i === 0 && j < firstDay) { let cell = document.createElement("td"); let cellText = document.createTextNode(""); cell.appendChild(cellText); row.appendChild(cell); } else if (date > daysInMonth) { … -
PostgreSQL VS MySQL while dealing with GeoDjango in Django
There are multiple Tutorials/Questions over the Internet/Youtube/StackOverflow for finding nearyby businesses, given a location, for example (Question on StackOverflow) : Returning nearby locations in Django But one thing common in these all is that they all prefers PostgreSQL (instead of MySQL) for Django's Geodjango library I am building a project as: Here a user can register as a customer as well as a business (customer's and business's name/address etc (all) fields will be separate, even if its the same user) This is not how database is, only for rough idea or project Both customer and business will have their locations stored Customers can find nearby businesses around him I was wondering what are the specific advantages of using PostgreSQL over MySQL in context to computing and fetching the location related fields. (MySQL is a well tested database for years and most of my data is relational, so I was planning to use MySQL or Microsoft SQL Server) Would there be any processing disadvantages in context to algorithms used to compute nearby businesses if I choose to go with MySQL, how would it make my system slow? -
Django permissions for GET, PUT and DELETE
I am trying to make the PUT and DELETE methods require authentication but I want the GET method to be public. I know I can take the GET method out and put it into its own function but I would need to make another url for it. What would be the best way to approach this? thanks @api_view(['GET', 'PUT', 'DELETE']) @permission_classes([IsAuthenticated]) def getOrUpdateOrDeleteCar(request, pk): if request.method == 'GET': vehicle = Car.objects.get(id=pk) serializer = CarSerializer(vehicle, many=False) return Response(serializer.data) elif request.method == 'PUT': data = request.data car = Car.objects.get(id=pk) car.image=data['image'] car.make=data['make'] car.prototype=data['prototype'] car.year=data['year'] car.serviceInterval=data['serviceInterval'] car.seats=data['seats'] car.color=data['color'] car.vin=data['vin'] car.currentMileage=data['currentMileage'] car.save() serializer = CarSerializer(car, many=False) return Response(serializer.data) elif request.method == 'DELETE': car = Car.objects.get(id=pk) car.delete() return Response('Car Deleted!') -
How to remove form-group from input in Django Crispy?
I'm having trouble rendering a template with Django Crispy. When I add a {{ form.name|as_crispy_field }} Crispy adds me a classless div and another div with the form-group class wrapping my input <div id="div_id_name" class="form-group"> <div class=""> <input type="text" name="name" value="Maria" maxlength="150" class="textinput textInput form-control" required="" id="id_name"> </div> </div> I would like to remove these two divs, and leave only the input. My forms.py looks like this: class ClientForm(forms.ModelForm): class Meta: model = ClientModel fields = ( "name", "email", "birth_date", ) widgets = { "birth_date": forms.TextInput(attrs={"type": "date"}), } def __init__(self, **kwargs): super().__init__(**kwargs) self.helper = FormHelper() self.helper.form_show_labels = False The version of Django Crispy Forms is 1.13.0 and Bootstrap 4.6.0. -
why not executed subprocess ffmpeg in online windows virtual server django?
this is my code: subprocess.run('ffmpeg -i ' + media_in + ''' -ss 00:00:01 -frames:v 1 -vf "scale=w='min(150\, iw*3/2):h=-1'" ''' + image_out, shell=True) image_out is result of a video. My code is executed correctly on localhost and output. Although I installed ffmpeg on a virtual server in the c:/ drive and made the environment settings But in Deploy mode, it does not run on Windows Virtual Server and does not output? Does not run on the my web site Blockquote -
Django: How to access object id with the reverse relationship?
Let's say I have this code: class Recipe(models.Model): item = models.OneToOneField("Item", on_delete=CASCADE) class Item(models.Model): # ... Recipe objects do have an item_id attribute, but Item objects don't have a recipe_id attribute. Is there a way to allow both models to directly access the id of the other side of the relation? Note that for some external reasons (that are not interesting to explain here), I can't access fields by relations, so recipe.id is unavailable to me. Of course, a workaround could be to define a property named recipe_id on the Item object, it works but feels unnatural to me, and a bit repetitive since I need do to it on multiple models. -
Managing helper/utils functions and their sensitive data in django
I am integrating some 3rd party API (say for sending OTP to mobile phones), and I want my system to be FLEXIBLE but SECURE at the same time, consider: Lets suppose right now I am using a vendor named msg91.com for sending SMS/OTP to customers. But in future I might switch to some other vendor (say way2sms.com) for the same service owing to various reasons (say cost/testing/production). I have some helper functions for integrating them consider the pseudo code: if SMS_VENDOR == 'MSG91': msg91_helper_function(): # do some processing specific to vendor # authenticate with msg91 # send SMS/OTP # ------------------------------------------------------------------ elif SMS_VENDOR == 'WAY2SMS': way2sms_helper_function(): # do some processing specific to vendor # authenticate with way2sms # send SMS/OTP I know usually people have a utils.py or helpers.py file in the same django app (usually named common) but the issue is: Each vendor has its own some sensitive data like auth_token that I can't store directly in the helper functions (as code will be shared) What I want: How to I securely store these auth_token like sensitive CONSTANTS while keeping my system flexible First Approach Storing them in .env file (then adding it to .gitignore) and then fetching them as: … -
Django creates Static Folder
When uploading my statics with `collectstatic' on Google Cloud Storage, it does upload the files into the main root of the bucket, instead in a folder called "/static/", so the web on production can't read the statics. How can I create the folder "/static/" and upload the files there on GCS? This are my settings: ALLOWED_HOSTS = ["*"] DEBUG = True INSTALLED_APPS += ["django_extensions", ] DEFAULT_FILE_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" STATICFILES_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" GS_BUCKET_NAME = "static-bucket" GS_MEDIA_BUCKET_NAME = "bucket-name" -
showing ManytoManyField element in a query loop
So I want to show elements in a loop from a class I created, however I don't know how to call the ManyToMany element out, can you help me? class Tag(models.Model): nametag = models.CharField(max_length=200, null=True) class OA(models.Model): tags = models.ManyToManyField(Tag) ... My function: def home(request): objetos = OA.objects.all() return render(request, {'objetos': objetos}) The problem: {% for i in objetos %} ... <tr>{{i.tags.nametag}}</tr> {% endfor %} In this case 'nametag' already has a value so it's not empty. I tried a few things but wasn't able to do much, I need help please. -
Using django models need to update the dropdown dynamically
I am currently using dependent dropdown in Django and updating the dropdown menu content using two models. This works fine for me. But the requirement in my app is now to fetch the content of dropdown menu dynamically on page load from a third party server (which is source of truth for the data). When I add the content to Django models and then use the webpage, the content is static in nature, as in it is not in sync with the third party server's data. What is the best way to update dropdown menu dynamically from a third party server when using models? -
how to use objects.filter() for filtering a dictionary to a POST method in django rest framework
Models.py class Category(models.Model): name = models.CharField(max_length=50,null=False, blank=False) def __str__(self): return self.name class Photo(models.Model): category = models.ForeignKey(Category, on_delete= models.SET_NULL,related_name='category', null= True, blank= False) image = models.ImageField(null= False, blank = False) description = models.TextField(null=True, blank=True) def __str__(self): return self.description Serializers.py class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ['name'] class PhotoSerializer(serializers.ModelSerializer): category = CategorySerializer(many=False) class Meta: model = Photo fields = ['id','category','image','description'] view.py from django.http import response from rest_framework import viewsets from rest_framework import serializers from rest_framework.response import Response from rest_framework.serializers import Serializer from rest_framework.views import APIView from .models import Category, Photo from .serializers import PhotoSerializer class DisplayAllViewSet(viewsets.ModelViewSet): queryset = Photo.objects.all() serializer_class = PhotoSerializer class DisplayCategoryViseViewSet(APIView): serializer_class = PhotoSerializer def post(self, request, format=None): data = self.request.data print(data) category = data['category'] print(category) print(category['name']) name=category['name'] queryset = Photo.objects.filter(category=name) serializer = PhotoSerializer(queryset, many=True) return Response(Serializer.data) urls.py from re import I from django.db import router from django.urls import path from django.conf.urls import include from rest_framework import routers from .views import DisplayAllViewSet, DisplayCategoryViseViewSet router = routers.DefaultRouter() router.register('allImages',DisplayAllViewSet) urlpatterns = [ path('', include(router.urls)), path('category',DisplayCategoryViseViewSet.as_view()), ] In Postman : GET request http://127.0.0.1:8000/gallery/allImages [ { "id": 1, "category": { "name": "Sirsi" }, "image": "http://127.0.0.1:8000/sunset.jpg", "description": "Sunset view point" }, { "id": 2, "category": { "name": "Chickmangluru" }, "image": "http://127.0.0.1:8000/tiger.jpg", … -
Dockerize django app along side with cucumber test
Here is the case. I have simple django app with cucumber tests. I dockerized the django app and it works perfect, but I want to dockerize the cucumber test too and run them. Here is my project sturcutre: -cucumber_drf_tests -feature -step_definitions axiosinst.js config.js package.json cucumber.js Dockerfile package-lock.json -project_apps -common docker-compose.yaml Dockerfile manage.py requirements.txt Here is my cucumber_drf_tests/Dockerfile FROM node:12 WORKDIR /app/src COPY package*.json ./ RUN npm install COPY . . EXPOSE 8000 CMD ["yarn", "cucumber-drf"] (this is how I run my test locally) My second Dockerfile FROM python:3.8 ENV PYTHONUNBUFFERED=1 RUN mkdir -p /app/src WORKDIR /app/src COPY requirements.txt /app/src RUN pip install -r requirements.txt COPY . /app/src And my docker-compose file version: "3.8" services: test: build: ./cucumber_drf_tests image: cucumber_test container_name: cucumber_container ports: - 8000:8000 depends_on: - app app: build: . image: app:django container_name: django_rest_container ports: - 8000:8000 volumes: - .:/django #describes a folder that resides on our OS within the container command: > bash -c "python manage.py migrate && python manage.py loaddata ./project_apps/fixtures/dummy_data.json && python manage.py runserver 0.0.0.0:8000" depends_on: - db db: image: postgres container_name: postgres_db volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=bla - POSTGRES_PASSWORD=blaa If I remove I remove test service and run the tests locally everything is … -
Django need first paragraph
I created model with my posts. file blog/models.py: import datetime from ckeditor.fields import RichTextField from django.db import models class Post(models.Model): name = models.CharField(max_length=250) content = RichTextField() date = models.DateField(default=datetime.date.today) and in db i has this record: <p>First paragraph</p> <p>Second paragraph</p> <p>Third paragraph</p> <p>etc</p> <p>...</p> How I can get result First paragraph ONLY -
Installing locales in docker env not working
I'm trying to use locale.setlocale(locale.LC_ALL, 'ar_AE.UTF-8') In Django app, that running in docker environment, with python:3.9.6-slim But it gives me unsupported locale setting error I tried to install locales in Dockerfile using RUN apt-get install -y locales RUN sed -i -e 's/# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/' /etc/locale.gen \ && sed -i -e 's/# ar_AE.UTF-8 UTF-8/ar_AE.UTF-8 UTF-8/' /etc/locale.gen \ && locale-gen ENV LANG ar_AE.UTF-8 ENV LC_ALL ar_AE.UTF-8 But it didn't fix the problem Anyone know how to solve this please -
Filtering values based on case-when returned values results in a SyntaxError
I have an object snapshot database model, saving some data regarding any arbitrary model in my project: class ObjectSnapshot(Model): user = ForeignKey(to=User, on_delete=SET_NULL, null=True, blank=True) timestamp = DateTimeField(verbose_name=_("Date when the document was generated"), auto_now_add=True) content_type = ForeignKey(ContentType, on_delete=CASCADE) object_id = PositiveIntegerField(verbose_name=_("Id of the referenced object")) content_object = GenericForeignKey("content_type", "object_id") data = JSONField(verbose_name=_("Serialized object"), default=dict, null=False, blank=True) There can be multiple snapshots for the same object (referencing the same object_id and content_type), there are also some snapshots that reference the same "logical object" meaning that e.g. object_id is different but those objects share some field values that denotes that they are the same object (it will be explained better by a query example below). Now I want to write a query retrieving list of those objects, annotated with their "previous" entry. ObjectSnapshot.objects.annotate( previous_id=Subquery( ObjectSnapshot.objects.filter( content_type=OuterRef('content_type'), object_id__in=Case( When( content_type__model='somemodel', then=Subquery( SomeModel.objects.filter( field_name=Subquery( # the `field_name` refers to the same "logical object" SomeModel.objects.filter( id=OuterRef(OuterRef('object_id')), ).values( 'field_name' )[:1] ), ).annotate(ids=ArrayAgg('id')).values('ids')[:1], ), ), default=ArrayAgg(OuterRef('object_id')), output_field=ArrayField(base_field=IntegerField()), ), ).exclude( pk=OuterRef('pk') ).values_list( 'object_id' ).order_by( '-timestamp' )[:1] ) ) Trying to run this query I get: syntax error at or near "ARRAY_AGG" LINE 1: ...g_objectsnapshot"."id")) HAVING U0."object_id" IN ARRAY_AGG(... ^ -
Django models FileField - field.url shows img on screen but gives ```No file``` on download attempts
For an image (or with doing the needed code changes for a different file format), The image appears fine on screen but when I try to download it: Chrome and Edge give Download failed - No file Firefox downloads it when save file is chosen // url -->> django_model_field.url --- model: FileField <a href={url} download="" target="_blank" rel="noreferrer"> <img src={url} alt="img"/> </a> How to fix this, please? Thanks in advance for your help :) -
Change value of field if input is not in choices Django ImportExportModelAdmin
I have this model field as an example: compliance_approve_status = models.CharField(max_length=200, blank=True, null=True, default=None, choices=review_status_choices) with these choices: for_review = 'FOR REVIEW' approved = 'APPROVED' rejected = 'REJECTED' review_status_choices = [(for_review, 'FOR REVIEW'), (approved, 'APPROVED'), (rejected, 'REJECTED')] A simplified version of fields with choices. I want to be able to make a default value in which if a user imports from a file and puts something other than a 'FOR REVIEW', 'APPROVED' or 'REJECTED', or is NULL, it would default to None. I thought adding a default=None would do it, but it accepts other values in Django's ImportExportModelAdmin. -
How to Use Custom Template Tag in Combination With Django's Built-in "with" Tag?
I have this simple tag: myapp/templatetags/my_filters.py @register.simple_tag def get_bookmark_object(content_type, object_id): return Bookmark.objects.get(content_type=content_type, object_id=object_id) In my template, I want to be able to do this: {% load my_filters %} {% with object as bookmark %} {% with bookmark_object=get_bookmark_object bookmark.content_type bookmark.object_id %} {% if bookmark.content_type.model == 'post' %} {% include 'content/post/object.html' with object=bookmark_object user_bookmark=bookmark %} {% elif bookmark.content_type.model == 'note' %} {% include 'content/note/object.html' with object=bookmark_object user_bookmark=bookmark %} {% endif %} {% endwith %} {% endwith %} I get the error: TemplateSyntaxError at /my-page/ 'with' received an invalid token: 'bookmark.content_type' My question is: How do I use my custom get_bookmark_object template tag in a with statement? An example with code would help me clarify a lot. Reference: Django's with built-in -
How to filter a Django queryset, after it is modified in a loop
I have recently been working with Django, and it has been confusing me a lot (although I also like it). The problem I am facing right now is when I am looping, and in the loop modifying the querryset, in the next loop the .filter is not working. So let's take the following simplified example: I have a dictionary that is made from the queryset like this dict = {chicken: 6, cows: 7, fish: 1, sheep: 2} The queryset is called self.animals for key in dict: if dict[key] < 3: remove_animal = max(dict, key=dict.get) remove = self.animals.filter(animal = remove_animal)[-2:] self.animals = self.animals.difference(remove) key[replaced_industry] = key[replaced_industry] - 2 Now the first time it loops (with fish), the .filter does exactly as it should. However, when I loop it a second time (for sheep), the remove = self.animals.filter(animal = remove_animal)[-2:] gives me an output is not in line with animal = filter. When I print the remove in the second loop, it returns a list of all different animals (instead of just 1). After the loops, the dict should look like this: {chicken: 4, cows: 5, fish: 1, sheep: 2} This because first cow will go down 2 and it is the … -
TypeError: Field 'id' expected a number but got <django.db.models.query_utils.query_utils.DeferredAttribute object
Trying to display Trainee(s) only for a spesific NewHireTraining. I am passging additional context data to a training_details view class to show trainees under that training which are related with foreingkey under Trainee's class. It is returning the location of the attribute id instead of the id value. Will really appreciate help models.py class NewHireTraining(models.Model): location = models.ForeignKey(Location, on_delete=models.CASCADE) program = models.ForeignKey(Program, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) trainer = models.ForeignKey(Trainer, on_delete=models.RESTRICT) start_date = models.DateField() nesting_date = models.DateField() production_date = models.DateField() requested_headcount = models.IntegerField() starting_headcount = models.IntegerField(null=True, blank=True) ending_headcount = models.IntegerField(null=True, blank=True) end_nesting_headcount = models.IntegerField(null=True, blank=True) def __str__(self): return str(self.program) + ' ' + str(self.project) + ' ' + str(self.start_date) class Trainee(models.Model): first_name = models.CharField(max_length=55) last_name = models.CharField(max_length=55) employee_number = models.IntegerField() hire_date = models.DateField() is_term = models.BooleanField(default=False) new_hire_training = models.ForeignKey(NewHireTraining, on_delete=models.CASCADE, default="") def __str__(self): return self.first_name + ' ' + self.last_name views.py class TrainingDetailsView(DetailView): model = NewHireTraining template_name = 'nht/training_details.html' context_object_name = 'training' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['trainees'] = Trainee.objects.filter(new_hire_training = self.model.id) return context Internal Server Error: /training_details/4 Traceback (most recent call last): File "C:\Users\User\Desktop\webprojects\calendar\venv\lib\site-packages\django\db\models\fields_init_.py", line 1823, in get_prep_value return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute' Traceback The above … -
Django Data Aggregation
How would I go about aggregating data from a model and import into a template? I have a model called "RequestAStudent". I want to show a count for absences, tardies, and lateness for each student. See attached screenshot for what I want it to look like in my template. Thanks![Template View][1] class RequestAStudent(models.Model): PERIODS=( ('Academic Network 1', 'Academic Networking 1'), ('Academic Network 2', 'Academic Networking 2'), ) MARK=( ('None', 'None'), ('Present', 'Present'), ('Tardy', 'Tardy'), ('X', 'X'), ('Absent', 'Absent'), ) student = models.ForeignKey(Student, on_delete= models.CASCADE) date_created = models.DateField(auto_now_add=True, null=True) Requesting_Teacher = models.ForeignKey(AdvisoryTeacher, on_delete= models.CASCADE) #AcademicNetwork2 = models.ForeignKey(AdvisoryTeacher, on_delete= models.CASCADE) Period = models.CharField(max_length=18, null=True, choices = PERIODS) teacher = models.ForeignKey(Teacher, verbose_name='Advisory Teacher',default="None", on_delete= models.CASCADE) date_requested = models.CharField(max_length=200, verbose_name='Date for Student Request (Use format MMDDYY)', default="2021-09-16",null=True) attendance = models.CharField(verbose_name='UPDATE ATTENDANCE HERE!',max_length=18, default="None",choices = MARK) #null=True, blank=True, owner = models.IntegerField("Request Owner", blank=False, default=1) def __str__(self): return "" + str(self.student) + ", Teacher: " + str(self.owner) class Meta: unique_together = ["student", "Period", "date_requested"] @user_passes_test(lambda u: u.groups.filter(name='administrators').exists()) def AttendanceByStudent(request): requests = RequestAStudent.objects.all() context={ 'requests':requests, } return render(request, 'attendancebystudent.html',context) I want to output into my template like this: Student Attendance Date Absent Tardy Late +5 -
Custom User Model: No such table exits while creatingsuperuser
I am trying to build a custom user model which I had did successfully in a previous project. But for some reason this is time I am met with this weird error, which I have gone through stackoverflow and find a fix for this. I try to do makemigrations and it shows no migrations to make and I simply do migrate and assume new table is created but then I try to create a superuser and this shows up. So did I miss a step or something? Things that might be informative, I had a previous in built model migrated and trying to create new one by deleting the database file of old one, I have deleted the previous migrations of all other Apps, I have added app and auth_user_model in the settings. Settings.py # Custom Model AUTH_USER_MODEL = "user.CustomUser" # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Custom "home", "user", ] users/models.py from django.db import models from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager class CustomUserManager(BaseUserManager): def create_superuser(self, email, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError( 'Superuser must be assigned to is_staff=True.') … -
Python, Django Issue while running command : python3 manage.py runserver
I am new to Python and Django. This is my first program in Django and trying to use command (python3 manage.py runserver) but getting below issue. Please help -- enter image description here enter image description here