Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ModuleNotFoundError: No module named "\n 'hello"
I am following Django dj4e course. While going through setup that is linked here https://www.dj4e.com/assn/dj4e_ads1.md?PHPSESSID=991c1f9d88a073cca89c1eeda44f61d2 I got this weird error: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/cisco18/.virtualenvs/django3/lib/python3.6/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/cisco18/.virtualenvs/django3/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/home/cisco18/.virtualenvs/django3/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/cisco18/.virtualenvs/django3/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/cisco18/.virtualenvs/django3/lib/python3.6/site-packages/django/apps/config.py", line 212, in create mod = import_module(mod_path) File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import ... bunch of similar bootstrap lines ... ModuleNotFoundError: No module named "\n 'hello" I got this error when I did everything in the tutorial's setup and then copied the settings because they were missing something. I went through all those steps again and this weird error keeps popping up during python3 manage.py check. Here are my settings: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Used for a default title APP_NAME = 'ChucksList' # Add # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! … -
Dockerize Django application with mongoDB
I am working on Django web application which store the data in mongoDB database. When I run the docker using the docker-compose.yml file, it open the login page and gives the CSFR token error. Following are the logs of Django container: pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused, Timeout: 30s, Topology Description: <TopologyDescription id: 61ad29e66ee4fa015775e4b9, topology_type: Single, servers: [<ServerDescription ('localhost', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('localhost:27017: [Errno 111] Connection refused')>]> [05/Dec/2021 21:13:23] "GET /dashboard/ HTTP/1.1" 500 94504 Content of docker-compose.yml file: version: "3.7" services: mongodb_container: image: mongo:latest volumes: - mongodb_data_container:/data/db ports: - 27017:27017 web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - django_data_container:/home/app/webapp ports: - "8000:8000" links: - mongodb_container depends_on: - mongodb_container Can anyone tell me how I can communicate the Django with mongoDB using dockers? -
django Many-To-One relationship model
I want to create models with this specs : A user has ONLY ONE profile to add extra info I want to users to be able to belong to ONLY ONE organization Is it right to write this : Class User(models.Model) name ... class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) address = models.CharField(max_length=100) ... class organization(models.Model): members = models.ForeignKey(User, on_delete=models.PROTECT) name = models.CharField(max_length=100) ... or Class User(models.Model) name ... organizatiob = models.ForeignKey(Organization, on_delete=models.CASCADE) class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.PROTECT) address = models.CharField(max_length=100) ... class organization(models.Model): name = models.CharField(max_length=100) ... Or I'm completely off the mark? -
How to associate quantity amount in Django's many to many relationship
In Django I have 2 models. One called Box and one called Product. A Box can have many different products and with different quantities of each product. For example box1 can have 1 productA and 2 productB. My box model class Box(models.Model): boxName = models.CharField(max_length=255, blank = False) product = models.ManyToManyField(Product) def __str__(self): return self.boxName My product model class Product(models.Model): productName = models.CharField(max_length=200) productDescription = models.TextField(blank=True) productPrice = models.DecimalField(max_digits=9, decimal_places=0, default=0) class Meta: db_table = 'products' ordering = ['-productName'] def __str__(self): return self.productName How do I set up this model allowing me to select quantity of a products when creating the box object? -
Can't login after overriding default user model in Django
I have customized default Django model and now after creating a new superuser I can't login. It says that login or password is invalid. models.py: class UserProfileManager(BaseUserManager): def create_user(self, email, first_name, last_name, password=None): if not email: raise ValueError("Email is required") user = self.model( email = self.normalize_email(email), first_name = first_name, last_name = last_name, password = password ) user.save(using=self._db) return user def create_superuser(self, email, first_name, last_name,password=None): user = self.create_user( email = self.normalize_email(email), password = password, first_name = first_name, last_name = last_name ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class UserProfile(AbstractBaseUser): GENDERS = ( ("Male", "Male"), ("Female", "Female"), ("Other", "Other") ) email = models.EmailField(max_length=150, unique=True) first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) birth_date = models.DateField(blank=True, null=True) gender = models.CharField(choices=GENDERS, max_length=50, blank=True, null=True) location = models.CharField(max_length=150, blank=True, null=True) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = UserProfileManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name"] def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True settings.py: AUTH_USER_MODEL = "UserProfile.UserProfile" AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) So when I create a new superuser and try to login in admin panel I … -
DRF API design: the best way to create views for logged-in user
I'm working on a DRF + React app that allows users to label medical data. Need your opinion on my API design There are 3 models here: User, Annotation and IC (independent component). Each User can make only one Annotation for each IC. Currently, I made a separate view with implicit user substitution. GET gives me existing annotation for a user or empty JSON if not exists. POST allows me to create/update annotation for a user. URL has the form of /api/user-annotation-by-ic/1 class UserAnnotationByIcView(APIView): permission_classes = [IsAuthenticated] serializer_class = UserAnnotationSerializer def get(self, request, ic_id): try: obj = Annotation.objects.get(ic=ic_id, user=request.user) serializer = self.serializer_class(obj) return Response(serializer.data) except ObjectDoesNotExist: return Response({}) def post(self, request, ic_id): create = False data = request.data data['ic'] = ic_id context = { 'request': self.request, } try: obj = Annotation.objects.get(ic=ic_id, user=request.user) serializer = self.serializer_class(obj, data=data, context=context) except ObjectDoesNotExist: serializer = self.serializer_class(data=data, context=context) create = True serializer.is_valid(raise_exception=True) serializer.save() if create: return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.data) In all tutorials on DRF I see ViewSet CRUD views with filtering feature. Following this approach, I could use URLs like /api/annotations?user=1&ic=1. For security reasons, I would have to check that provided user matches to the logged-in user. So which approach is better? What … -
How to give css style in Django filter
Friends, is there any other way to change the style of Django filter fields except Bootstrap? can we style it ourselves with css -
How to build a E-commerce website using django
Hello guys.... Any one can suggest me, a video tutorial and wab-site tutorial of build a E-commerce project using django,html ,css, and any database but dont't useing javascript because i don't JS. And what is functionality went to add on my project.... I think you guys help me.. Thanks.... -
Why is Plotly displaying empty space when displaying a graph through django data?
I am trying to print a pie graph using from Django but it is showing an empty space instead of printing the pie chart. I used the instructions from https://plotly.com/javascript/pie-charts/ but I am getting an error. How do I fix it? views.py labels = list(account_graph.keys()) # ['Food', 'Gas', 'Friends'] data = list(account_graph.values()) # [-6.09, -20.0, -7.0] return render(request, "finances/account.html", {'labels': labels, 'data': data}) account.html <div id='expenses'></div> <script> var data = [{ values: {{data|safe}}, labels: {{labels|safe}}, type: 'pie' }]; var layout = { height: 400, width: 500 } Plotly.newPlot('expenses', data, layout); </script> -
Send request to View Django, without receiving any response
I ask the user a question on my website and if the answer is yes, I will send two data to view Django using a JavaScript file and using Ajax. I want to get this data in View Django and not send any HttpResponse to the user. If we do not send a response in the view, it will give an error. How should I do this? Thanks ValueError: The view tourist.views.planing did not return an HttpResponse object. It returned None instead. def planing(request): if request.is_ajax(): # Get user location from user location.js file: latitude = request.POST.get('latitude', None) longitude = request.POST.get('longitude', None) # To save data request.session['latitude'] = latitude request.session['longitude'] = longitude elif request.method == "GET": return render(request, "tourist/planing.html") elif request.method == "POST": # To retrive data: latitude = request.session.get('latitude') longitude = request.session.get('longitude') if latitude is not None : latitude = float(latitude) longitude = float(longitude) . . . return render(request, "tourist/map.html") -
How to store each months data in django model
I am creating an app where people can log in and create a committee and invite another users to join their committee and then whoever joined it will pay the committee each month till the end date. and one of the users will get the committee at the end of each month, I am having an issue I dont know how to store data of users who are paying month by month. I have created all these django models. but now the missing part is the storing of each months data, so that I can show the status as pending or completed. class Committee(models.Model): committee_creator = models.ForeignKey(Profile, on_delete=models.CASCADE) committee_name = models.CharField(max_length=100) committee_members_limit = models.IntegerField() committee_amount_per_month = models.IntegerField(default=0) committee_month_period = models.IntegerField(default=0) committee_amount_limit = models.IntegerField(null=True) committee_starting_date = models.DateTimeField(auto_now_add=False) committee_ending_date = models.DateTimeField(auto_now_add=False) class Participants(models.Model): participants_name = models.ForeignKey(Profile, on_delete=models.CASCADE) participants_committee_name = models.ForeignKey(Committee, on_delete=models.CASCADE) participants_paid_status = models.BooleanField(default=False) participants_amount_paid = models.IntegerField() participants_payment_slip = models.ImageField(upload_to='images/', null=True, blank=True) -
Django ChoiceField and RadioSelect return EnumMeta error
I have a ChoiceField that I would like to show as Radio selection but I get the following error: EnumMeta.call() missing 1 required positional argument: 'value' Here it is the code model.py class Answer(models.IntegerChoices): NO = 0, _('No') YES = 1, _('Yes') form.py question = forms.ChoiceField( choices=Answer, widget=forms.RadioSelect() ) I've followed the django documentation and I can't figure it out the nature of the error, thank you for any explanation that you can give me -
How to record audio from browser and upload to django server?
I have to record an audio from the browser and upload it to the django server, can someone help me? My django view: @api_view(['POST']) def audio_analysis(request): audio_data = request.FILES['audio'] # view content return render(request, 'homepage.html') -
After setting correct environment I am still facing this issue while deploying django app on heroku
I have added STATIC_ROOT in my setting.py file but still I am facing this error while deploying my app on heroku. Pictures of my settings.py file are attached below. Please help. Error: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. settings.py settings.py -
Django - Error received when anonymous user submits form
In one of my views I have a form where when a user logs in and submits the form, it works fine. However, when an anonymous user submits the form I get the following error: Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x1052fd3a0>>": "User_Inquiries.user" must be a "CustomUser" instance. This form needs to be submitted whether a user is anonymous or logged in. What do I need to do in order to resolve this issue? Code below. Any help is gladly appreciated. Thanks! views.py def account_view_contact(request): form = ContactUsForm(request.POST or None, request.FILES or None,) user_profile = User_Inquiries.objects.all() user_profile = User_Info.objects.all() user = request.user if request.method == "POST": # checking if request is POST or Not # if its a post request, then its checking if the form is valid or not if form.is_valid(): contact_instance = form.save(commit=False) # "this will return the 'Listing' instance" contact_instance.user = user # assign 'user' instance contact_instance.save() # calling 'save()' method of model return redirect("home") context = { 'form': form, 'user_profile': user_profile } return render(request, 'contact.html', context) models.py class User_Inquiries(models.Model): email = models.EmailField(max_length=100, null=True) name = models.CharField(max_length=100, null=True) subject = models.CharField(max_length=100, null=True) message = models.CharField(max_length=100, null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, null=False, on_delete=models.CASCADE) date_submitted = models.DateTimeField(auto_now_add=True, null=True) class Meta: … -
why git push heroku master giving error at every library?
I have following content in requirements.txt -ip==21.0 aioredis==1.3.1 bs4==0.0.1 django-binary-database-files==1.0.10 django-cors-headers==3.7.0 django-templated-email==2.4.0 djangochannelsrestframework==0.3.0 djoser==2.1.0 msgpack==1.0.2 mysqlclient==2.0.3 pandas==1.3.4 pillow==8.3.1 pip-chill==1.0.1 ply==3.11 psycopg2==2.8.6 psycopg2-binary==2.8.6 pylint-django==2.4.2 pyopenssl==21.0.0 service-identity==21.1.0 sklearn==0.0 waitress==2.0.0 whitenoise==5.3.0 but whenever I use git push heroku master this is giving same error at every library remote: ERROR: Could not find a version that satisfies the requirement aioredis==1.3.1 (from versions: none) remote: ERROR: No matching distribution found for aioredis==1.3.1 I have tried removing aioredis==1.3.1 from requirements.txt then it is giving error on next one and so on. what the exactly issue is? and how can I solve this? -
Django migration dependencies not being honoured
I get that to ensure that a given set of migrations are run before others we need to add the dependent permissions in the dependencies array. I seem to be doing that properly, however, when the migrations are run the dependent ones are not run before the current one and that creates other issues. Here are the details - thanks in advance Django version 2.2.5 File Name: equipment/migrations/0006_add_group_permissions.py class Migration(migrations.Migration): dependencies = [ ("hfauth", "0027_dispatch_staff_permissions"), ("equipment", "0005_add_tractor_manager"), ] operations = [ migrations.RunPython(add_permissions, reverse_code=remove_permissions), ] in the above example, ideally, a ("hfauth", "0027_dispatch_staff_permissions") should run before the current file That's not happening which causes other issues. How do I ensure that some dependencies are executed before running the current one. -
Django admin select like permission field
How to create form in admin panel like this one? It's default admin user view. My looks like that, but i want two "windows" class RoleAdmin(admin.ModelAdmin): list_display = ('name', ) fieldsets=( (None, {'fields': ('name', )}), (_('Role Permissions'), { 'fields': ('permissions', ), }), ) -
why git push heroku master giving error at every library?
I have following content in requirements.txt -ip==21.0 aioredis==1.3.1 bs4==0.0.1 django-binary-database-files==1.0.10 django-cors-headers==3.7.0 django-templated-email==2.4.0 djangochannelsrestframework==0.3.0 djoser==2.1.0 msgpack==1.0.2 mysqlclient==2.0.3 pandas==1.3.4 pillow==8.3.1 pip-chill==1.0.1 ply==3.11 psycopg2==2.8.6 psycopg2-binary==2.8.6 pylint-django==2.4.2 pyopenssl==21.0.0 service-identity==21.1.0 sklearn==0.0 waitress==2.0.0 whitenoise==5.3.0 but this is giving same error at every library remote: ERROR: Could not find a version that satisfies the requirement aioredis==1.3.1 (from versions: none) remote: ERROR: No matching distribution found for aioredis==1.3.1 I have tried removing aioredis==1.3.1 from requirements.txt then it is giving error on next one and so on. what the exactly issue is? and how can I solve this? -
Django ModelForm, not saving data
I'm using ModelForm to create a form, then I'm using this form to create a new instance in the database. But the form is not saving data, it's just reloading the page when the form submmited. I'm also uploading an image. forms.py from django import forms from django_summernote.widgets import SummernoteWidget from events.models import Event class EventCreateForm(forms.ModelForm): class Meta: model = Event fields = "__all__" widgets = { "content": SummernoteWidget(), } def __init__(self, *args, **kwargs): super(EventCreateForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs["class"] = "form-control" self.fields["start_datetime"].widget.attrs["class"] += " datetimepicker" self.fields["finish_datetime"].widget.attrs["class"] += " datetimepicker" self.fields["image"].widget.attrs["class"] = "custom-file-input" self.fields["address"].widget.attrs["rows"] = 3 views.py from django.urls import reverse_lazy from django.views.generic import ListView from django.views.generic.edit import FormView from django.contrib.auth.mixins import LoginRequiredMixin from events.models import Event from events.forms import EventCreateForm class EventListView(LoginRequiredMixin, ListView): model = Event context_object_name = "events" class EventFormView(LoginRequiredMixin, FormView): template_name = "events/event_form.html" form_class = EventCreateForm success_url = reverse_lazy("dashboard:events:home") event_form.html <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="card-body"> <div class="form-group"> <label>Title</label> {{ form.title }} </div> <div class="row"> <div class="col-sm-4"> <div class="form-group"> <label>Start Date and Time</label> {{ form.start_datetime }} </div> </div> <div class="col-sm-4"> <div class="form-group"> <label>Finish Date and Time</label> {{ form.finish_datetime }} </div> </div> <div class="col-sm-4"> <div class="form-group"> <label for="exampleInputFile">Image</label> <div class="input-group"> <div class="custom-file"> {{ … -
I cannot import summer notes in django
when i try to import summernoteModelAdmin in admin using from djangosummernote.admin import SummernoteModelAdmin it shows error Import "djangosummernote.admin" could not be resolved admin.py: from django.contrib import admin from djangosummernote.admin import SummernoteModelAdmin from .models import BlogPost class BlogPostAdmin(SummernoteModelAdmin): summernote_fields = ('content') admin.site.register(BlogPost, BlogPostAdmin) -
Dynamic link in Django always calls the first url path
In urls.py within urlpatterns I have below two lines urlspatterns = [ ... path('<slug:productSlug>', ProductView.as_view(), name = 'viewProduct'), path('<slug:boxSlug>', BoxView.as_view(), name = 'BoxView'), ... ] In my html template I have two links <a href="{% url 'viewProduct' item.productSlug %}" class="btn btn-outline-primary" tabindex="-1" role="button" aria-disabled="true">product view</a> <a href="{% url 'BoxView' item.boxSlug %}" class="btn btn-outline-primary" tabindex="-1" role="button" aria-disabled="true">Box View</a> The problem is even though I specified BoxView in the {% url 'BoxView' ... %} it keeps calling the viewProduct path. If I reverse the order of the two paths in urlPatterns then, it keeps calling the 'BoxView'. What I don't understand is it keeps calling whatever it finds first in urlPatterns. -
why pip freeze is giving error Could not generate requirement for distribution -ip 21.0?
pip freeze > requirements.txt giving an error WARNING: Could not generate requirement for distribution -ip 21.0 (c:\python39\lib\site-packages): Parse error at "'-ip==21.'": Expected W:(abcd...) How to remove this error and what the error exactly it is? following is the content of the file after running the command pip freeze > requirements.txt requirments.txt aioredis==1.3.1 asgiref==3.3.1 astroid==2.4.2 async-timeout==3.0.1 attrs==21.2.0 autobahn==21.3.1 Automat==20.2.0 beautifulsoup4==4.9.3 bs4==0.0.1 certifi==2020.12.5 cffi==1.14.5 channels==3.0.4 channels-redis==3.3.1 chardet==4.0.0 colorama==0.4.4 constantly==15.1.0 coreapi==2.3.3 coreschema==0.0.4 cryptography==3.4.7 daphne==3.0.2 defusedxml==0.7.1 Django==3.0.11 django-binary-database-files==1.0.10 django-cors-headers==3.7.0 django-render-block==0.8.1 django-templated-email==2.4.0 django-templated-mail==1.1.1 djangochannelsrestframework==0.3.0 djangorestframework==3.12.2 djangorestframework-simplejwt==4.7.1 djoser==2.1.0 hiredis==2.0.0 hyperlink==21.0.0 idna==2.10 incremental==21.3.0 isort==5.7.0 itypes==1.2.0 Jinja2==3.0.1 joblib==1.1.0 lazy-object-proxy==1.4.3 MarkupSafe==2.0.1 mccabe==0.6.1 msgpack==1.0.2 mysqlclient==2.0.3 numpy==1.21.4 oauthlib==3.1.0 pandas==1.3.4 Pillow==8.3.1 ply==3.11 psycopg2==2.8.6 psycopg2-binary==2.8.6 pyasn1==0.4.8 pyasn1-modules==0.2.8 pycparser==2.20 PyJWT==2.1.0 pylint==2.6.0 pylint-django==2.4.2 pylint-plugin-utils==0.6 pyOpenSSL==21.0.0 python-dateutil==2.8.2 python3-openid==3.2.0 pytz==2020.5 requests==2.25.1 requests-oauthlib==1.3.0 scikit-learn==1.0.1 scipy==1.7.2 service-identity==21.1.0 six==1.15.0 sklearn==0.0 social-auth-app-django==4.0.0 social-auth-core==4.1.0 soupsieve==2.1 sqlparse==0.4.1 threadpoolctl==3.0.0 toml==0.10.2 Twisted==21.7.0 twisted-iocpsupport==1.0.2 txaio==21.2.1 typing-extensions==3.10.0.2 uritemplate==3.0.1 urllib3==1.26.3 waitress==2.0.0 whitenoise==5.3.0 wrapt==1.12.1 zope.interface==5.4.0 above is the content of the file after running the command pip freeze > requirements.txt. I am new to django any help will be apreciated! -
Django tests pass locally but not on Github Actions push
My tests pass locally and in fact on Github Actions it also says "ran 8 tests" and then "OK" (and I have 8). However, the test stage fails due to a strange error in the traceback. Traceback (most recent call last): File "/opt/hostedtoolcache/Python/3.9.9/x64/lib/python3.9/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) File "/opt/hostedtoolcache/Python/3.9.9/x64/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 421, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: near "SCHEMA": syntax error The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/runner/work/store/store/manage.py", line 22, in <module> main() File "/home/runner/work/store/store/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/opt/hostedtoolcache/Python/3.9.9/x64/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/opt/hostedtoolcache/Python/3.9.9/x64/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/hostedtoolcache/Python/3.9.9/x64/lib/python3.9/site-packages/django/core/management/commands/test.py", line 23, in run_from_argv super().run_from_argv(argv) File "/opt/hostedtoolcache/Python/3.9.9/x64/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/opt/hostedtoolcache/Python/3.9.9/x64/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/opt/hostedtoolcache/Python/3.9.9/x64/lib/python3.9/site-packages/django/core/management/commands/test.py", line 55, in handle failures = test_runner.run_tests(test_labels) File "/opt/hostedtoolcache/Python/3.9.9/x64/lib/python3.9/site-packages/django/test/runner.py", line 736, in run_tests self.teardown_databases(old_config) File "/opt/hostedtoolcache/Python/3.9.9/x64/lib/python3.9/site-packages/django_heroku/core.py", line 41, in teardown_databases self._wipe_tables(connection) File "/opt/hostedtoolcache/Python/3.9.9/x64/lib/python3.9/site-packages/django_heroku/core.py", line 26, in _wipe_tables cursor.execute( File "/opt/hostedtoolcache/Python/3.9.9/x64/lib/python3.9/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/opt/hostedtoolcache/Python/3.9.9/x64/lib/python3.9/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "/opt/hostedtoolcache/Python/3.9.9/x64/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/opt/hostedtoolcache/Python/3.9.9/x64/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__ raise … -
Django "__str__ returned non-string (type tuple)"
I've seen similar problems but still cannot solve mine. I'm making e-commerce ticket system. Here's the code. class Event(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, db_index=True) banner = models.ImageField(upload_to='banners/' ,null=True, blank=True) description = models.TextField(blank=True) address = models.CharField(max_length=255) slug = SlugField(max_length=255, blank=True) event_date_time = models.DateTimeField() price_1 = models.DecimalField(max_digits=5, decimal_places=2) pool_1 = models.IntegerField() pool_date_1 = models.DateTimeField() price_2 = models.DecimalField(max_digits=5, decimal_places=2) pool_2 = models.IntegerField() pool_date_2 = models.DateTimeField() price_3 = models.DecimalField(max_digits=5, decimal_places=2) pool_3 = models.IntegerField() def __str__(self): return ( self.id, self.name, self.banner, self.description, self.address, self.slug, self.event_date_time, self.price_1, self.pool_1, self.pool_date_1, self.price_2, self.pool_2, self.pool_date_2, self.price_3, self.pool_3 ) class Ticket(models.Model): id = models.AutoField(primary_key=True) event = models.ForeignKey(Event, related_name='ticket', on_delete=models.CASCADE) slug = SlugField(max_length=255, blank=True) date_sold = models.DateTimeField() price = models.DecimalField(max_digits=5, decimal_places=2) bought_by = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, related_name='buyer') promotor = models.CharField(max_length=4, blank=True) def __str__(self): return ( self.id, self.slug, self.date_sold, self.price ) I'm not sure which one of those values returns error, could someone please explain to me which value and why returns tuple? I've tried many combinations and was still not able to solve it.