Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Testing Django UserCreationForm - form.is_valid() always returning false
I am trying to write tests for my Django chat application to validate the UserCreationForm. I am following the Django test code here: https://github.com/django/django/blob/master/tests/auth_tests/test_forms.py I have a users app which handle registration, login, etc. users/tests.py from django.test import TestCase from django.contrib.auth.forms import UserCreationForm class UserCreationFormTest(TestCase): def test_form(self): data = { 'username': 'testuser', 'password1': 'test123', 'password2': 'test123', } form = UserCreationForm(data) self.assertTrue(form.is_valid()) I've extended the UserCreation form to include an email field (forms.py) when registering. users/forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True, label='Email') class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] I cannot for the life of me figure out why form.is_valid() always returns False during my testing. In my test I have self.assertTrue(form.is_valid()) To execute tests I am running python manage.py test users from the terminal. Actual registration, login, etc. works fine but my tests do not work as expected! users/views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): # check if valid form.save() # save user info messages.success( request, f'Your account has been … -
How to test a django class based view with token authentication?
I am testing a REST API that requires token authentication. I am using coreapi.Client and coreapi.auth.TokenAuthentication to test the view. But it fails due to the following exception: coreapi.exceptions.NetworkError: URL missing scheme '/v0/endpoint/' My dependencies are listed here: python_version = "3.7" django = "==2.2.6" djangorestframework = "==3.9.4" Test File from rest_framework.test import APITestCase import coreapi from requests.auth import HTTPBasicAuth from django.urls import reverse from module.views import MyView class TestViews(APITestCase): def test_train_GET(self): auth = coreapi.auth.TokenAuthentication( scheme = 'Token', token = '<TOKEN>' ) client: coreapi.Client = coreapi.Client(auth=auth) response = client.get( reverse('endpoint') ) self.assertEqual(response.status_code, 200) Project Urls file: from django.urls import include, path urlpatterns = [ path('v0/', include('app.urls')), ] App Urls file: from django.conf import settings from django.contrib import admin from django.urls import include, path from .views import MyView urlpatterns = [ path('endpoint/', MyView.as_view(), name='endpoint'), ] I recieve the following error while running the test: raise exceptions.NetworkError("URL missing scheme '%s'." % url) coreapi.exceptions.NetworkError: URL missing scheme '/v0/endpoint/'. -
How to add a modal pop up on the view button?
<div class="col-md-3"> <div class="card card-profile"> <div class="card-avatar"> <a href="#pablo"> <img class="img" src="{% static 'img/faces/marc.jpg' %}"> </a> </div> <div class="card-body"> <h5 class="card-category text-gray">CEO / Co-Founder</h5> <h4 class="card-title">{{user.first_name}} {{user.last_name}}</h4> <h6 class="card-category text-gray">ILO - 001</h6> <h6 class="card-category text-gray">HOME HEALTH</h6> <p class="card-description"> Monday to Friday (9AM to 6PM) </p> <a href="#" class="btn btn-primary btn-round">View</a> </div> </div> </div> The code for an Profile Pic on my main page, and I was trying to add a modal pop to wherein when I click the View button it will show the whole profile of the employee. And i don't have an idea how to do this. Thanks for any help. -
TypeError: 'DeferredAttribute' object is not iterable for dropdown
I need to make some dropdown the list is from Instagram.username but it say object not iterable anyone can help here's my code : models.py # Create your models here. class Instagram(models.Model): nama_depan = models.CharField(max_length=100) nama_belakang = models.CharField(max_length=100) username = models.CharField(max_length=100) def __str__(self): return "{}.{}".format(self.id,self.username) class InstagramName(models.Model): Instaname = models.CharField(choices=Instagram.username) def __str__(self): return "{}.{}".format(self.id, self.Instaname) forms.py from django import forms from . models import Instagram,InstagramName class InstagramForm(forms.ModelForm): class Meta: model = Instagram fields = [ 'nama_depan', 'nama_belakang', 'username', ] class InstagramNameForm(forms.ModelForm): class Meta: model = InstagramName fields = ['Instaname'] -
django makemigrations error "no such column"
I am developing a Django project with REST Framework. It all worked well before, but all of a sudden I can't add any new model fields: If I add any new field even if the most simple one like this: def_episode = models.IntegerField(blank=True, null=True) And manage.py makemigrations, this will happen: Traceback (most recent call last): File "D:\MyProjects\Python\Django\env\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "D:\MyProjects\Python\Django\env\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such column: novelrecorder_novel.def_episode The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "D:\MyProjects\Python\Django\env\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "D:\MyProjects\Python\Django\env\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\MyProjects\Python\Django\env\venv\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "D:\MyProjects\Python\Django\env\venv\lib\site-packages\django\core\management\base.py", line 361, in execute self.check() File "D:\MyProjects\Python\Django\env\venv\lib\site-packages\django\core\management\base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "D:\MyProjects\Python\Django\env\venv\lib\site-packages\django\core\management\base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "D:\MyProjects\Python\Django\env\venv\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "D:\MyProjects\Python\Django\env\venv\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "D:\MyProjects\Python\Django\env\venv\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "D:\MyProjects\Python\Django\env\venv\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "D:\MyProjects\Python\Django\env\venv\lib\site-packages\django\urls\resolvers.py", line 584, in url_patterns patterns … -
Is it possible to somehow print 'i+1' in django template?
Scenario:I want to make a page for available slots for booking ,for which I want print time slot for 1 hour that is from i To i+1 and color it according to the availability. I am newbie to django and can't figure out the way to make a calendar and that is why I am printing time values in HTML template. Is there any other way to make this page and also is printing 'i+1' possible. Views.py @login_required def slots(request): k={ 'pro':range(8,17) } return render(request, 'login/slots.html',k) slots.html {% for i in pro %} <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> <td id="demo">{{ i }} to {{ i+1 }}</td> </tr> {% endfor %} I know this might be a silly question but I am not able to figure it out, any help is appreciated. -
Django; NoReverseMatch exception - 1 Pattern Tried
Upon trying to test a model's get_absolute_url(), I'm getting the following exception. accounts happens to be the app name in this case. I'm just trying to test the path that is the result of calling that function: django.core.urlresolvers.NoReverseMatch: Reverse for 'profile' with arguments '()' and keyword arguments '{'username': 'test_user'}' not found. 1 pattern(s) tried: ['accounts/profile/<username>/'] class Profile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) birth = models.DateField() bio = models.TextField() avatar = models.ImageField(upload_to=image_file_path) def get_absolute_url(self): profile_user = self.user.username return reverse('accounts:profile', kwargs={'username': profile_user}) class UserProfileMethods(TestCase): def setUp(self): self.test_user = User.objects.create_user('test_user') self.image = open(join(dirname(__file__), 'images/test_image.jpg'), 'rb') self.profile_data = { 'user' : self.test_user, 'birth': '2019-01-01', 'bio': 'Hello World!', 'avatar': SimpleUploadedFile( self.image.name, self.image.read(), content_type="image/jpeg" ) } self.profile = Profile.objects.create(**self.profile_data) self.profile_url = self.profile.get_absolute_url() def test_profile_url(self): self.assertEqual(self.profile_url, 'profile/test_user') from django.conf.urls import url from . import views urlpatterns = [ url(r'sign_in/$', views.sign_in, name='sign_in'), url(r'sign_up/$', views.sign_up, name='sign_up'), url(r'sign_out/$', views.sign_out, name='sign_out'), url(r'profile/<username>/', views.profile, name='profile') ] -
Django Rest Framework - return Response(serializer.data) image field get null instead of the url
I set an 'ImageField' in the model, using postman to post data. The image uploaded successfully. However, when my view returns serializers.data, the image field is null, which is supposed to be the URL of the image. Does anyone have any ideas? I appreciate it so much. This is the response { "user": 7, "category": "2018", "cover": null, "name": "Louisville" } This is my model class Journey(models.Model): def user_directory_path(self, filename): return 'media/journey_cover/{0}/{1}'.format(self.user_id, filename) user = models.ForeignKey(to=UserProfile, related_name="journeys", on_delete=models.CASCADE) category = models.CharField(null=False, max_length=50) cover = models.ImageField(upload_to=user_directory_path) created = models.DateTimeField(auto_now_add=True) name = models.CharField(null=False, max_length=50) My serializer: class JourneySerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(queryset=UserProfile.objects.all()) cover = serializers.ImageField(use_url=True) class Meta: model = Journey fields = ['user', 'category', 'cover', 'name'] My View class JourneyList(APIView): permission_classes = [IsOwnerOrReadOnly, permissions.IsAuthenticatedOrReadOnly] parser_classes = [MultiPartParser, FormParser] def post(self, request): print(request.content_type) serializer = JourneySerializer(data=request.data) if serializer.is_valid(raise_exception=True): journey = serializer.create(serializer.validated_data) journey.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Is It Possible To Have A Theme Selector For Users Possibly In The Admin CP To Choose The Style of Their Site?
I was wondering if it's possible to have a option for users to pick from a set of themes/styles they want for there site like wordpress or forums like MyBB? I plan on releasing a script for people to use but I don't want them to all have the same theme so I would like to have a option for them to select one they like that I created or have them be able to upload/create there own. Thanks for your help! -
How do I batch update a field with a function in Django
How do I batch update a field with a function in Django and The function argument is the field value . such as Data.objects.filter(need_add=1).update(need_add=Myfunc(F('need_add'))) -
How to fade out Django success messages using Javascript?
I am trying to fade out Django success messages using a small Javascript script but cannot seem to get it to work. This is in my base.html: {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}"> {{ message }} </div> {% endfor %} {% endif %} <script> var m = document.getElementsByClassName("alert"); setTimeout(function(){ m.style.display = "none"; }, 3000); </script> -
Cant run django server because of cx_oracle
i pull my friend code in github , and when i want to run it with django *path*>workon test (test)*path*>py manage.py runserver it has error in it Traceback (most recent call last): File "C:\Users\u532246\Envs\test\lib\site-packages\django\db\backends\oracle\base.py", line 47, in <module> import cx_Oracle as Database ModuleNotFoundError: No module named 'cx_Oracle' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\users\u532246\appdata\local\programs\python\python38-32\Lib\threading.py", line 932, in _bootstrap_inner self.run() File "c:\users\u532246\appdata\local\programs\python\python38-32\Lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\u532246\Envs\test\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\u532246\Envs\test\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\u532246\Envs\test\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[1] File "C:\Users\u532246\Envs\test\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\u532246\Envs\test\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\u532246\Envs\test\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\u532246\Envs\test\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\u532246\Envs\test\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\u532246\Envs\test\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\u532246\Desktop\skripsi\Django-master\polls\models.py", line 6, in <module> class Question(models.Model): File "C:\Users\u532246\Envs\test\lib\site-packages\django\db\models\base.py", line … -
React + Firebase + Python
I have one project that I want to write in React frontend and Firebase as a database. But I need to write some functions with Python, I have some operations with ssh, valve, and FTP. Should I use Django? How to grab data that comes from Python libraries live like from base? What do you recommend? Btw, I never user Python with Firebase and I have struggles. -
Using bootswatch with Django Dojo
I am working on an app that uses Django + Dojo. I want the UX to have awesome fonts, bootswatch kind of themes for example https://bootswatch.com/3/cosmo/ The entire app is going to be written in python and want to understand how I can ensure I get the modern look interface rather than the arcane Microsoft UI like feel some of the older dojo widgets spit out. -
upload_to category folder based on ForeignKey
I have an Image model where I can upload images and assign them a foreign key. I want to use the ImageField's upload_to parameter and put them in the corresponding folder when uploaded. model.py class Image(models.Model): category = models.ForeignKey(Category, on_delete="CASCADE") image = models.ImageField(upload_to=str(category.name)) caption = models.CharField(max_length=250, blank=True) I'd Like to create the category folder on creation then uploat images to their foreign key's folder. -
OAuth2 with Vue and Django
I have a project with Vue Js + Django Rest Framework and i want to be able to login with Google. I all ready have the GoogleUser object with this code: <script> export default { name:'GoogleButton', mounted () { window.gapi.load('auth2', () => { const auth2 = window.gapi.auth2.init({ client_id: 'API_CLIENT.apps.googleusercontent.com', cookiepolicy: 'single_host_origin' }) auth2.attachClickHandler(this.$refs.signinBtn, {}, googleUser => { this.$emit('done', googleUser) }, error => console.log(error)) }) }, } </script> ( This code is just for testing the object and endpoint ) onSuccess(obj){ var usuario = obj.getBasicProfile() console.log("TEsting login" + usuario.getName()); var email = usuario.getEmail(); var data = { 'email':email, 'password':'********', } var url = 'http://localhost:8000/login/'; var paquete = { method:'POST', body:JSON.stringify(data), headers:{ 'Content-Type': 'application/json', } } fetch(url,paquete).then( res => res.json() ).catch( error => console.error('Error:', error) ).then(function(res){ console.log(res); }); } Now my question is... what can i do from the server's side to know if the data that was sent is actually from a Google user? Can i use the TokenId and "asking throw OAuth to Google is its ok" ? -
Getting the count of objects inside a django model related set (nested)
I have three models, each one has a 1:n relationship with the other, so coming from one model I would like the know the total count of all the children objects. I already have a working code (displayed below) in a function but I believe it can be done in a single query. class Carton(models.Model): id = models.CharField(max_length=15, primary_key=True) pallet = models.ForeignKey(Pallet, null=True, blank=True, on_delete=models.SET_NULL) # removed the other unrelated fields class Pallet(models.Model): id = models.CharField(max_length=15, primary_key=True) group = models.ForeignKey(PalletGroup, on_delete=models.CASCADE) # removed the other unrelated fields class PalletGroup(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True) # removed the other unrelated fields # THIS IS WHAT I THINK COULD BE DONE IN A SINGLE QUERY def total_assigned_cartons(self): total_assigned_cartons = 0 for pallet in self.pallet_set.all(): total_assigned_cartons += pallet.carton_set.count() return total_assigned_cartons I'm just trying to understand if it can be done in a single query instead of iterating over all the related objects and counting the total count for each. -
Can I return a template and a variable separately from a single Django function?
I am writing an ajax call. The call returns HTML. However, I only want to actually load the new HTML if a certain thing happened on the backend (either an insert or a delete action occurred). Thus, I want to return two variables from Django. (1) The html, that I will only load if the second variable (2) returns true or false. Although this won't be very useful, a sample function is below: def update_party_and_company_data(request): parties, companies, reload = get_the_data() context = {'parties': [list of parties], 'companies': [list of companies],} html = render(request, 'setup_parties_data.html', context) reload_instruction = reload return HttpResponse(json.dumps({'html': html , 'reload_instruction ': reload_instruction })) -
Django and jQuery, why?
I'm struggling to intuitively understand some basic concepts related to Django and jQuery. Surprisingly there is an equal struggle try to find a good curated answer. 1. Eg DataTables (a very common add-in ) Why do I need to use jQuery at all, why cannot I use python? 2. How do I connect JS with Python, as Python is needed to work with models? Do I need to take de-tour using JSON and serializers? Why don't a django version of DataTables exist, isn't django a pretty common framework? Is there a specific chapter in a book, a video, a blog, article, udemy that can bring me from zero to hero when it comes to Django and Datatables? Documentation around DataTables is not accessible as a start point. Many thanks for some guidance along the road in a time of frustration. -
How to filter a column name that's a PK Django query set
Basically, I pass the column name via a pk into a view. Next, I want to filter a queryset by the column name equals TRUE, however, I am unsure how to do this. def ColumnNameView(request, column_name): table = Model.objects.filter(column_name=True) return render(request, template, {'table':table}) This does not work as I cannot use a string as column name. -
Callbacks not working for FileUpload plugin
So I'm trying to follow this tutorial https://simpleisbetterthancomplex.com/tutorial/2016/11/22/django-multiple-file-upload-using-ajax.html to try to implement file uploading capabilities for my own web app. However, when I get to the section about "Displaying the Progress" my modal is not shown. Any idea what I'm doing wrong? (Code is kinda copied almost word for word for testing purposes) HTML: {% extends 'qqq/main_template.html' %} {% load static %} {% block content %} <!-- Datatables provided styles and js code --> <link href="{% static 'qqq/vendor/datatables/dataTables.min.css' %}" rel="stylesheet"> <script src="{% static 'qqq/vendor/datatables/dataTables.min.js' %}"></script> <!-- Page level custom scripts --> <script type="text/javascript" src="{% static 'qqq/js/custom-datatable.js' %}"></script> <script src="{% static 'qqq/js/fileUpload/js/vendor/jquery.ui.widget.js' %}"></script> <script src="{% static 'qqq/js/fileUpload/js/jquery.iframe-transport.js' %}"></script> <script src="{% static 'qqq/js/fileUpload/js/jquery.fileupload.js' %}"></script> <!-- Maybe need to edit --> <script src="{% static 'qqq/js/basic-upload.js' %}"></script> <!-- Page Heading --> <h1 class="h3 mb-2 text-gray-800">Parse & Update</h1> <!-- <input type="file" multiple id="fileLoader" name="myfiles" title="Load File" /> <input class="btn btn-primary btn-lg" type="button" id="btnOpenFileDialog" value="Parse & Update" onclick="openfileDialog();" /> --> <!-- {# 1. BUTTON TO TRIGGER THE ACTION #} --> <div> <button type="button" class="btn btn-primary btn-lg js-upload-photos">Parse & Update</button> <input id="fileupload" type="file" name="file" multiple style="display: none;" data-url="{% url 'qqq:parse' %}" data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'> </div> <table id="gallery" class="table table-bordered"> <thead> <tr> <th>Logs</th> </tr> </thead> <tbody> {% … -
Django session matching query does not exit
I am trying to accept urls of the form "http://0.0.0.0:8000/sim_session/ABCD/EFGH/[0-9][0-9][0-9]/" via my django url patterns but I don't know why it cannot recognize "http://0.0.0.0:8000/sim_session/ABCD/EFGH/000/" or "http://0.0.0.0:8000/sim_session/ABCD/EFGH/311/" whereas, it accepts "http://0.0.0.0:8000/sim_session/ABCD/EFGH/010/" and "http://0.0.0.0:8000/sim_session/ABCD/EFGH/110/" Can someone help me how to accept 3 digits one after another via django url patterns? and also some explanation on why the above regex behaves unexpectedly would be much appreciated. I have also tried patterns like url(r'(?P < tutor_name>[^/]+)/(?P< tutee_name>[^/]+)/(?P< image_name>[\d]{3})/$', views.sim_session, name='room') but it does not work. Code snippet from django.conf.urls import url from . import views urlpatterns = [ url(r'(?P< tutor_name>[^/]+)/(?P< tutee_name>[^/]+)/(?P< image_name>[0-9][0-9][0-9])/$', views.sim_session, name='room') ] -
Accessing Django model fields throws NameError inside of dictionary
I'm trying to return a dictionary via DRF's Response(), but I can't access any model fields from within the dictionary. I tried returning a single field's value without first packing the data into a dictionary, and it worked. I know that Django's querysets are lazy and only hit the DB on evaluation, but I'm stumped by why my model suddenly has no fields when it's accessed inside of a dictionary. @api_view(['GET']) def arDetail(request): ''' gets data from model and puts it into a dict to be returned ''' model = model.objects.get(pk=int(request.GET["pk"])) #return Response(model.pk) WORKS here, but throws a nameerror #when accessed in rspData rspData = { pk: model.pk, problem: model.problem, solution: model.solution, primaryCategory: model.primaryCategory, secondaryCategory: model.secondaryCategory, profilePic: model.author.profilePic } return Response(rspData) I need to pull URLS and whatnot from other models, so I can't just use DRF's serializers as I do on my other models. What should happen is that I set each of the necessary fields in the dictionary and then return that with Response(), but I can't access model fields from within the rspData dictionary. Instead, Django throws a NameError on the first line of the dict, (and any others if I comment out fields to look for … -
How to use chrome to view a website that is locally hosted on a VPS (ssh)
Trying to view, with my windows desktop, a development server hosted locally on a VPS, via Chrome + SSH tunnel. VPS locally hosted port 8000 Trying to output tunnel on my windows to port 8080 (or any port that is safe idc) I can ssh just fine via cmd with ssh user@ip.com and I felt like this one might be close but I can't get it to work... ssh -L 127.0.0.1:8080:127.0.0.1:8000 myuser@myvps.com It holds the connection in the cmd line like it is "working" but when I navigate to 127.0.0.1:8080 and all I get is "This site can't be reached". -
How to fix modelformset error: __init__() missing 1 required positional argument: 'user'
This is my first attempt at using formsets and I am stuck with this error. Where am I going wrong? I don't fully understand how this works yet. I think my form is expecting a user but I don't know what to do with it. Thanks for any help! error: init() missing 1 required positional argument: 'user' model: class PropertySubmission(models.Model): BANNER_CHOICES = ( ('NB', 'No Banner'), ('FL', 'For Lease'), ('FS', 'For Sale'), ('NL', 'New Listing'), ('SD', 'Sold'), ('LD', 'Leased'), ('RD', 'Reduced'), ('NP', 'New Price'), ('SC', 'Sold Conditionally'), ('CB', 'Custom Banner'), ) image = models.ImageField(upload_to=user_directory_path, blank=True) mls_number = models.CharField(max_length=8, blank=True) headline = models.CharField(max_length=30) details = RichTextField() banner = models.CharField(max_length=2, choices=BANNER_CHOICES) author = models.ForeignKey(User, on_delete=models.CASCADE) date_posted = models.DateTimeField(default=timezone.now) date_modified = models.DateTimeField(default=timezone.now) program_code = models.ManyToManyField(Program) product = models.ForeignKey('Product', on_delete=models.SET_NULL, null=True) production_cycle = models.ManyToManyField('ProductionCycle') shell = models.ForeignKey('Shell', on_delete=models.SET_NULL, null=True) card_delivery_instructions = models.CharField(max_length=1000, blank=True) card_delivery_instructions_image = models.ImageField(upload_to=card_delivery_instructions_image_path, blank=True) form: class PropertyCreateKeepInTouchForm(forms.ModelForm): class Meta: model = PropertySubmission fields = ['headline','details','banner','image','mls_number','program_code'] help_texts = { 'details': '110 characters maximum', } def clean(self): cleaned_data = super().clean() image = cleaned_data.get("image") mls_number = cleaned_data.get("mls_number") program_code = cleaned_data.get("program_code") if mls_number == '' and image is None: # Only do something if one field are valid so far. self.add_error('image', 'Please provide an image …