Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Allow all ips in CSRF_TRUSTED_ORIGIN django
How to allows all/ any ips in CSRF_TRUSTED_ORIGIN of django Backend django restapi are running and frontend is on angular in one system and we are trying to access with system ip in another system, i am able to access frontend and while accessing backend POST method API's are not working it's showing not found in card trusted origins. In settings.py i made get dynamic ips. import socket def get_ipaddress(): host_name = socket.gethostname() ip_address = socket.gethostbyname(host_name) return "http://"+ip_address+":4200" ALLOWED_HOSTS=["*"] CSRF_TRUSTED_ORIGINS=[get_ipaddress()] Tried to use csrf_excempt , but it's not working. Version of django4.0.1, Angular 16 -
How do I access image URL from one django model to another? How do I put it on a template?
I am using two models Forum and User. User model.py: class User(models.Model): first_name = models.CharField(max_length=100) middle_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) profile_img = models.ImageField(upload_to='images/', null=True, blank=True) I wanted to access the url of User's profile_img and display it to my template in Forum. How should I code this in my Forum's model.py? -
Cannot populate elasticsearch index using ```python manage.py search_index --rebuild``` in django using docker
I am using django, elasticsearch and postgresql from docker in separate containers. When I try to run python manage.py search_index --rebuild, I get the following error: Traceback (most recent call last): File "C:\Users\ashut\Desktop\ramrobazar\manage.py", line 22, in <module> main() File "C:\Users\ashut\Desktop\ramrobazar\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\ashut\Desktop\ramrobazar\venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\ashut\Desktop\ramrobazar\venv\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\ashut\Desktop\ramrobazar\venv\lib\site-packages\django\core\management\base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\ashut\Desktop\ramrobazar\venv\lib\site-packages\django\core\management\base.py", line 460, in execute output = self.handle(*args, **options) File "C:\Users\ashut\Desktop\ramrobazar\venv\lib\site-packages\django_elasticsearch_dsl\management\commands\search_index.py", line 166, in handle self._rebuild(models, options) File "C:\Users\ashut\Desktop\ramrobazar\venv\lib\site-packages\django_elasticsearch_dsl\management\commands\search_index.py", line 143, in _rebuild if not self._delete(models, options): File "C:\Users\ashut\Desktop\ramrobazar\venv\lib\site-packages\django_elasticsearch_dsl\management\commands\search_index.py", line 132, in _delete "the '{}' indexes? [y/N]: ".format(", ".join(index_names))) TypeError: sequence item 0: expected str instance, NoneType found Everything else works fine. When I run docker-compose up, all of my containers i.e. the postgresql database, web service and the elasticsearch containers start running without any problems. The website starts running on localhost:8000 and I can also create new users from the admin panel. So, the website and database are working fine. On localhost:9200, I can see the following JSON: { "name" : "4336b15c63fa", "cluster_name" : "docker-cluster", "cluster_uuid" : "a_long_string", "version" : { "number" : "7.14.2", "build_flavor" : "default", "build_type" : "docker", "build_hash" … -
'Access is denied' on wrong port select
could not open port 'COM#': PermissionError(13, 'Access is denied.', None, 5) actually this is not a mistake, I want to show window alert message when someone select wrong port if anyone knows please help def add_charger_view(request): if request.method == 'POST': port = request.POST['port'] port = port.split().pop(0) baud_rate = request.POST['baud_rate'] serial.Serial(port, baud_rate) return render(request, "charger.html", context) all things good, connection is ok but shows this error in not ok -
user registered but cannot login django
I tried to implement customized user login/ Registration in django. but only one user can be logged in but not anyother user are logged in. Registration area looks fine cause user can register easily. These are my codes I guess there is problem with CSRF token but i dont know where to update it In view Register def registerPage(request): form = UserForm() if request.method == 'POST': print(request.POST) form = UserForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.user_name = user.user_name.lower() user.save() login(request, user) return redirect('home') else: messages.error(request, 'An error occured duing registration!!') return render(request, 'base/login_register.html', {'form': form}) My Views Login def loginPage(request): page = "login" if request.user.is_authenticated: return redirect('home') if request.method == "POST": email = request.POST.get('email').lower() password = request.POST.get('password') try: user = NewUser.objects.get(email=email) except: messages.error(request, 'User doesnot exist') user = authenticate(request, email=email, password=password) if user is not None: login(request, user) print("mess going on here!") return redirect("home") else: messages.error(request, "Email or Password doesnot exit") context = {'page': page} return render(request, 'base/login_register.html', context) Forms.py from tkinter import Widget from django.forms import ModelForm from .models import NewUser class UserForm(ModelForm): class Meta: model = NewUser fields=['email','user_name','first_name','country','address','year_in_school','about','avatar'] def __init__(self, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) self.fields['email'].widget.attrs.update({'class': 'form-control'}) # self.fields['email','user_name','first_name','country','address','year_in_school','about'].widget.attrs.update({'class': 'form-control'}) self.fields['user_name'].widget.attrs.update({'class': 'form-control'}) self.fields['first_name'].widget.attrs.update({'class': 'form-control'}) self.fields['country'].widget.attrs.update({'class': 'form-control'}) self.fields['address'].widget.attrs.update({'class': 'form-control'}) … -
The directory 'D:\dj\staticfiles' in the STATICFILES_DIRS setting does not exist
This is my settings.py I already created a folder 'staticfiles' in the project folder. How can I solve the error -
'Image' instance expected, got OrderedDict([('text', 'First Image'), ('gallery', <Gallery: First Gallery>)])
I am building a simple gallery image app and using django-rest-framework. I am saving two model instances, which I am rendering as nested response and also saving throughh nested json. But when I click on Post from api admin then it is showing 'Image' instance expected, got OrderedDict([('text', 'First Image'), ('gallery', <Gallery: First Gallery>)]) I think the problem is in the create() function. I have also tried modifying it but it is still not working and showing the same error. models.py class Gallery(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=300) class Image(models.Model): gallery = models.ForeignKey(Gallery, on_delete=models.CASCADE, related_name="images") text = models.CharField(max_length=300) serializers.py class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = "__all__" class GallerySerializer(serializers.ModelSerializer): images = ImageSerializer(many=True) class Meta: model = Gallery fields = "__all__" def create(self, validated_data): created = Gallery.objects.create(poll=1) created.images.set(validated_data['images']) return created my response which I am saving { title: "First Gallery", images : [ { "gallery": 1, "text": "First Image" } ] } And When i print validated_data like :-: print(validated_data['images']) then it is showing [OrderedDict([('text', 'First Image'), ('gallery', <Gallery: First Gallery>)]), OrderedDict([('text', 'Second Image'), ('gallery', <Gallery: First Gallery>)]), OrderedDict([('text', 'Third Image'), ('gallery', <Gallery: First Gallery>)]), OrderedDict([('text', 'Fourth Image'), ('gallery', <Gallery: First Gallery>)])] I have just started learning … -
How can i edit uploaded mp3 files by user
I want my django app to do. User Uploads mp3 file user inputs time range my app trims the mp3 file to the range given avail result mp3 to user -
Django: How to automatically update a model instance everytime another model instance is updated
In online shop projects, I have a model called Order (and this model stores order instances) and a model called Points. The model Points stores bonus points which are collected by the users when they make orders. But the order may be cancelled, so I would like to be able to monitor when an order is being cancelled (model Order instance's status being changed to "cancelled") in order to take the points away. How can I do that? -
Django Imagefield renaming works only every other time
I'm attempting to upload a profile picture to a django model which should always be named pic.jpg. Old pictures are deleted using django_cleanup. This works every other time. I upload an image and it's saved as pic.jpg, then upload a different one and it's saved as pic_{randomchars}.jpg (i.e pic_wCU5xwv.jpg). def rename_pic(instance, filename): return os.path.join("api/media/me/", filename) pic = models.ImageField(upload_to=rename_pic) def save(self, *args, **kwargs): try: # Opening the uploaded image img = Image.open(self.pic) output = BytesIO() img = img.convert('RGB') # after modifications, save it to the output img.save(output, format='JPEG') output.seek(0) # Set field to modified picture self.pic = InMemoryUploadedFile(output, 'ImageField', "pic.jpg", 'image/jpeg', sys.getsizeof(output), None) except Exception as e: print(e) print(self.pic.name) # Always prints pic.jpg super(MyData, self).save() # Error happens in this line print(self.pic.name) # Prints api/media/me/pic.jpg and api/media/me/pic_{randomchars}.jpg alternating The error happens somewhere in the super(MyData, self).save() line, as the file has the correct name before it's called. -
deleting a post in django
hi ive read some of similar posts but couldn't find same problem. i wrote a code to delete post and when i press delete it shows 404 error but when back to home post is still there views: def delete_music_view(request,music_id): #view for deleting music my_object = add_music.objects.get(id=music_id) if request.method == 'POST': my_object.delete() return redirect('pages:home') context = {'my_object':my_object} return render(request,'pages/delete_music.html',context) url: app_name = 'pages' urlpatterns = [ path('',views.home,name='home'), path('add_music/',views.add_music_view,name='add_music'), path('musics/<int:music_id>',views.musics_view,name='music_page'), path('musics/<int:music_id>/delete',views.delete_music_view,name='delete_music'), ] template: {% extends 'pages/base.html' %} {% block content %} <form action="." method='POST'> {% csrf_token %} <p><input type="submit" name="delete" value="yes"><a href="../../">cancel</a></p> </form> {% endblock %} can u pls tell me whats wrong? -
Django: Direct assignment to the forward side of a many-to-many set is prohibited. Use user.set() instead
I see this is a common problem and understand the idea is that you cannot add many to many unless it is created first. I have seen multiple solutions for this but unsure which one to use. Models.py class Concert(models.Model): venue = models.CharField(max_length=200, null=True) concertid = models.CharField(max_length = 200, null=False, default='didnotsaveproperly') date = models.DateField(null=True) city = models.CharField(max_length=100, null=True) country = models.CharField(max_length=200, null=True) user = models.ManyToManyField(USER_MODEL, related_name="concerts", null=True) song = models.ManyToManyField("Song", blank=True, null=True) def __str__(self): return str(self.concertid) + " " + str(self.venue) + " " + str(self.date) Views.py def log_concert_and_song(request, concertdict): if request.method == "POST": Concert_save = Concert( concertid=concertdict['id'], date=concertdict['eventDate'], venue=concertdict['venue'], city=concertdict['city'], country=concertdict['country'], user = request.user ) Concert_save.save() Should I use the User model? -
modify the model to take the information from the another model
I have two models the first form is for users and the second is for candidates when I register an account that is done using the first form and when I enter to edit the account information as the name and date of birth I need to rewrite this information back knowing that I put it during the account registration, is there a way to modify the second model form to take the information from the first model the first models : from django.db import models from django.contrib.auth.models import AbstractUser from phonenumber_field.modelfields import PhoneNumberField GENDER_CHOICES = ( ('M', "Male"), ('F', "Female"), ('O', "Other"), ) class User(AbstractUser): username=None email=models.EmailField( verbose_name='email address', max_length=255, unique=True ) date_of_birth = models.DateField(default='1990-01-01') gender=models.CharField(max_length=1,choices=GENDER_CHOICES,blank=True) picture=models.ImageField( upload_to='img/users',null=True,verbose_name="" ) phone = PhoneNumberField() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def __str__(self): return self.email the secound models : from django.db import models from accounts.models import User from django.utils import timezone from autoslug import AutoSlugField from django_countries.fields import CountryField from recruiters.models import Job from django.utils import timezone CHOICES = ( ('Full Time', 'Full Time'), ('Part Time', 'Part Time'), ('Internship', 'Internship'), ('Remote', 'Remote'), ) class Profile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True, related_name='profile') full_name = models.CharField(max_length=200, null=True, blank=True) country = CountryField(null=True, blank=True) … -
Django: key error after setting the key with AJAX from JAVASCRIPT
I am using django to manage my site. I have a JAVASCRIPT event that update's the server with this an AJAX call: **script_x.js** $.ajax({ type: "POST", url: "my_url_to_server", headers: {'X-CSRFToken': csrftoken}, data: {}, success: function(response){alert(response);} }); On the server in the views, I set the "SESSION variable" once the JQUERY function fires: **views.py** def set_session_now(request): if not request.is_ajax() or not request.method=='POST': return HttpResponseNotAllowed(['POST']) request.session['my_key'] = 0 return HttpResponse('ok') and in the urls.py: path('set_session_now', views.set_session_now, name='set_session_now'), But once the process finishes; I only get "ok" sent from the server; but the session is not set; the server returns "Key Error: 'my_key'". Any help would be appreciated. -
How to populate field from the view django?
I am trying to populate a field on a template form in Django. I have tried to do it on the view as well as a value on the form template but no luck. Here is my work The outcome would be to populate username and email field from the resource model, but I am getting an UNIQUE constraint failed: auth_user.username error. Thanks forms.py class AdminRegistrationForm(UserCreationForm): is_superuser = forms.BooleanField(), password1 = forms.CharField( label="Password", widget=forms.PasswordInput) password2 = forms.CharField( label="Password Confirmation", widget=forms.PasswordInput) class Meta: model = User fields = ['password1', 'password2'] def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if not password1 or not password2: raise ValidationError("Please confirm your password") if password1 != password2: raise ValidationError("Passwords must match") return password2 view.py def admin_registration(request, username): resources = Resource.objects.get(username=username) if request.user.is_authenticated: return redirect(reverse('index')) if request.method == "POST": resources = Resource.objects.get(username=username) admin_registration_form = AdminRegistrationForm(request.POST) if admin_registration_form.is_valid(): obj = admin_registration_form.save(commit=False) obj.is_superuser = True obj.save() user = auth.authenticate(username=[resources.username], password=request.POST['password1']) if user: auth.login(user=user, request=request) messages.success(request, "You have successfully registered") return redirect(reverse('index')) else: messages.error(request, "Unable to register your account at this time") else: admin_registration_form = AdminRegistrationForm() return render(request, 'registration/registration.html', { "registration_form": admin_registration_form, 'email': resources.email }) models.py class Resource(models.Model): ROLE = [ ('Analyst', "Analyst"), ('Team Manager', "Team Manager"), ('Quality Auditor', … -
OMR BubbleSheet Test Recognization
I'm handling my last homework for the university in Spain (Business Adminstration), and I decided create a system that the Teacher insert the Exam correct answer, then download a model to give to the students do the exam, and after recieve the exams, he uploads it and the system compare the correct answers with the answers that the students did. The model is this one: answers sheet model The model with correct answers: answer sheet correct Wrong answer exam: wrong answer exam I could develop the backend in Django, they can do everything before the test corrector. Of course I tried multiple ways (Bubblesheet OMR on google and we have a lot of people doing the same test using the same example: https://pyimagesearch.com/2016/10/03/bubble-sheet-multiple-choice-scanner-and-test-grader-using-omr-python-and-opencv/ ), I found more examples, but the most closer one was : Detect All Circles in an image (Optical Mark Recognition) using Python OpenCV , but not worked in my example file. Can someone help me please? Here you have the three options. The Idea is that the teacher will upload all the PDF files, then is transformed into img (i did it using pdf2image), and then the corrector system loop in all the images/pdf correcting and … -
Why some fields are not created while making migrations?
I have this two models in models.py class Bid(models.Model): bid = models.IntegerField(default = 0) user = models.ForeignKey(User, on_delete = models.CASCADE, related_name = "bid") def __str__(self): return f"Bid of {self.bid} from {self.user}" class AuctionListings(models.Model): name_of_item = models.CharField(max_length=32) description = models.CharField(max_length=400) owner = models.ForeignKey(User, on_delete = models.CASCADE, related_name="auctionlistings", default = None)** bid = models.ForeignKey(Bid, on_delete = models.CASCADE, related_name = "auctionlistings", default = None)** is_closed = models.BooleanField(default=False, blank=True, null=True) url = models.CharField(max_length=800) watchlist = models.ManyToManyField(User, blank=True, related_name="watch_listings") category = models.CharField(max_length=50) When i makemigrations: operations = [ migrations.CreateModel( name='AuctionListings', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name_of_item', models.CharField(max_length=32)), ('description', models.CharField(max_length=400)), ('is_closed', models.BooleanField(blank=True, default=False, null=True)), ('url', models.CharField(max_length=800)), ('category', models.CharField(max_length=50)), ], ), migrations.CreateModel( name='Bid', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('bid', models.IntegerField(default=0)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='bid', to=settings.AUTH_USER_MODEL)), ], ), My Question is: Why Django did not create the fields: "bid" and "user" specified in models.py. -
when there is no Overlapping i am getting overlapping validation error
With thins code i can check overlappig but the problem when overlapping is not happening i am getting overlapping validation error. How i can solve this error. form.py for i in range(count): start = self.data.get(f'applicationdefinition_set-{i}-start', []) end= self.data.get(f'applicationdefinition_set-{i}-end', []) if (start > end_bbch) or (start == start): raise ValidationError( 'Overlapping Not Allowed' ) -
How can I integrate a website functionality to a mobile app and share same database
I'm creating a website using Django as a back-end and next I will make a native mobile app using Flutter, so how can I bond these together (share same database and funcionality)? Making what is called PWA (progressive web app) -
form.is_valid() always returns False and form is not valid
i have a simple form for adding comments and in views i am checking it for validity. But it always returns False and i get error404 according to my code. I have several assumption, but it didn`t work. And now i have no idea how to get the reason views.py: class ProductDetailView(DetailView): model = Product template_name = "core/product.html" context_object_name = "product" .... def post(self, request, *args, **kwargs): if request.POST.get("product_detail_form") == 'add_comment_form_two': if self.request.user.is_authenticated: form = CommentForm(request.POST) if form.is_valid(): comment = Review(review=request.POST.get("review"), rating=request.POST.get("rating"), author=self.request.user, product_connected=self.get_object()) comment.save() print("success ") return redirect("product_detail", *args, **kwargs) else: print("error") raise Http404 .... html form <form action="" method="post"> {% csrf_token %} {{ comment_form.as_p }} <input type="submit" name="product_detail_form" value="add_comment_form_two">add comment</input> </form> forms.py class CommentForm(forms.ModelForm): review = forms.CharField( required=True, widget=forms.TextInput( attrs={"class": "comment_form", "placeholder": "Comment"}), label="" ) OPTIONS = ( ("1", "1"), ("2", "2"), ("3", "3"), ("4", "4"), ("5", "5"), ) rating = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=OPTIONS) class Meta: model = Review fields = ["review", "rating"] model class Review(models.Model): review = models.TextField(max_length=500) author = models.ForeignKey(User, on_delete=models.CASCADE) product_connected = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="reviews") creation_date = models.DateTimeField(auto_now_add=True) last_update_time = models.DateTimeField(auto_now=True) rating = models.IntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(5)]) Thanks for any help, I just can't understand it for a long time. stupid rule that I have to write … -
How to use model's field's distinct values as select field's choices
My model looks like this. class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) roll_no = models.CharField(max_length=32) course = models.CharField(max_length=120) Now I want to want to make a filter form using django_filters and want to use distinct values of course field as choices of select input but it requires each value to be associated with unique id and this field have any unique id. I tried this: class StudentFilter(django_filters.FilterSet): course = django_filters.ModelChoiceFilter(queryset=Student.objects.values("course",flat = True).distinct(),empty_label=('Course')) class Meta: model = Student fields = [] but it didn't work. Note I do not want to make separate model for course. -
Does not appear to have any patterns in it. Django
when I run the project on the server, I get the following error, but there is no problem in local. The included URLconf 'config.settings' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import home.urls code from django.urls import path, include from home.views.anasayfa import anasayfa from home.views import iletisim, kategori from home.views.articles import articles_detail from home.views.productdetail import product_detail from home.views.surdur import surdur from home.views.about import abaut_detail from home.views.sozluk import sozluk urlpatterns = [ path('', anasayfa, name='anasayfa'), path('iletisim', iletisim), path('<slug:kategoriSlug>', kategori, name='kategori'), path('detail/<slug:slug>', product_detail, name='product_detail'), path('articles/<slug:slug>', articles_detail, name='articles'), path('surdurulebilirlik/<slug:slug>', surdur, name='surdur'), path('kurumsal/<slug:slug>', abaut_detail, name='abaut_detail'), path('sozluk/', sozluk, name='sozluk'), path(r'^ckeditor/', include('ckeditor_uploader.urls')) ] confi.urls code from xml.etree.ElementInclude import include import django from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path ('' , include('home.urls')) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to get a response with new line characters with Django Rest Framework's Response?
I am currently trying to understand how to use the Response class from DRF. Using Django's HttpResponse, and using the following code: return HttpResponse("Hello \n World", content_type="text/plain") I get the following response: Hello World Which is what I am expecting. However, using the following code: return Response("Hello \n World", content_type="text/plain") I get the following response: "Hello \n World" Notice how I also get the pair or quotes in the second one "". Since Response is a child of HttpResponse, how can I have the same result using Response? I've come to this problem because I want to present new line characters and tab characters with Response, but I have not been successful so far. The only the I've seen that might help me was using Renderers from DRF, and making a custom one for plain text. but I do not understand how to apply them to Responses, and I am a bit surprised that DRF doesn't support plain text considering it is a subclass of HttpResponse. Thank you -
Django form fields not rendering in template
I am trying to render a simple Django Form on my index page. I have stripped it way back in an attempt to get it to work. I can display other context elements when passing them in, and I know an instance of the Form is being created (by printing type(form)), it is just empty and I cannot figure out why. I have made similar forms multiple times before without running into this issue. I have tried rendering as {{ form.as_p }} as well as {{ form }}. All that renders is the heading, the hidden csrf_token, and the submit button. Thanks in advance... from django import forms class NewPostForm(forms.Form): title: forms.CharField(label='Title', max_length=100) content: forms.CharField(label='Content', max_length=100) def index(request): form = NewPostForm() return render(request, "network/index.html", { "form": form }) {% block body %} <div class="new-post"> <h5>New Post</h5> <form action="" method="POST"> {% csrf_token %} {{ form }} <input type="submit" value="Add Post"> </form> </div> {% endblock %} -
ManyToMany Relationship with additional fields Django Forms
For my Django project I am trying to create a singular form that allows me to add a row in my Pipeline model and link that row to the Process model through the PipelineProcess model. This is fairly straightforward by using ModelForms IF the PipelineProcess model did not have an extra field (phase). models.py class Pipeline(models.Model): name = models.CharField(max_length=100) sector = models.CharField(max_length=100, blank=True, null=True) process = models.ManyToManyField(Process, through='PipelineProcess') class Meta: managed = True db_table = 'pipeline' class Process(models.Model): name = models.CharField(max_length=100) class Meta: managed = True db_table = 'process' class PipelineProcess(models.Model): pipeline = models.ForeignKey(Pipeline, models.DO_NOTHING, blank=True, null=False) process = models.ForeignKey(Process, models.DO_NOTHING, blank=True, null=False) phase = models.CharField(max_length=100) class Meta: managed = True db_table = 'pipeline_process' forms.py class PipelineForm(ModelForm): class Meta: model = Pipeline fields = ['name', 'sector', 'phase'] This form generates the following error which makes sense: django.core.exceptions.FieldError: Unknown field(s) (phase) specified for Pipeline I have tried looking up examples of other people but none of which are useful to me. Most were far too complicated for me to put into my own project. I am fairly new with Django and web dev in general. Any help would be greatly appreciated.