Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Inject javascript variable in a django template filter
I have a django template filter to retrieve dictionary items based on the key passed. {% with data=dict_data|get_data:key %} I have separately made a template_tag.py file which returns those items. def get_domain_data(dictionary, key): p = ast.literal_eval(dictionary) return p[key] # data being returned successfully The issue is in passing the dynamic value of the key in the filter function. <script> var key_val = $('#input_id').val(); '{% with key="'+key_val+'" %}'; '{% with data=dict_data|get_domain_data:"'+key+'" %}'; //encountering error here // rest of the code '{% endwith %}'; '{% endwith %}'; </script> If I hardcode a string value the entire operation works, but I am unable to use the javascript variable within the django {% filter %} function. Any help would be greatly appreciated. Thanks! -
Unable to extract data from model's(database)
I am building an legal compliance webapp that includes the relationships between entries, etc. I have separate models that are Company_Masters, Location_Masters, dept, employ and Comp_Info. On my index page I would like to list all the compliances and would like to create, update and edit them. But I don’t know how to use all the models #view.py from django.shortcuts import render from django.views.generic import ListView from .models import Company_Masters, Location_Masters,dept, emplo, Comp_Info def home(request): mylist = zip(Company_Masters.objects.all(), Location_Masters.objects.all() , dept.objects.all(), emplo.objects.all()) context = { 'mylist': mylist } return render(request,'compliance/home.html',context) class PostListView(ListView): model = Company_Masters model = Location_Masters model = dept model = emplo model = Comp_Info template_name = 'compliance/home.html' context_object_name = 'mylist' def about(request): return render(request,'compliance/about.html') URLS.PY #urls.py from django.urls import path from .views import PostListView from . import views urlpatterns = [ path('', PostListView.as_view(), name='compliance-home'), path('about/', views.about, name='compliance-about') ] HOME.HTML {% extends "compliance/base.html" %} {% block content %} {% for comp,loc,dept,emp in mylist %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">COMPLIANCE 1</a> <small class="text-muted">DATE EXPIRY</small> </div> <p class="article-content"> COMPANY ID: {{ comp.comp_id }}</p> <p class="article-content">COMPANY NAME: {{ comp.comp_name }}</p> <p class="article-content">LOCATION ID: {{ loc.loc_id}}</p> <p class="article-content">LOCATION NAME: {{ loc.loc_name}}</p> <p class="article-content">DEPT ID: {{ dept.dept_id}}</p> <p … -
Why django creates duplicate index?
I have just started using pghero and added my database being used by the django applicatin for monitoring. There, pghero is reporting that there are duplicate indexes and is showing that there are duplicate indexes on the tables provided by default(check the picture). Why does django create duplicate indexes? or is there some flaw in pghero's reporting? -
Default prefix of Django inline formset
Say I have the following models: class Pizza(models.Model): ... class Topping(models.Model): pizza = models.ForeignKey(Pizza, related_name='toppings') I have would like to make an inline formset like so: PizzaFormSet = inlineformset_factory(Pizza, Topping, form=CreatePizzaForm, formset=PizzaToppingsFormSet, extra=0, min_num=1) where PizzaToppingsFormSet inherits from BaseInlineFormSet. If I have: form_data = { 'form-INITIAL_FORMS': 0, 'form-TOTAL_FORMS': 1, 'form-0-meat': 'Chicken', 'form-0-cheeze': 'Mozzarella', } formset = DatesFormSet(form_data) I get an error django.core.exceptions.ValidationError: ['ManagementForm data is missing or has been tampered with']. I understand I can specify my own prefix like formset = DatesFormSet(form_data, prefix='my_prefix') and then it works. But I would like to know: what is the default prefix for an inline formset? The Django docs say that for a regular formset the default prefix is form, but this is not the case for an inline formset. -
IntegrityError on saving ImageField : Field 'path' doesn't have a default value
I am trying to save a Model with an ImageField but i can't because it keeps giving me this error: (1364, "Field 'path' doesn't have a default value") I tried to give that field a default value, save first the model then the field, and did not work. MODEL class Images360(models.Model): name = models.CharField(max_length=32, null=True) oldpath = models.ImageField(upload_to='uploads/img/', null=True) product = models.ForeignKey('Product', blank=True, null=True) order = models.PositiveIntegerField() METHOD photo = Images360(name=filename, product=self.product, order=count ) # photo.save() photo.oldpath.save(filename, ContentFile(data)) EDIT This have been working for months and it stopped working this week. I checked the files that are being uploaded and everything seems ok. -
Django CMS (3.6.0) automatic language switch/detection not working as intended
Expected behaviour would be that a newly visiting person with FR as first setting in HTTP header should see the french version of the page (which is existing and set as language in settings, but not as default. manual language switch is working). Accoriding to django docs language should be determined in the following order https://docs.djangoproject.com/en/dev/topics/i18n/translation/#how-django-discovers-language-preference language prefix in the requested URL cookie Accept-Language HTTP header Default Settings Actual behaviour correctly switches navigation nodes (django cms menu) to french, but not cms plugin content (displayed in default language). #MIDDLEWARE SETTINGS (order as mentioned in docs) 'cms.middleware.utils.ApphookReloadMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'webpack.middleware.WebpackDevserverMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.admindocs.middleware.XViewMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'cms.middleware.page.CurrentPageMiddleware', 'cms.middleware.user.CurrentUserMiddleware', 'cms.middleware.toolbar.ToolbarMiddleware', 'cms.middleware.language.LanguageCookieMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ################################################################## # multisite language handling ################################################################## AVAILABLE_LANGUAGES = { 'de': _('Deutsch'), 'fr': _('Französisch'), 'it': _('Italiano'), 'en': _('English'), } SITE_LANGUAGES = config('SITE_LANGUAGES', default='de,fr', cast=Csv()) LANGUAGE_CODE = SITE_LANGUAGES[0] LANGUAGES = [(k, v) for k, v in AVAILABLE_LANGUAGES.items() if k in SITE_LANGUAGES] Is CMS_LANGUAGES needed if SITE_LANGUAGES are set. In Django CMS all relevant options in page tree are available. I could not see any different behaviour if set. Any ideas what could cause this behaviour? -
I get logs 2 times in stdout when there is a traceback error in django
my settings.py for LOGGER is as below, LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'json': { '()': 'sample_app.json_log_formatter.JSONFormatter', }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'stream': sys.stdout, #'level': '', 'formatter': 'json' }, }, 'loggers': { '': { 'handlers': ['console'], 'level': 'INFO', #'propogate': True, }, }, } Now when there is any unhandled exceptions like var = abc and abc is not defined I get my logs 2 times, one with my handler so the traceback error is in json format and the second is again the same error without json format it is coming from django.request. Note: I have not added any extra logger line in my code . I just want all my unhandled exceptions also in json format but only once. so that when I send to ELK its clean -
GenericForeignKey in Grappelli admin: filter content_type
With related lookups, I can easily get access to all the models I have to have a generic foreign key. Obviously, this is not what I want to do. I want to restrict it to just a sub set of the models I have -- specifically all the inherit from the abstract model Registry. My models look like thus: class Registry(models.Model): """A base registry class.""" number = models.BigAutoField(primary_key=True) when = models.DateField(default=timezone.now) title = models.CharField( max_length=1024, default='', blank=True, null=True) class Meta: """The meta class.""" abstract = True […] class Revision(models.Model): """A revision model.""" when = models.DateTimeField(default=timezone.now) identification = models.BigIntegerField() content_type = models.ForeignKey( ContentType, on_delete=models.CASCADE, related_name='+') object_id = models.PositiveIntegerField() parent = GenericForeignKey('content_type', 'object_id') […] class Document(Registry): […] class Drawing(Registry): […] So that each Registry derived instances can have many different revisions. And the relevant admin: class RevisionAdmin(admin.ModelAdmin): """Revision administration definition.""" fieldsets = [ ('Revision', { 'fields': [ 'when', 'identification', ] }), ('Registry', { 'classes': ('grp-collapse grp-open',), 'fields': ('content_type', 'object_id', ) }), ] -
How to wait long enough for Django views results on Firefox?
I'm developing a website with Django 2.2, using : Centos 7 Mozilla Firefox 60.6.0 Google Chrome 73.0.3683.86 Docker and Docker compose The first page allows the user to submit data from a formatted file (equivalent to csv) and the second page shows the result of calculations (done row by row) in a datatable. I have noticed a difference between Mozilla Firefox and Google Chrome: For big files, on Chrome, the web browser waits long enough to receive and display the results of calculations. Whereas in Firefox, the web browser stops waiting for localhost and the "results" page is not loaded. As the problem occured when the file exceeded a certain size, I have guessed that the app spent too much calculating time and Firefox stopped waiting for the response before to load the "results" page. So I changed my view to accelerate calculations. The problem still persists with big files. With files from approximately 3.5Mo the results page os displayed or not (almost randomly). I tried to raise "dom.max_script_run_time" in my Mozilla settings but this can't be done programatically. I saw that Celery can be used for long time running calculations, but in my case, calculations can be performed on … -
Implementing Django FilteredSelectMulitple into none admin form
I'm trying to implement the Django widget FilteredSelectMultiple into a non-admin form and although it displays, when loading I get a JavaScript error in console. The error is TypeError: node.tagName is undefined SelectFilter2.js:11:9 If I then select items from the list I get the following JavaScript error in console TypeError: cache is undefined SelectBox.js:76:29 This is my Django form class PlaylistForm(forms.ModelForm): class Meta: model = Playlist exclude = ['id'] widgets = { 'owner' : forms.HiddenInput(), 'name' : forms.TextInput ( attrs={ 'class' : 'form-control', 'placeholder' : _('Playlist Title'), 'label' : _('Playlist Title')}), 'projects' : FilteredSelectMultiple ('Items', is_stacked=True, attrs = {'class' : 'form-control'}) } class Media: css = { 'all': (os.path.join(settings.BASE_DIR, '/static/admin/css/widgets.css'),), } js = ( '/admin/jsi18n/', ) This is the view class CreatePlaylistView (LoginRequiredMixin, CreateView): model = Playlist form_class = PlaylistForm And this is the template additions <script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.min.js' %}"></script> <script type="text/javascript" src="{% static 'admin/js/jquery.init.js' %}"></script> <script type="text/javascript" src="{% url 'admin:jsi18n' %}"></script> {{ form.media }} And I included this is urls.py based on some other posts path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'), What have I got wrong? -
AttributeError: 'str' object has no attribute 'get' and "list index out of range"
I'm working on a django project that allows users to upload images and videos, both images and video upload fine, but when a user try to edit the images in a post it returns weird errors. For instance when a user try to delete "one" image it returns "list index out of range", when a user also tries to delete more than one image it returns to the post without deleting and sometime it returns AttributeError: 'str' object has no attribute 'get' or Unique constraint failed: blog_images.image #views.py class EditView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Post fields = ['title', 'content', 'restrict_comment'] template_name = 'blog/postupdate.html' def get(self, request, *args, **kwargs): pk = kwargs['pk'] post = get_object_or_404(Post, pk=pk) form = PostEditForm(instance=post) ImageFormset = modelformset_factory(Images, fields=('image',), extra=4, max_num= 4) formset = ImageFormset(queryset=Images.objects.filter(post=post)) context = { 'form': form, 'post': post, 'formset': formset, } return render(request, 'blog/postupdate.html', context) def post(self, request, *args, **kwargs): pk = kwargs['pk'] post = get_object_or_404(Post, pk=pk) ImageFormset = modelformset_factory(Images, fields=('image',), extra=4, max_num=4) if request.method == 'POST': form = PostEditForm(request.POST or None, request.FILES or None, instance=post) formset = ImageFormset(request.POST or None, request.FILES or None) # print(form.is_valid()) print(formset.is_valid()) if form.is_valid() and formset.is_valid(): form.save() # print(formset.cleaned_data) data = Images.objects.filter(post=post) for index, f in enumerate(formset): if … -
Django REST framework - MultiSelectField - TypeError: Object of type 'set' is not JSON serializable
I'm trying to make a multi-choice rest api with Django REST framework and django-multiselectfield. Currently inside the model I have: ANIMAL = ( ('dog', 'Dog'), ('cat', 'Cat'), ) class MyForm(models.Model): ... animals = MultiSelectField(choices=ANIMAL) and in my serializer I have: class MyFormSerializer(serializers.ModelSerializer): class Meta: model = MyForm fields = (..., 'animals') animals = fields.MultipleChoiceField(choices=ANIMAL) When I'm trying to POST into the api using this kind of body: { ... "animals": ["cat"], ... } I get an error: TypeError: Object of type 'set' is not JSON serializable Traceback (most recent call last): File "C:\Python36\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Python36\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Python36\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python36\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "c:\mysite\myserver\myform\views.py", line 15, in angels_add return JsonResponse(serializer.data, status=201) File "C:\Python36\lib\site-packages\django\http\response.py", line 558, in __init__ data = json.dumps(data, cls=encoder, **json_dumps_params) File "C:\Python36\lib\json\__init__.py", line 238, in dumps **kw).encode(obj) File "C:\Python36\lib\json\encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "C:\Python36\lib\json\encoder.py", line 257, in iterencode return _iterencode(o, 0) File "C:\Python36\lib\site-packages\django\core\serializers\json.py", line 104, in default return super().default(o) File "C:\Python36\lib\json\encoder.py", line 180, in default o.__class__.__name__) TypeError: Object of type 'set' is not JSON serializable … -
Redirect or refresh page after file download Django
i have some code to make zip and make it downloadable via browser i try code from some reference, like make it refresh after download using jquery file download Django: redirect after file download https://jqueryfiledownload.apphb.com/ views.py def backup(request): ... ... if request.method == 'POST': ... ... zipper = shutil.make_archive(base_name = os.path.join(settings.MEDIA_ROOT,file_name), format = 'zip', root_dir = backup_dir, base_dir = './' ) shutil.rmtree(backup_dir) resp = HttpResponse(open(zipper, 'rb').read(), content_type = "application/octet-stream") resp['Content-Disposition'] = 'attachment; filename=%s.zip' % file_download resp['Set-Cookie'] = 'fileDownload=true; Path=/' del_dir = os.getcwd() os.remove(os.path.join(settings.MEDIA_ROOT,file_name+'.zip')) formm.save() return resp the file can be downloaded and then i try add js to refresh backup.html <script type="text/javascript"> $("#file_download").click(function() { $.fileDownload($(this).prop('type'), { preparingMessageHtml: "The file download will begin shortly, please wait...", failMessageHtml: "There was a problem generating your report, please try again." }); return false; //this is critical to stop the click event which will trigger a normal file download! }); </script> after add that js code the results is, pop up an box with "There was a problem generating your report, please try again." -
Django project: No post found matching the query error
Problem: I am trying to retreive a detail view (singular blog post) by placing the following url in the browser: http://127.0.0.1:8000/post/1/ It should retrieve and render the first blog post on the screen, however, it comes up with the following error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/post/1/ Raised by: socialmedia.views.PostDetailView No post found matching the query I have looked through the code and have created the view correctly, as far as I can see, and also have the route (in urls) that should call the view. Question: Can someone point out the error please? Could you also provide a useful explanation to aid understanding in this specific example (routing, query matching posts etc) I have looked at similar questions and answers but cannot quite find the solution to this. A similar question suggested it may be to do with the admin or routes, but used regular expressions in the urls.py suggesting an older version of Django which is of no use to me. urls.py #THIS IS THE SOCIAL MEDIA URLS ..not the root directory URLS from django.contrib import admin from django.urls import path from . views import PostListView,PostDetailView from . import views urlpatterns = [ path('', … -
Google App engine Error :attempt to write a readonly database
I am newbie and I am deploying my django application on google app engine,which is having a signin & logout functionality.It work properly in local but when I deployed in app engine, It gives a operational error - attempt to write a readonly database. Moreover I am using firestore database. -
Connect to remote mysql with django on Windows 10
I've got a Django settings file which works on mac and linux which will let me use my. my.cnf file to connect to a remote MySQL database on AWS. However, on Windows 10 this doesn't seem to be the case. It keeps on saying it can't connect to the local database as if the my.cnf file doesn't exist. I've installed mysql connector and python mysql connector on windows 10, along with pip install mysqlclient as well like I would need to on linux however the problem still persists. '''python db_conf = Path("Project/my.cnf") DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'read_default_file': '{}'.format(db_conf), } } } ,,, With the same settings file I can run makemigrations, migrate and run the server. On windows this same thing crashes it. my.cnf is the same on Windows/Mac/Linux any help would be appreciated. I suspect it's a hangup with the way Windows does paths but I'm unsure how to resolve this as I usually code in Linux. -
I cant display an image on Django template
Am working with django 1.5.4 with python 2.7 I have tried to figure out what is the cause of this image to show like this view.py def single(request,slug): product = Product.objects.get(slug=slug) images = product.productimage_set.all() categories = product.category_set.all() context = { "product":product, "categories":categories, "edit":True, "images":images, } return render_to_response("products/single.html", context, context_instance=RequestContext(request)) and the single.html {% extends "base.html" %} {% block content %} <h1>{{ product }}</h1> {% for abc in images %} <img src="{{ MEDIA_URL }}{{ abc.image }}" /> {% endfor %} <ul> {% for category in categories %} <li>{{ category }}</li> {% endfor %} </ul> {% if edit %} <a href="#">Edit this product</a> {% endif %} {% endblock %} But it shows is this picture please help out with this issue is the problem form code or ? -
django multitable inheritance in django modeladmin
I have to models class Parent(object): text_field = models.TextField() boolean_field = models.BooleanField() class Child(Parent): another_text_field = models.TextField() With the following ModelAdmin class ChildAdmin(admin.ModelAdmin): pass admin.site.register(Child, ChildAdmin) I currently see all fields in the admin page, i.e. text_field, boolean_field, and another_text_field. Question: How can I get a parent select field and exclude text_field and boolean_field (for latter I guess I can use exclude). -
Django templates how to use tags and template filters to get data from json dict
I'm having dict which can be seen here https://jsoneditoronline.org/?id=a570322381fc45919a7a03ebad78cbee but from what I was reading so far, it's more likely a list of dicts. I am trying to display data from dicts like title, description, authors and categories but template tags are not displaying this what I want, tried with loops but can't access it Tried loops like this {% for items in books %} {% for volumeInfo in items %} {{ volumeInfo.title }} {% endfor %} {% endfor %} only what works is {{ books.items }} but it's giving me the whole json but I need only few values. def api(request): books = {} if 'books' in request.GET: books = request.GET['books'] url = 'https://www.googleapis.com/books/v1/volumes?q=%s' % books response = requests.get(url) books = response.json() print(type(books)) with open("data_file.json", "w") as write_file: json.dump(books, write_file) return render(request, 'books/api.html', {'books': books}) {% load get_item from template_filters %} {% block content %} <h2>Google API</h2> <form method="get"> <input type="text" name="book"> <button type="submit">search on google books api</button> </form> {% if books %} <p> {% for items in books %} {% for volumeInfo in items %} {{ volumeInfo.title }} {% endfor %} {% endfor %} {{ books.items }} </p> {% endif %} {% endblock %} -
How to restrict views to User groups?
I am using Django 2.0 . I have created user groups now I want to restrict views using User Groups. Which is the best way to solve this problem ? -
How Can I integrate Guacamole project in my django project?
Currently, I am building a platform with Django framework and I need to integrate Guacamole project in my platform so that any user logged in his account can connect to remote machines. How can I do this? I'm reading the documentation and I'm really confused about this because I have no idea how to start it. -
Update_or_create doesn't update
Update_or_create doesn't update any record, whereas new records are inserted and old/inserted record without any change are untouched. But when old/inserted record is updated, Django throws an error Duplicate entry '' for key 'PRIMARY'" Code obj, created = bfs_shots.objects.update_or_create( bfs_project_code = column[0], bfs_shot_code = column[1], bfs_shot_sequence_code = column[2]) print(created) Values created newly widow, 4 True Throws error when editing the same value widow, 5 Duplicate entry 'widow' for key 'PRIMARY'" Thanks in advance -
Django REST framework - require BooleanField to be true
Hi I'm trying to create a rest api with Django REST framework with a boolean field to be required to be true. Inside the model I have: class MyForm(models.Model): ... agree_terms = models.BooleanField() and in my serializer I have: class MyFormSerializer(serializers.ModelSerializer): class Meta: model = MyForm fields = (..., 'agree_terms') The problem is that I can POST to this api agree_terms = false and I'm trying to make it required to be True. I've tried adding to the serializer: accept_terms = fields.BooleanField(required=True) but it didn't worked for me. Is there is a way to make it work? Thanks in advance, Etay. -
Passing data to form (from POST and url)
I'm not sure how to pass data from a given object (profile) and from form (request.POST) to one model (many to many relation). I have two models: Profile and Keyword. Users can define many profiles (for different subjects) and in each profile they can define many keywords (used later by a crawler). It is possible that the same keyword is in many profiles, and one profile can have many keywords. Now, I have a view adding new profile to user, and in next step I want to add view adding keyword/keywords to this particular profile. I'm passing a parameter foreign key - profile_id - via url, and I have build form from my model Keyword. Now I have problem with passing both of them to my function. models.py class Profiles (models.Model): id_profile = models.AutoField(primary_key=True) user_id = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=45) description = models.TextField(max_length=120, default=' ') class Keywords (models.Model): id_keyword = models.AutoField(primary_key=True) name = models.CharField(max_length=100) id_profile = models.ManyToManyField(Profiles) template <button class="btn btn-outline-danger" type="submit"> <a href="{% url 'new_keyword' profile_id=object.id_profile %}">new keyword </a></button> urls.py path('profile_detail/<int:pk>/', users_view.ProfileDetailView.as_view(), name = 'profile_detail'), path('new_keyword/<profile_id>/', users_view.NewKeyword, name = 'new_keyword'), views.py def newKeyword(request): form = NewKeyword(request.POST) if request.method == 'POST': form.is_valid() form.save() return redirect('profile') return render(request, 'users/new_keyword.html', {'form': … -
KeyError while update_or_create objects in Model
I'm getting data from remote server iterating over the data to some extra cleaning and saving it into my model, def _fetch_data(): """ TODO: Fetch data from server """ ... else: _server_data = response.json() print(_server_data) while _server_data['next'] is not None: response = requests.get( _server_data['next'], headers=headers ) _server_data = response.json() _clean_json = remove_empty(_server_data) for _data in _clean_json['data']: yield _data I'm calling this function in my BaseCommand: class Command(BaseCommand): help = "Fetch data for QR" def handle(self, *args, **options): self.run() self.finalize() def run(self): _page_data = _get_product() # print(_page_data) for _product in _page_data: Product.objects.update_or_create( qr_id=_product['primaryId'], ean_code=_product['EAN'], description=_product['Description105'], category=_product['Category'], marketing_text=_product['Marketing Text'], bullet=_product['Bullet 1'], brand_image='\n'.join(_product['Brand Image']), image='\n'.join(_product['Images']) ) logger.debug(f'Something went wrong {_product}') print(f'This is the Data:{_product}') def finalize(self): self.stdout.write('All good') I'm using [update_or_create][1] here because of the update and I'll need to call BaseCommand from time to time, now the Traceback that I'm getting is 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 "/home/copser/Documents/Project/qr-backend/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/copser/Documents/Project/qr-backend/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/copser/Documents/Project/qr-backend/venv/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/copser/Documents/Project/qr-backend/venv/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/copser/Documents/Project/qr-backend/server/products/management/commands/load_product.py", line 16, in handle self.run() File "/home/copser/Documents/Project/qr-backend/server/products/management/commands/load_product.py", …