Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django create user profile
I created a user profile model for my system. I created all models and It works perfectly. I have a form and form works too. But when I look user create form from admin page, It doesn't look the same. There are some missing parts like rank, comp_name. How can I fix it? models.py class UserProfile(models.Model): ranks = ( ('xxx', 'xxx'), ... ) comp_name = models.CharField(max_length=200, default="Choose") user_id = models.UUIDField(default=uuid.uuid4(), editable=False, unique=True) username = models.CharField(max_length=500) first_name = models.CharField(max_length=200, default=None) last_name = models.CharField(max_length=200, default=None) password = models.CharField(max_length=50) email = models.EmailField(max_length=254) rank = models.CharField(max_length=200, choices=ranks) forms.py class SignUpForm(UserCreationForm): comp_name = forms.CharField(label='What is your company name?') email = forms.CharField(max_length=254) rank = forms.ChoiceField(label='What is your rank?', choices=UserProfile.ranks) first_name = forms.CharField(max_length=250) last_name = forms.CharField(max_length=250) comp_name = forms.ModelChoiceField(queryset=CompanyProfile.objects.all()) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'comp_name', 'password1', 'password2', 'rank' admin enter image description here -
Django Admin Interface Upload Multiple Images at once
I would like to upload upload up to 10 images at the same time to ImageField or FileField in Django Admin Interface. I know that there is some JavaScript libraries like Dropzone.js but I don't know how to use it in admin interface -
Django Models how to add unique constraint
Unsimilar to for example this case I am trying to allow only one entry in a database for one user: class Station(models.Model): serial = models.CharField("serial", max_length = 31, unique = True) user = models.ForeignKey(User, on_delete = models.CASCADE, ) What I want is that one user can only have zero or one Station (serial). -
How to avoid abusing TRY EXCEPT when check API parameters requested?
I have an API which is a POST This API has a lot of optional parameters, so obviously, my code would be something like this: input_data = request.data try: optional_parameter_1 = input['parameter_1'] except: **do sth ............................................. try: optional_parameter_2 = input['parameter_1'] except: optional_parameter_2 = something ................................................ In my code there are a lot of it, and I think I am abusing try and except too much. I wonder if there is any alternatives way which is short, simple and clean then using try and except -
(Django - Python) "Select a valid choice. That choice is not one of the available choices." - Django Admin Error
I have to register two models on the site administration of Django but when I choose the element and click on save I get this error: Select a valid choice. That choice is not one of the available choices. I put here my code of: - models.py from django.db import models from django.contrib.auth.models import User from djongo.models.fields import ObjectIdField class Profile(models.Model): _id = ObjectIdField() user = models.ForeignKey(User, on_delete=models.CASCADE) class Order(models.Model): _id = ObjectIdField() profile = models.ForeignKey(Profile, on_delete=models.CASCADE) datetime = models.DateTimeField (auto_now_add=True) price = models.FloatField() quantity = models.FloatField() - admin.py from django.contrib import admin from .models import Order, Profile admin.site.register(Order) admin.site.register(Profile) Can you help me please, thanks to everyone! -
How can I check if an user is superuser in django
I'm listing registered users on a ListView page and I'm trying to show if user is superuser or not. My main user is created with "manage.py createsuperuser" command and I'm sure it is a superuser beacuse I've checked from admin panel too. When I try to print if it is superuser or not my code always shows a "False" output. Here are my codes: views.py @method_decorator(staff_member_required, name='dispatch') class Uyeler(ListView): model = User paginate_by = 40 ordering = ['-pk'] template_name = "panel/uyeler.html" and in template file: {% for obj in object_list %} {% if obj.is_superuser %}SuperUser {% else %} Not SuperUser {{ obj.is_superuser }} {%endif%} {% endfor % And my html output is "Not SuperUser False" for all users including my superuser account. Any ideas? -
Creating Gunicorn docker file with Postgress without DB name error
I'm building my container like this FROM python:3.7.4-alpine3.10 ADD mediadbin/requirements.txt /app/requirements.txt RUN set -ex \ && apk add --no-cache --virtual .build-deps postgresql-dev build-base python3-dev gcc jpeg-dev zlib-dev\ && python -m venv /env \ && /env/bin/pip install --upgrade pip \ && /env/bin/pip install --no-cache-dir -r /app/requirements.txt \ && runDeps="$(scanelf --needed --nobanner --recursive /env \ | awk '{ gsub(/,/, "\nso:", $2); print "so:" $2 }' \ | sort -u \ | xargs -r apk info --installed \ | sort -u)" \ && apk add --virtual rundeps $runDeps \ && apk del .build-deps ADD mediadbin /app WORKDIR /app ENV VIRTUAL_ENV /env ENV PATH /env/bin:$PATH EXPOSE 8000 CMD ["gunicorn", "--bind", ":8000", "--workers", "3", "mediadbin.wsgi:application"] which works, but when I run Django's makemigrations to populate my DB in the container I'm getting an error django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? my env file look like this DJANGO_SECRET_KEY=somekey DEBUG=True DJANGO_ALLOWED_HOSTS=* DATABASE_ENGINE=django.db.backends.postgresql_psycopg2 DATABASE_NAME=django_db DATABASE_USERNAME=somename DATABASE_PASSWORD=somepass DATABASE_HOST=127.0.0.1 DATABASE_PORT=5432 DJANGO_LOGLEVEL=info I found here that I can't connect to localhost inside of the container and I should set service name for the db to connect to, but I'm not using a yml file so … -
How to assign a permissions system to my roles with django?
So I have two models which depict roles. class GlobalRole(models.Model): """ Represents a Global-Role object. Roles have their own: - Hex Color Code [Integer Representation] - Name [&] - Permissions. """ objects = RolesManager() id = models.BigAutoField(primary_key=True, db_index=True, editable=False, auto_created=True) name = models.CharField(max_length=512, db_index=True) hex_color_code = models.IntegerField(db_index=True) position = models.IntegerField(db_index=True) parent = models.ForeignKey('api_backend.DataSheetsCluster', on_delete=models.CASCADE, db_index=True, editable=False) created_at = models.DateTimeField(auto_now=True, editable=False, db_index=True) REQUIRED_FIELDS = [name, parent, position] class LocalRole(models.Model): """ Represents a Local-Role object. An one-to-one related model with Global role. Roles have their own: - Hex Color Code [Integer Representation] - Name [&] - Permissions. Role permissions for individual datasheets override global parent permissions. """ objects = RolesManager() id = models.BigAutoField(primary_key=True, db_index=True, editable=False, auto_created=True) global_role = models.OneToOneField('api_backend.GlobalRole', on_delete=models.CASCADE) parent = models.ForeignKey('api_backend.DataSheet', on_delete=models.CASCADE, db_index=True) created_at = models.DateTimeField(auto_now=True, editable=False, db_index=True) REQUIRED_FIELDS = [global_role, parent] Roles have a set of permissions of their own, and can be assigned to users. Roles have a position field. The lowest position depicts the user's highest role, and vice versa. The permissions for the user's highest role is taken as the user's permissions. I have this system of clusters and datasheets, too. Clusters can contain multiple datasheets. So now roles can be created for clusters, and these … -
Serve voice files like with Youtube features
I want server large voice files, and I need to make them like Youtube; it means the client can have a seek bar, all voice files should have chunked and can be accessed while playing. Like I want to get in the middle of a voice without getting the whole file. Any solutions? Any keyword can help me? -
Cross-Origin Request Blocked Django and React
I have installed pip install django-cors-headers still not working added into the settings.py file INSTALLED_APPS = [ ... 'corsheaders', ... ] MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] Django Rest Framework -
Django: Heroku server status 500 when debug=False
I deployed my application to Heroku and I keep getting a 500 error (Server Error (500)) when I set debug =False. I have researched every stackoverflow article about this subject but I cant manage to find the solution. I assume that there is a problem inside my Settings file somewhere. import os import django_heroku import dj_database_url from decouple import config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'planning.apps.PlanningConfig', 'kalender.apps.KalenderConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django_filters', 'bootstrap3', 'django_popup_view_field', 'access_tokens', 'django_expiring_token', 'django_cleanup', # this one automatically deletes old profile pictures after a new one has been set. 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'storages' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'django_project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True WSGI_APPLICATION … -
trying to run python script from a django form can any one please help me out.iam new to django
creating a simple ui which takes 2 files as input and if we press submit button then trying to run script.py(which is python script) and render output on screen or some output folder #forms.py from django import forms class AwsForm ( forms.Form ): Aws_SourceFile = forms.FileField () Aws_RefernceFile = forms.FileField () #views.py from django.shortcuts import render from .forms import AwsForm import subprocess def home_view(request): context = {} context [ 'form' ] = AwsForm () return render ( request , "home.html" , context ) def submit_view(request): info = request.POST [ 'info' ] def my_view(request): if request.method == 'GET': form = AwsForm () else: if form.is_valid (): info = request.POST [ 'info_name' ] output = script_function ( info ) return render ( request , 'myapp/home.html' , { 'info': info , 'output': output , } ) return render ( request , 'myapp/home.html' , { 'form': form , } ) def script_function(post_from_form): print ( post_from_form ) return subprocess.check_call ( [ '\script_18122020.py' , post_from_form ] ) #urls.py from django.contrib import admin from django.urls import path from myapp.views import home_view, submit_view urlpatterns = [ path('', home_view ), path('submit', submit_view), ] #home.html {% block main_content %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> … -
Filter the foreign key in generic CreateView
I have a DetailView list for Course Model. path('<slug:url>/', views.CourseDetailView.as_view(), name='course'), path('<slug:url>/update', views.CourseUpdateView.as_view(), I do have one more Model for Enrollment. And i want to format my URL something like this path('<slug:url>/enroll', views.EnrollmentCreateView.as_view(), Above, I used CreateView for enrollemnt. I have 3 main model, Course, Batch and Enrollment model, class Course(models.Model): name = models.CharField(max_length=100, unique=True) url = models.CharField(max_length=100, unique=True) description = models.TextField(blank=True, null=True) duration = models.IntegerField(blank=True, null=True) fee = models.IntegerField(blank=True, null=True) image = models.ImageField(default='course.jpg', upload_to='course_pics') order = models.IntegerField(blank=True, null=True) def __str__(self): return f'Course {self.name}' class Batch(models.Model): class Meta: unique_together = (('course', 'batch_no'),) course = models.ForeignKey(Course, on_delete=models.CASCADE) batch_no = models.IntegerField(blank=True) centre = models.ForeignKey(Centre, on_delete=models.CASCADE) start_date = models.DateField() end_date = models.DateField() instructor = models.ForeignKey( CustomUser, on_delete=models.CASCADE, related_name='instructor_name', limit_choices_to={'role': 'staff'}) def __str__(self): return f'Batch: {self.batch_no} ({self.start_date} - {self.end_date})' class Enrollment(models.Model): class Meta: unique_together = (('batch', 'student'),) batch = models.ForeignKey(Batch, on_delete=models.CASCADE) student = models.ForeignKey( CustomUser, on_delete=models.CASCADE, limit_choices_to={'role': 'student'}) completed_date = models.DateField(blank=True, null=True) certificate_no = models.CharField(max_length=30, blank=True) payment_reference = models.CharField( max_length=50, blank=True, null=True) payment_notes = models.CharField( max_length=50, blank=True, null=True) def __str__(self): return f'{self.batch.course.name}: Student: {self.student.username}' I want to pass the course url from the path path('<slug:url>/enroll', views.EnrollmentCreateView.as_view()) to the EnrollmentCreateView, so that I can filter the batch that belongs to particular course. I dont know … -
Django-Rest-Framework Serializer validate data return None
I'm having trouble getting data in validate() function of Serializer for my API. I'm using django AbstractUser Model Django = "^3.1.3" djangorestframework = "^3.12.2" My serializers.py: class ChangePasswordSerializer(serializers.Serializer): old_password = serializers.CharField(max_length=255, required=True) new_password = serializers.CharField(max_length=255, required=True, write_only=True) new_password_confirm = serializers.CharField(max_length=255, required=True, write_only=True) def validate_old_password(self, value): if not self.context['user'].check_password(value): # got data raise serializers.ValidationError("Incorrect Old Password") def validate_new_password(self, value): try: # validate the password and catch the exception validators.validate_password(password=value) # got data # the exception raised here is different than serializers.ValidationError except exceptions.ValidationError as e: raise serializers.ValidationError(list(e)) def validate_new_password_confirm(self, value): try: # validate the password and catch the exception validators.validate_password(password=value) # got data # the exception raised here is different than serializers.ValidationError except exceptions.ValidationError as e: raise serializers.ValidationError(list(e)) def validate(self, data): if data['new_password'] != data['new_password_confirm']: # both return None raise serializers.ValidationError({'message': ["Your password and confirmation password do not match."]}) return data views.py: class change_password(APIView): def post(self, request): received_json_data=request.data user = request.user serializer = ChangePasswordSerializer(data=received_json_data, context={'user': user}) if serializer.is_valid(): user.set_password(received_json_data['new_password']) # got new_password return JsonResponse({ 'message': 'Password changed.' }, status=200) else: return JsonResponse({'message':serializer.errors}, status=400) The problem is in validate(self, data) the data currently return as OrderedDict([('old_password', None), ('new_password', None), ('new_password_confirm', None)]) so it skipped the custom validation, but in other validation methods … -
Bulk create with multi-table inheritance models
I'm using multi-table inheritance models. from django.db import models class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) class Restaurant(Place): serves_hot_dogs = models.BooleanField(default=False) serves_pizza = models.BooleanField(default=False) class Cinema(Place): sells_tickets = models.BooleanField(default=False) sells_popcorn = models.BooleanField(default=False) class Coffee(Place): sells_tea = models.BooleanField(default=False) I have a view that creates several different models: items = [ Restaurant(...), Restaurant(...), Restaurant(...), Cinema(...), Cinema(...), Coffee(...), Coffee(...), # + 1.000 other items ] for item in items: item.save() Obviously, this is really inefficient since it creates a lot of queries. Unfortunately, Django doesn't provide a bulk-create method for multi-table inheritance yet (there is an open pull request for it). What is the best way to optimize this code? Do I have to write a raw SQL query or is there another way? -
ImportError while rendering PHP files through Django Views
For code reusability, I'm trying use the previously created php file to render in django when I access the url.I have tried some installing django_php module as mentioned Here I'm getting the following error while rendering InvalidTemplateLibrary at / Invalid template library specified. ImportError raised when trying to load 'django_php.templatetags.php': No module named 'popen2' Any help is appreciated. Thank you. -
config Tiny Editor in django
i use tiny editor and i wanna use 'js': ['path/to/editor.js', 'path/to/plugin.js'] instead of 'js': ['//cdn.ckeditor.com/4.14.0/standard/ckeditor.js'] now don't know how i can, I copy code from cdn to my static path : static/jquery/my-js/script.js Try to use this path instead of cdn but it didn't work, try to override the source but i can't. how to load from static and change it main code? and i don't want use script in html i config it in my settings.py. how it possible?? thanks. -
Django OperationalError table has no column named user_id
I created a signup system. Firstly it was working but then I added name and surname to my models then it stopped work. I delete all migrations and I apply makemigrations and migrate. Bu I get an error. I use Sqlite. OperationalError at /admin/auth/user/add/ table register_companyprofile has no column named user_id models.py class CompanyProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default=None) comp_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) comp_name = models.CharField(max_length=200) class UserProfile(models.Model): ranks = ( ('analyst', 'Analyst'), ('seniorAnalyst', 'Senior Analyst'), ('lead', 'Lead'), ('manager', 'Manager'), ('seniorManager', 'Senior Manager'), ('director', 'Director'), ('regionalDirector', 'Regional Director'), ('cfo', 'Chief Financial Officier'), ) companies = () comp_name = models.CharField(max_length=200, choices=companies, default="Choose") user_id = models.UUIDField(default=uuid.uuid4(), editable=False, unique=True) username = models.CharField(max_length=500) name = models.CharField(max_length=200, default=None) surname = models.CharField(max_length=200, default=None) password = models.CharField(max_length=50) email = models.EmailField(max_length=254) rank = models.CharField(max_length=200, choices=ranks) forms.py class SignUpForm(UserCreationForm): comp_name = forms.CharField(label='What is your company name?') email = forms.CharField(max_length=254) rank = forms.ChoiceField(label='What is your rank?', choices=UserProfile.ranks) name = forms.CharField(max_length=250) surname = forms.CharField(max_length=250) class Meta: model = User fields = ('username', 'name', 'surname', 'email', 'comp_name', 'password1', 'password2', 'rank') views.py def signup(request): form_class = SignUpForm if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() # load the profile instance created by the signal user.save() raw_password = … -
Working with composite primary key and foreign keys in django project with legacy database
In this question, e4c5 suggests updating tables in the legacy database with a single primary key to work with Django. However, every table referencing the updated table will be using the composite primary key as reference and will therefore not work in Django. Is there a way to either update the tables so they would use the new primary key, or a workaround for this? -
django.core.exceptions.FieldError: Related Field got invalid lookup: icontains
I am creating a Cascading dropdown and keep getting a Related Field got invalid lookup: icontains error. I have tried several suggestions under this subject on Stackoverflow but none seems to address my case. I am using autocomplete I have two models. class BusinessCategory(BaseModel): name = models.CharField(max_length=255, verbose_name=_('Category name')) status = models.BooleanField(default=True) class SubBusinessCategory(BaseModel): business_category = models.ForeignKey(BusinessCategory, on_delete=models.CASCADE) name = models.CharField(max_length=255) status = models.BooleanField(default=True) And this is the setup of how it has been used in my model forms class BusinessBoardingForm(forms.ModelForm): """On boarding business form for Business Application""" category = forms.ModelChoiceField( queryset = BusinessCategory.objects.all(), label=u"Business Category", widget=ModelSelect2Widget( data_url='/admin/directories/businesscategory/autocomplete/', model=BusinessCategory, search_fields=['name__icontains'], ) ) # This one works alright. sub_category = forms.ModelChoiceField( queryset = SubBusinessCategory.objects.all(), label=u"Sub Category", widget=ModelSelect2Widget( data_url='/admin/directories/subbusinesscategory/autocomplete/', model=SubBusinessCategory, search_fields=['business_category__name__icontains'], dependent_fields={'business_category': 'name'}, max_results=500, ) ) I am getting the lookup error at the Sub category. What am I missing? -
Where can i find projects or more information using Django channel3?
I am trying to implement a live notification system using Django. But all tutorials seems to be in django-channels2. Can anyone suggest books or tutorials in other than documentation? -
Is there any one to assist me with my django project deployment in ubuntu server
I am using the ubuntu server VPS, placed the Django project in /var/www - name as srv. srv is a folder and inside srv my project name "ems" is placed. it is fully running using python3 manage.py runserver myip:8000. but when I configured site at cd /etc/apache2/sites- available/ems.conf. and below is my content under ems.conf <VirtualHost *:80> ServerAdmin me@amritshahi.com ServerName amritshahi.com ServerAlias www.amritshahi.com DocumentRoot /var/www/srv Alias /static /var/www/srv/ems/static <Directory "/var/www/srv/ems/static"> Options Indexes FollowSymLinks Order allow,deny Allow from all Require all granted </Directory> Alias /media /var/www/srv/ems/media <Directory "/var/www/srv/ems/media"> Options Indexes FollowSymLinks Order allow,deny Allow from all Require all granted </Directory> ErrorLog ${APACHE_LOG_DIR}/ems_error.log CustomLog ${APACHE_LOG_DIR}/ems_access.log combined WSGIDaemonProcess ems python-home=/var/www/srv/ems/venv python-path=/var/www/srv/ems WSGIProcessGroup ems WSGIScriptAlias / /var/www/srv/ems/ems/wsgi.py <Directory /var/www/srv/ems/ems> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> When I enable my site using : a2ensite ems.conf it sucefully enabled and restart apache server . but I get the error message in the page as : Internal Server Error, The server encountered an internal error or misconfiguration and was unable to complete your request.Please contact the server administrator at me@amritshahi.com to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be … -
Celery - How to get the task id for a shared_task?
I've looked at questions like this one and a dozen others. But none of them seems to be working. I've a shared_task like this one, which doesn't return anything: @shared_task def rename_widget(widget_id, name): w = Widget.objects.get(id=widget_id) w.name = name w.save() I've tried self.request.id and current_task.request.id but they both returned None. My celery version is 5.0.4 and django version is 3.1.1. I'm using Rabbitmq as messenger. -
Iterate Over objects in an m2m_changed signal
I have the following setup: order/signals.py @receiver(m2m_changed, sender=Order.deliverer.through) def m2m_changed_order_deliverer(sender, instance, **kwargs): if kwargs['action'] == 'post_add': instance.deliveringstatus = True instance.save() #changes the order model's, on-delivery status to TRUE once an order_deliverer has been appended onto its ManyToManyField. account-app/signals.py @receiver(m2m_changed, sender=Order.order_deliverer.through) def m2m_changed_deliverer_profile(sender, instance, **kwargs): if kwargs['action'] == 'post_add': #print(instance.order_deliverer.through.objects.all()) obj = instance.order_deliverer.through.objects.last().deliverer obj.busy = True obj.save() #alters the deliverer's profile status to busy. 1. My problem is on handling iterations. If the order's order_deliverer field has multiple user objects, the account signal is only handled on the last object. 2. How do I iterate & alter each deliverer's profile. I'm thinking of looping via 'for' but I first need to be able to fetch individual user objects rather than first or last. -
How to use multiple column from one model
I have three model the user, major, and topic. every user related to one major and each user can have multiple topic. My issue is I want to make sure topic only displayed to user with related major. For example only user with math major can create and see math topic. I have to tell django "This topic is made by math major and only math major can see it." Right now my plan is when user create topic, I want the topic remember the user and what is the user's major.I can save the user who create the topic but I cannot save the major of that user who create the topic to get the current user I use this package class Profile(AbstractUser): # Extra Few New Fields for django user model email = models.EmailField(_("Email Address"), max_length=254, unique=True) major = models.ForeignKey(Major, verbose_name=_("Major Name"), on_delete=models.SET_NULL, null=True) student_id = models.CharField(_("Student ID"), max_length=50, null=True, blank=True) class Topic(models.Model): name = models.CharField(_("Name"), max_length=400) major = models.ForeignKey(Major, verbose_name=_("Major Name"), on_delete=models.SET_NULL, null=True, blank=True) created_by = CurrentUserField(blank=True, null=True, on_delete=models.SET_NULL, related_name="created_by") class Major(models.Model): kode = models.CharField(_("Kode Prodi"), max_length=5, unique=True) name = models.CharField(_("Major Name"), max_length=250) status = models.BooleanField(_("major Status"), default=True, help_text="check the box to make major active")