Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Model method separation of concern
Toy example: In my Django project, I have two apps: Core and Blog Core app provides users functionality; User model, login logout, register etc Blog app provides blogging functionality; Blogs, Comments, Categories etc The subject of interest are the models: # core/models.py class User(models.Model): firstName = models.CharField(max_length=100) lastName = models.CharField(max_length=100) email = models.EmailField() ... # blog/models.py class BlogPost(models.model): title = models.CharField(max_length=100) post = models.TextField() owner = models.ForeignKey('core.User', on_delete=models.CASCADE) ... I'm using DRF and for one of my ViewSets in which I return a list of all BlogPosts for the currently logged in user. For this, I need to create a QuerySet I can create a model method on the user object like so: # core/models.py class User(models.Model): ... def viewable_blogs(self): return BlogPost.objects.filter(owner=self.id) And simply use it like this: class BlogPostViewSet(viewsets.ModelViewSet): serializer_class = BlogPostSerializer def get_queryset(self): return self.request.user.viewable_blogs.all() This seems quite wrong to me and makes me a little uncomfortable since it breaks encapsulation / Seperation of Concern. i.e The User Model should know nothing about other models. I come from other frameworks like express, springboot etc, I'd create a BlogService and put the functionality of viewable_blogs in there: class BlogPostViewSet(viewsets.ModelViewSet): serializer_class = BlogPostSerializer def get_queryset(self): return BlogService.getBlogsForUser(self.request.user) Is there a … -
How do I control what authenticated users can see in Django?
Trying to hide a view to create a restaurant from anyone other than a restaurant Owner. Used examples shown using groups and testing whether a user is in that group or not but nothing seems to work. views.py def is_owner(user): if user.objects.filter(name="Owner").exists(): return True class CreateRestaurantView(generic.CreateView): form_class = CreateRestaurantForm success_url = reverse_lazy('home') template_name = 'signup.html' @login_required def create_restaurant(request): if is_owner == True: if request.method == "POST": form = CreateRestaurantForm(request.POST) if form.is_valid(): restaurant = form.save(commit=False) restaurant.Restaurant_Owner = request.user restaurant.save() return redirect('restaurant_list') else: form = CreateRestaurantForm() return render(request, 'create_restaurant.html', {'form': form}) else: return render(request, 'home.html') forms.py signup form for Owners class OwnerCreationForm(forms.ModelForm): error_messages = { 'password_mismatch': _("The two password fields didn't match."), } password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput) password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput, help_text=_("Enter the same password as above, for verification.")) class Meta: model = User fields = ("username",) def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) return password2 def save(self, commit=True): user = super(OwnerCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() group = Group.objects.get(name='Owner') user.groups.add(group) return user I'm trying to get the view to show the create_restaurant form when a user belongs to the "Owner" group but the function to test … -
How do I make an ArrayField using MongoEngine?
There isn't an ArrayField option in mongoengine's documentation. Here it is: http://docs.mongoengine.org/guide/defining-documents.html I'm going crazy over how something like that isn't named ArrayField. Is it even possible to do an ArrayField using mongoengine? -
Django Cannot Import Local Module During Migrations
In my project i've got two custom objects, defined in a local fields.py file & blocks.py file. I import them in my models.py as such: from . import fields as blockfields from . import blocks and when running migrations, the autogenerated migrations look like this: import PROJECTNAME.fields import blocks and since blocks isnt in the local scope of the migrations folder, it throws an error. If i manually change it to "import PROJECTNAME.blocks as blocks" then it runs fine, but it'd be silly to have to do that every time. Any thoughts? -
Use two models in ListView
I have a ListView for every budget category in my list of transactions. For each of these views, I'd like to show the actual budget for this category. For instance, my Bill budget has sub budgets for rent, insurance, phone, etc which is stored in a separate model from the transactions. The current ListView just sends the transactions filtered by budget type: class BillListView(ListView): model = Transaction template_name = 'budget/base_transactions.html' context_object_name = 'transactions' paginate_by = 10 queryset = Transaction.objects.filter(budget_type__exact='bill') Is there a way to send the sub budget data from my budget database as well so I can display it at the top of the template? -
。。。。。。。。。。。。。。。。。。。。。。 [on hold]
from django.utils import timezone from django.utils.text import slugify class Article(models.Model): STATUS_CHOICES = (('draft','草稿'),('publish','出版')) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='articles') title = models.CharField(max_length=200) # slug和publish唯一 slug = models.SlugField(max_length=200,unique_for_date='publish',allow_unicode=True) body = models.TextField() # 对时区敏感 publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=50,choices=STATUS_CHOICES,default='draft') class Meta: ordering=('-publish',) def __str__(self): return self.title def save(self, force_insert=False, force_update=False, using=None, update_fields=None): if not self.slug: self.slug = slugify(self.title) super().save() save doesn't work -
How to fix error deploying existing Django app to Elastic Beanstalk? "Your WSGIPath refers to a file that does not exist"
Overview I built a Django application on my machine that runs locally using: python manage.py runserver I want to deploy it to AWS Elastic Beanstalk to be publicly visible. I used pip to install the eb cli and ran eb init and configured all my settings. When I zip up and deploy my code to the AWS environment I get an error about my wsgi.py file: Your WSGIPath refers to a file that does not exist. I've already looked at other questions here on SO and looked at my project structure (see below), my .gitignore and .ebignore files, I've restarted my environment and tried a variety of paths for the wsgi.py file. Project Structure fresh_air/ ------------------> This is the folder that I zip up \ -- .ebextensions \ -- django.config \ -- .elasticbeanstalk \ -- config.yml \ -- some other auxiliary apps that assist the main app \ -- fresh_air/ --------------> My main app \ -- static/ \ -- __init__.py \ -- settings.py \ -- urls.py \ -- views.py \ -- wsgi.py \ -- .ebignore (empty file, just there to overwrite .gitignore) \ -- .gitignore \ -- manage.py \ -- requirements.txt django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: fresh_air/wsgi.py config.yml branch-defaults: default: environment: … -
How could i set the value from a function in django
I am developing a little project in django, i am new with this amazing framework. My question is: There is a way to set a value from my database from a function, there is a example: I am trying to modify the existencia to False with this: def delete_clasification(request, id_category): clasificacion = Clasificacion.objects.get(id=id_category) if clasificacion.existencia == True: clasificacion.existencia = False return redirect('adminview:clasification') But i think this is not the correct way to do it. This is my url: url(r'^delete_clasification/(?P<id_category>\d+)/$', delete_clasification, name='delete_clasification'), I am just trying that when i go to that url, the value from "clasificacion.existencia" change to False, and just that... If you can help me with this thing, i appreciate. Thank you! -
Is there a Debug Dashboard like Laravel Telescope for Django?
I need to monitor some request and queries like I do easy with Laravel Telescope, is there something like it for Django? -
GAE, from tastypie import api causes "NotImplementedError: Only tempfile.TemporaryFile is available for use"
Need some help on this Tastypie error on Google app engine. The code worked fine on GAE for long time. Suddendly, it has some weird error when import tastypie api. Not sure if due to mismatch of django, tastypie and python version. ----my_api.py---- from django.conf import settings from django.conf import urls from tastypie import api >>>> cause problem <<<< ----Log file---- .... File .../google3/third_party/py/tastypie/api.py", line 11, in <module> from tastypie.resources import Resource File ...google3/third_party/py/tastypie/resources.py", line 22, in <module> from django.contrib.gis.db.models.fields import GeometryField File ...python27/python27_dist/lib/python2.7/ctypes/util.py", line 90, in _findLib_gccfdout, ccout = tempfile.mkstemp() File ...python27/python27_dist/lib/python2.7/tempfile.py", line 45, in PlaceHolder raise NotImplementedError("Only tempfile.TemporaryFile is available for use") NotImplementedError: Only tempfile.TemporaryFile is available for use -
Trying to run development server on HTTPS but certifcate not found
I am trying to run the development using HTTPS to have it have a secure connection. The issue I run into is FileNotFoundError: No such file or directory: '/tmp\\cert.crt' I have done: pip install django-extensions Werkzeug pyOpenSSL Than I have set my settings in my settings.py file to this: CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_HTTPONLY = True SESSION_COOKIE_HTTPONLY = True SECURE_SSL_REDIRECT = True and I have also added this line here: 'django_extensions' to my installed Apps and when I run this line python manage.py runserver_plus --cert /tmp/cert I get the error -
ValueError: Related model 'referrals.Referral' cannot be resolved
I am getting the error shown in the title when i tried to run python manage.py migrate on my heroku server (migrate worked fine locally). Full traceback: Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying engine.0051_userprofile_referral... OK Applying engine.0052_auto_20190414_0131...Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 234, in handle fake_initial=fake_initial, File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 249, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 507, in alter_field new_db_params = new_field.db_parameters(connection=self.connection) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/fields/related.py", line 966, in db_parameters return {"type": self.db_type(connection), "check": self.db_check(connection)} File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/fields/related.py", line 963, in db_type return self.target_field.rel_db_type(connection=connection) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/fields/related.py", line 878, in target_field return self.foreign_related_fields[0] File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/fields/related.py", line 632, in foreign_related_fields return tuple(rhs_field for lhs_field, rhs_field in … -
Obtain list of files from input
I have this input <input type="file" id="file" name="file" accept="image/*" multiple> this allow the user select several images and I need to pass all of them to my FormData so I do this: var formdata = new FormData(); var files = $('#file')[0].files[0]; formdata.append('file',files); But that only take the first image from de list, How can i take all the images and store all of them in var files? Thanks in advance -
Sending POST data using JQUERY UI to Django
I'm following the example provided in the JQUERY UI documentation to create a dialog form. I have method=POST and action= "{% url 'example:new_article' %}" in the form, so I recon that the form should be submitted when I click on the "Add Article' button. Am I missing something? I know that with AJAX I would do something along the lines of $.ajax({url: new_article} Is there something similar for JQUERY? I've been looking around, but can't find an example that shows the correct way of sending POST data to Django views. js <script> $( function() { var dialog, form, exampleName = $( "#exampleName" ), articleTitle = $( "#articleTitle" ), articleLink = $( "#articleLink" ), allFields = $( [] ).add( exampleName ).add( articleTitle ).add( articleLink ), tips = $( ".validateTips" ); function updateTips( t ) { tips .text( t ) .addClass( "ui-state-highlight" ); setTimeout(function() { tips.removeClass( "ui-state-highlight", 1500 ); }, 500 ); } function checkLength( o, n, min, max ) { if ( o.val().length > max || o.val().length < min ) { o.addClass( "ui-state-error" ); updateTips( "Fields cannot be empty or be longer than 255 characters"); return false; } else { return true; } } function addArticle() { var valid = true; … -
Django ModelForm initial not working for textarea
I have a django ModelForm, I'm trying to populate it with initial values from my views, all fields are populated except for the textarea field. I have no idea why. Any help is appreciated. Thanks! views.py name = 'Testing123' private = True notes = 'JUST CHECKING' ctx['header_form'] = NewTemplateForm(initial={'name': name, 'private': private,'notes:': notes}) private is a BooleanField, initial works even for that name is populated notes is the only field that isn't being populated. -
django variable available to all the views
With context_processors it' s easy to define a callable which results variables available to all the templates. Is there any similar technique which makes a variable available to all the views? Is that somehow possible? Maybe with some workaround? Django: 2.2 Python: 3.5.3 . -
localhosted Chat Apps on Chrome doesn't work properly DJANGO
localhosted Chat Apps on Chrome doesn't work properly DJANGO i am developing a project which is a chat room app which runs on localhost , chrome doesn't show up messages on android but it does on desktop idk why ? i searched and found to change site permissions to send updates but the site isn't found in the permissions section because its a localhost i guess the project which i develop chat app in a video -
Passing Model objects into function from viewset
I have a Django viewset, where I have a function, that sends an email, whenever the viewset, is used. I override the create function, to send the email, where I have a function, that sends the email to the user. I want to pass in some arguments, to the function, to display in the email (done with Django's template engine) class ContactRequestViewSet(viewsets.ModelViewSet): queryset = ContactRequest.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = ContactRequestSerializer def create(self, request, *args, **kwargs): response = super(ContactRequestViewSet, self).create(request, *args, **kwargs) send_email() return response #function to send email def send_email(): htmly = get_template('email.html') d = {'company_name': 'dodo'} #i want this dictionary, to contain the attributes from the viewset send_mail( subject='Test email', message='', from_email='test@email.com', recipient_list=['test@email.com'], html_message= htmly.render(d) ) right now I just have a sample placeholder as d but here I want to pass in attributes from the serializers/model, that the user provided, I tried passing in the serializer, and accessing its attributes, but I don't know how to do this the proper way -
Creating a new object when assigning from dropdown
In the Django admin, you can click the green "+" icon next to a dropdown field and create a new object instead of choosing one from the dropdown menu. I'd like to implement this on my site, but I'm not sure of the process going on here. How does the admin site return the new object to the dropdown menu after it's created? -
How to edit text on a Django class based form
I am trying to edit the text rendered to the form in the template. But I cannot find a way to do it in class based views and only in function based views. In the image above, I want to change the text 'image' to 'thumbnail'. Views (Both edit and create view): class PostCreateView(LoginRequiredMixin, PostEdit, CreateView): fields = ['title', 'youtube_url', 'text', 'image', 'job_type'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class PostUpdateView(LoginRequiredMixin, PostEdit, UpdateView): fields = ['title', 'youtube_url', 'text', 'image', 'job_type'] HTML: <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <input type="submit" class="btn btn-success" value="Publish"> </form> Thanks guys. -
How To Correctly Define 'get_absoute_url' in Django?
Can you please help me to correctly define the get_absolute_url? Right now I'm been redirected to '.../product/32949492331', however the url should look like: '.../product/1', '.../product/2', etc. Here is models.py: class Product(models.Model): product_id = models.CharField(max_length=50) pub_date = models.DateTimeField(default=datetime.now) title = models.CharField(max_length=255) url = models.TextField() price = models.FloatField() def get_absolute_url(self): return reverse('detail', kwargs={'product_id': self.product_id}) views.py: def detail(request, product_id): product = get_object_or_404(Product, pk=product_id) return render(request, 'product/detail.html', {'product': product}) urls.py: urlpatterns = [ path('add', views.add, name='add'), path('<int:product_id>', views.detail, name='detail'), ] This is a follow up to my previous question. Thanks in advance for your help! -
How to create Django model with FK field based on ID from URL of post request?
I am making a simple API in DjangoRESTFramework. I have following model of a task, that belongs to one and only one Educational application (eduapp for short): class Task(models.Model): id = models.AutoField(primary_key=True, blank=True) name = models.TextField() eduapp = models.ForeignKey(EduApp, on_delete=models.CASCADE, null=False) and simple serializer for it: class TaskSerializer(serializers.ModelSerializer): taskId = serializers.IntegerField(source='id', required=False) class Meta: model = Task fields = ('taskId', 'name') To access these tasks, I have a view that shows list of all tasks with given eduapp id (eduapp is another model). Eduapp id is taken from URL used for requests with following url pattern: path('eduapps/<int:eduapp_id>/tasks/', views.TaskList.as_view()), so for example: localhost:8000/eduapps/1/tasks/ gives my view eduapp id of 1: class TaskList(generics.ListCreateAPIView): serializer_class = TaskSerializer def get_queryset(self): queryset = Task.objects.all() eduapp_id = self.kwargs.get('eduapp_id') queryset = queryset.filter(eduapp=eduapp_id) return queryset This works just fine. However, I am now at the point where I want to also save new tasks (previously injected straight into DB) and not just list existing ones. I am wondering how to propagate eduapp_id from the view into serializer, and how to then utilize it as a foreign key for new eduapp field (which already exists in model), something along the lines of: class TaskSerializer(serializers.ModelSerializer): taskId = serializers.IntegerField(source='id', required=False) eduapp … -
How to save a selected radio button in db in django
I am creating a multiple choice quiz and I am not able to save the selected option on the radio button in the database as a new answer. Also, I want you to show if the option matches the correct answer. When I select one of the options, it appears in the address bar the value of the radio button next to the text, but I want this value to be saved in db. views.py def detalhes(request, idProva): prova = get_object_or_404(Prova,pk=idProva) model = Prova template_name = 'polls/detalhes.html' # Default: <app_label>/<model_name>_list.html context_object_name = 'prova' # Default: object_list paginate_by = 10 queryset = Prova.objects.all() usuario = request.user.id questao = request.POST.get('idQuestao') try: questao_selec = prova.questao_set.get(pk=request.POST['questao']) pagina = paginator.page(page) resposta = Resposta(resposta=resposta,idQuestao=idQuestao,idResposta=1,respostacerta=1) resposta.save() return redirect('/') except (KeyError,Questao.DoesNotExist): return render (request,'polls/detalhes.html',{ 'prova': prova, }) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) else: #questao_selec.votes += 1 questao_selec = Questao(textoQuestao=request.POST.get('textoQuestao'),imagemQuestao=request.FILES('imagemQuestao'),imagem2Questao=request.FILES('imagem2Questao'),perguntaQuestao=request.POST.get('perguntaQuestao')) resposta_selec = Resposta(idResposta = request.POST.get('idResposta'),idQuestao = request.POST.get('idQuestao'),usuario = request.POST.get('usuario'),resposta = request.POST.get('#mysubmit')) questao_selec.save() resposta_selec.save() return HttpResponseRedirect(reverse('polls:resultados',args=(prova.idProva,))) detalhes.html <form id="NPSform" method="GET"> {% if not resposta.usuario %} <input type="radio" name="scores" id="A" value="A"> A) {{questao.aOpcao}}<br> <input type="radio" name="scores" id="B" value="B"> B) {{questao.bOpcao}}<br> <input type="radio" name="scores" id="C" value="C"> C) {{questao.cOpcao}}<br> <input type="radio" name="scores" id="D" value="D"> D) {{questao.dOpcao}}<br> <input type="radio" … -
getting "Requested settings, but settings are not configured" error when running tests
I have set up a different settings file for each environment (dev, test, and prod), all of which inherit from a base file. My configuration looks like this myproject settings base.py dev.py test.py prod.py In manage.py I have def main(): if 'test' in sys.argv: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings.test") elif os.environ['DJANGO_DEVELOPMENT'] == 'true': os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings.dev") else: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings.prod") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) But when I run python -m unittest discover I get Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 85, in _run_code exec(code, run_globals) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/__main__.py", line 18, in <module> main(module=None) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/main.py", line 100, in __init__ self.parseArgs(argv) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/main.py", line 124, in parseArgs self._do_discovery(argv[2:]) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/main.py", line 244, in _do_discovery self.createTests(from_discovery=True, Loader=Loader) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/main.py", line 154, in createTests self.test = loader.discover(self.start, self.pattern, self.top) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/loader.py", line 347, in discover tests = list(self._find_tests(start_dir, pattern)) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/loader.py", line 412, in _find_tests yield from self._find_tests(full_path, pattern, namespace) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/loader.py", line 412, in _find_tests yield from self._find_tests(full_path, pattern, namespace) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/loader.py", … -
Forms - Foreign Key - ModelChoiceField - NOT SAVING
I have 2 accounts, Instructor & Student which both extend a CustomUser model. Instructors have an email field. Students have an instructor key that they select from a drop-down menu. I am able to populate the ModelChoiceField with instructor's emails, no problem. However, I am now unable to save the selected instructor's email into the foreign key appropriately. I think the error lies in how I save the instructor_id, specifically this line, student.instructor_id = Instructor.objects.get(email=self.cleaned_data["instructor_id"]) , but I'm not sure what the problem is. Please help! forms.py class StudentSignUpForm(UserCreationForm): instructor_id = forms.ModelChoiceField(queryset=Instructor.objects.all()) class Meta(UserCreationForm): model = CustomUser fields = ('username', 'inGameName', 'instructor_id') help_texts = { 'username': 'Required', 'inGameName': 'Required; A name by which you can be identified', 'instructor_id': 'Optional; Provided by your professor', } @transaction.atomic def save(self): user = super().save(commit=False) user.is_student = True student = Student.objects.create(user=user) student.instructor_id = Instructor.objects.get(email=self.cleaned_data["instructor_id"]) student.save() user.save() return user class InstructorSignUpForm(UserCreationForm): email = forms.EmailField(label='Your Email', help_text='Required') class Meta(UserCreationForm.Meta): model = CustomUser fields = ('username', 'inGameName', 'email') help_texts = { 'username': 'Required', 'inGameName': 'Required; A name by which you can be identified', } @transaction.atomic def save(self): user = super().save(commit=False) user.is_instructor = True instructor = Instructor.objects.create(user=user) instructor.email = self.cleaned_data["email"] instructor.save() user.save() return user models.py from django.contrib.auth.models import AbstractUser, …