Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django not showing images in editor (404 error)
I'm try create post and add to this post images. And i'm use for this Django-summernote in Django 3.0. Picture upload to folder on hard disk, but not showing in editor. Console show 404 Error. Please, give me advice how to fix it? Thank you! settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' ADMIN_MEDIA_PREFIX = STATIC_URL + "grappelli/" X_FRAME_OPTIONS = 'SAMEORIGIN' SUMMERNOTE_THEME = 'bs4' # Show summernote with Bootstrap4 MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py urlpatterns = [ path('admin/filebrowser/', site.urls), path('summernote/', include('django_summernote.urls')), path('admin/', admin.site.urls), path('', include('blog.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) image = models.ImageField(upload_to="", blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def get_absolute_url(self): return "/api/article/%i/" % self.id def __str__(self): return self.title screenshot from console -
UUID fails unit pytest due to formatting?
I am returning a user's UUID in my serializier and this works fine. However, when writing a unit test to test this return the test fails despite them being called the same way. Below is a simplified version of my code. My serializers.py: class UserSerializer(serializers.ModelSerializer): user_sso = serializers.SerializerMethodField("get_user_sso") class Meta: model = get_user_model() fields = ( "user_sso", ) def get_user_sso(self, user): return user.profile.sso_id My unit test in test_views.py class TestUserAPIView(BaseAPIViewTest): factory = factories.UserFactory def expected_response(self, user): return { "user_sso": user.profile.sso_id, } The failed test message (the user generated from a factory is the top one): E - 'user_sso': UUID('f696d740-bdd5-43a3-8f58-406b7a1e117d')}, E ? ----- - E + 'user_sso': 'f696d740-bdd5-43a3-8f58-406b7a1e117d'}, How do I make this test pass? I do not have the word 'UUID(' at the begining of my current output which looks to be the problem but I'm not sure how to remove this without everything a string? Many thanks. -
Why is Elastic beanstalk app creation failing at [InstallDependency] python3.8
I've rebuilt the requirements.txt multiple times, and removed and re-created pipenv, but still every time I build the deployment package for elastic beanstalk, the deployment fails giving this error: 2021/12/14 18:31:40.411896 [ERROR] An error occurred during execution of command [app-deploy] - [InstallDependency]. Stop running the command. Error: fail to install dependencies with Pipfile file with error Command /bin/sh -c /usr/bin/python3.8 -m pipenv install --skip-lock failed with error exit status 1. Stderr:Warning: Your Pipfile requires python_version 3.8, but you are using unknown (/var/app/s/.venv/bin/python). $ pipenv --rm and rebuilding the virtual environment may resolve the issue. $ pipenv check will surely fail. Error while executing command /var/app/staging/.venv/bin/python -c import sysconfig, distutils.sysconfig, io, json, sys; paths = {u'purelib': u'{0}'.format(distutils.sysconfig.get_python_lib(plat_specific=0)),u'stdlib': u'{0}'.format(sysconfig.get_path('stdlib')),u'platlib': u'{0}'.format(distutils.sysconfig.get_python_lib(plat_specific=1)),u'platstdlib': u'{0}'.format(sysconfig.get_path('platstdlib')),u'include': u'{0}'.format(distutils.sysconfig.get_python_inc(plat_specific=0)),u'platinclude': u'{0}'.format(distutils.sysconfig.get_python_inc(plat_specific=1)),u'scripts': u'{0}'.format(sysconfig.get_path('scripts')),u'py_version_short': u'{0}'.format(distutils.sysconfig.get_python_version()), }; value = u'{0}'.format(json.dumps(paths));fh = io.open('/tmp/tmpn2omzq7a.json', 'w'); fh.write(value); fh.close():Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/pipenv/vendor/vistir/misc.py", line 513, in _create_subprocess c = _spawn_subprocess( File "/usr/local/lib/python3.8/site-packages/pipenv/vendor/vistir/misc.py", line 190, in _spawn_subprocess return subprocess.Popen(cmd, **options) File "/usr/lib64/python3.8/subprocess.py", line 854, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File "/usr/lib64/python3.8/subprocess.py", line 1702, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) OSError: [Errno 8] Exec format error: '/var/app/staging/.venv/bin/python' Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/pipenv/vendor/vistir/contextmanagers.py", line 205, in spinner yield _spinner File "/usr/local/lib/python3.8/site-packages/pipenv/vendor/vistir/misc.py", line 618, in run … -
Django Serializer only serializing objects with many=True
I am trying to make a serializer class StoreSerializer(serializers.ModelSerializer): class Meta: model = Store fields = '__all__' and in the viewset, def list(self, request, *args, **kwargs): obj = Store.objects.first() ser = StoreSerializer(data=obj) if ser.is_valid(): pass print(ser.data) return Response(ser.data) this method is returning just an empty dict {} as the response. When defining the serializer as ser = StoreSerializer(data=[obj], many=True) the object is getting serialized. What am I doing wrong here? -
Django-import-export-celery Import error [Errno 13] Permission denied
I have a minor issue where I always see an error 13: Import error [Errno 13] Permission denied: '/_/_/_/media/django-import-export-celery-import-change-summaries' I can still import but I cannot see the end HTML template. It's supposed to look like this (on my windows localhost): I believe this is an Ubuntu file permission issue but I do not want to do anything because as I understand it, granting permissions on a production server is dangerous. Any help is appreciated. Thanks! -
OperationalError: no such table: users_profile in Django
I am trying to create an extend User model but when I start the server I get an OperationalError: no such table: users_profile. Here is a structure of the project: │ db.sqlite3 │ manage.py │ ├───ithogwarts │ │ asgi.py │ │ settings.py │ │ urls.py │ │ wsgi.py │ │ __init__.py │ │ │ └───__pycache__ │ ├───main │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ urls.py │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ │ __init__.py │ │ │ │ │ └───__pycache__ │ │ │ ├───static │ │ └───main │ │ ├───css │ │ │ footer.css │ │ │ header.css │ │ │ index.css │ │ │ │ │ ├───img │ │ │ │ │ └───js │ │ script.js │ │ │ ├───templates │ │ └───main │ │ index.html │ │ layout.html │ │ level_magic.html │ │ │ └───__pycache__ │ ├───templates │ └───registration └───users │ admin.py │ apps.py │ forms.py │ models.py │ tests.py │ urls.py │ utils.py │ views.py │ __init__.py │ ├───migrations │ │ 0001_initial.py │ │ __init__.py │ │ │ └───__pycache__ │ ├───static │ └───users │ └───css │ login.css │ register.css │ ├───templates │ └───users │ login.html … -
Add some data to extra_context in response_change
I have some model: from django.db import models class Deviation(models.Model): name = models.CharField(max_length=100) def calc(self): # some calculation return 1 Then I added a button that runs calc method (overrided change form): {% extends 'admin/change_form.html' %} {% block submit_buttons_bottom %} {{ block.super }} <div class="submit-row"> <input type="submit" value="Calculate" name="calc"> </div> Calculation result: {{ result }} {% endblock %} This model is registered in admin with handling calc button submit (pass result in extra_context): @admin.register(Deviation) class DeviationAdmin(admin.ModelAdmin): change_form_template = 'admin/deviations_change_form.html' list_display = '__str__', def response_change(self, request, obj): if "calc" in request.POST: obj.save() result = obj.calc() return self.change_view(request, str(obj.id), form_url='', extra_context={'result': result}) return super().response_change(request, obj) Here problem happening. I cannot render change view with result through extra_context. How can I pass extra_context to change view? -
ModuleNotFoundError: No module named 'api' (heroku)
tree ├───pzApi │ │ asgi.py │ │ db.sqlite3 │ │ manage.py │ │ settings.py │ │ urls.py │ │ wsgi.py │ │ __init__.py │ │ │ └───api │ │ apps.py │ │ funcs.py │ │ urls.py │ │ views.py │ │ __init__.py Procfile release: python pzApi/manage.py migrate web: gunicorn --bind 127.0.0.1:8000 pzApi.wsgi:application I'm still trying to deploy this web app and after fixing the wsgi.py not found error by putting it in the same dir as manage.py, now I have another problem where the 'api' folder is not being found, any help is appreciated! -
How to clear a ManyToMany Field in a patch request?
My ManyToMany Relationship doesn't reset. I'm doing a patch requests that translates into djrf's partial_update. But afterwards RecordUsersEntry still has the same users saved it got from setup_entry. I've tried a put request with field and record, and then the many to many relationship is resetted, but I want to reset it with a patch request. Might be related to: https://github.com/encode/django-rest-framework/issues/2883, however I'm going to use JSON Requests and at the moment I'm only concerned about how to get this test green. I've written the follwing test: def test_entry_update(self): self.setup_entry() view = RecordUsersEntryViewSet.as_view(actions={'patch': 'partial_update'}) data = { 'users': [] } request = self.factory.patch('', data=data) force_authenticate(request, self.user) response = view(request, pk=1) self.assertEqual(response.status_code, 200) entry = RecordUsersEntry.objects.first() self.assertEqual(entry.users.all().count(), UserProfile.objects.none().count()) # <-- The test fails here with def setup_entry(self): self.entry = RecordUsersEntry.objects.create(record=self.record, field=self.field) self.entry.users.set(UserProfile.objects.all()) and the model looks like this: class RecordUsersEntry(RecordEntry): record = models.ForeignKey(Record, on_delete=models.CASCADE, related_name='users_entries') field = models.ForeignKey(RecordUsersField, related_name='entries', on_delete=models.PROTECT) users = models.ManyToManyField(UserProfile, blank=True) class Meta: unique_together = ['record', 'field'] verbose_name = 'RecordUsersEntry' verbose_name_plural = 'RecordUsersEntries' def __str__(self): return 'recordUsersEntry: {};'.format(self.pk) Viewsets and Serializer just being the basic ones: class RecordUsersEntryViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, GenericViewSet): queryset = RecordUsersEntry.objects.none() serializer_class = RecordUsersEntrySerializer def get_queryset(self): # every field returned because they are supposed to … -
Unable to see messages using django register
I have an app with views.py as follows from django.shortcuts import render,redirect from django.contrib.auth.models import User, auth from django.contrib import messages # Create your views here. def register(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] password1 = request.POST['password1'] password2 = request.POST['password2'] email = request.POST['email'] if password1==password2: if User.objects.filter(username=username).exists(): messages.info(request,'username taken') return redirect('register') elif User.objects.filter(email=email).exists(): messages.info(request,'email taken') return redirect('register') else: user= User.objects.create_user(username=username, password=password1, email=email, first_name=first_name,last_name=last_name) user.save(); print('user created') else: print('password missmatch') return redirect('register') return redirect('/') else: return render(request,'register.html') I have added a for loop for showing the messages in register.html {% for message in messages %} <h3> {{message}} </h3> {% endfor %} I can't able to see messages when the for loop is available but i can see message address when for loop is removed. Can some explain and help me how to proceed? -
Django: Help converting Flask app: How/where to refer to main.py?
I've set up all the foundational pages/folders for a Django app, including a bunch of html templates, admin.py, apps.py, models.py, settings.py, urls.py, views.py, etc. They work fine to pull up the menu.html template without errors. But my main py file, which I call index.py, which has most of my functionality: How and where do I refer to it? Thanks! -
How can i submit two forms in django
I have a template where i should have 2 forms and update them, I succeded to get the 2 foms in the same template, but when i make changes nothing happens ! forms.py class OrderManageForm(forms.ModelForm): class Meta: model = Order fields = ['customer', 'product', 'quantity', 'status'] class CustomerForm(forms.ModelForm): address = forms.CharField(widget=forms.Textarea(attrs={'rows': 5})) class Meta: model = Customer fields = ['full_name', 'address', 'phone', 'city', 'email' models.py class Customer(models.Model): full_name = models.CharField(max_length=150) address = models.CharField(max_length=1500, null=True) phone = models.CharField(max_length=20) city = models.CharField(max_length=100) email = models.EmailField(null=True) def __str__(self): return self.full_name class Order (models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE,) quantity = models.IntegerField(default=1) status = models.TextField(choices=ORDER_STATUS, default='Pending') def __str__(self): return 'Order n°: ' + str(self.id) views.py def update_order(request, order_id): order = get_object_or_404(Order, id=order_id) cust = get_object_or_404(Customer, order__id=order_id) if request.method == 'POST': customer = CustomerForm(request.POST) form = OrderManageForm(request.POST) print(request.POST) if form.is_valid() and customer.is_valid(): order = form.save(commit=False) customer = customer.save() order.customer = customer order.save() return redirect('orders') else: form = OrderManageForm(instance=order) customer = CustomerForm(instance=cust) return render(request, 'dashboard/order_details.html', {'form': form, 'customer': customer}) I put the 2 forms in only one form tag inside my HTML template -
Write an Effective query for django for a FOR Loop?
I need to get number of policies bought in each month from these model class Insurance(models.Model): #other fields.. date_purchased_on = models.DateField(auto_now_add=True) customer_region = models.CharField( max_length=10, choices=RegionType.choices) so i have written a views to get a response @api_view(['GET']) def chart_data(request): # structure of the op should be all the months from 1 to 12 # [{"month": 1,"count": 100,}, { "month:2", "count":20}] filtered_data = [] for i in range(1, 13): query = Insurance.objects.filter(date_purchased_on__month=i).count() data = { "month": i, "count": query } filtered_data.append(data) return Response(filtered_data) now the problem is this query hits the database every time its like 12 times. is there a way to handle this to get in a single query or to reduce it and my logger results (0.000) SELECT COUNT(*) AS "__count" FROM "insurance_insurance" WHERE EXTRACT('month' FROM "insurance_insurance"."date_purchased_on") = 1; args=(1,); alias=default (0.000) SELECT COUNT(*) AS "__count" FROM "insurance_insurance" WHERE EXTRACT('month' FROM "insurance_insurance"."date_purchased_on") = 2; args=(2,); alias=default (0.000) SELECT COUNT(*) AS "__count" FROM "insurance_insurance" WHERE EXTRACT('month' FROM "insurance_insurance"."date_purchased_on") = 3; args=(3,); alias=default (0.000) SELECT COUNT(*) AS "__count" FROM "insurance_insurance" WHERE EXTRACT('month' FROM "insurance_insurance"."date_purchased_on") = 4; args=(4,); alias=default (0.000) SELECT COUNT(*) AS "__count" FROM "insurance_insurance" WHERE EXTRACT('month' FROM "insurance_insurance"."date_purchased_on") = 5; args=(5,); alias=default (0.000) SELECT COUNT(*) AS "__count" FROM "insurance_insurance" … -
ProcFile declares types -> (none) ProcFile
I want to host Django server over heroku and my procfile looks like this web: gunicorn DjangoHerokuApp.Portfoliowebapp.wsgi and this my file structure both procfile and requirements.txt are in root folder enter image description here and it is giving me this error continously Procfile declares types -> (none) and this my requirements.txt asgiref==3.4.1 Django==4.0 gunicorn==20.1.0 sqlparse==0.4.2 tzdata==2021.5 Please Help ! I am stuck at this for 2 days -
How to post an image in django server using tiny mce editor? Note: I have integrated the tiny mce editor in a simple html page
I have designed a simple html webpage. Where I've integrated tinymce editor. Someone gave me a uri, Where I need to post an image from tinymce editor to django server by using a uri.In response the server will return a url. That url I need to show in success message. How to do that? -
How does payment work while shopping on a webpage with Django?
I am creating a shopping web app and I'm wondering how does it work? How do I connect my page to the credit card and how does it take money from it? How to implement it in Django? Where to send the money that was taken from the credit card itself? You can probably understand now what I need. Thanks in advance. -
Django-summernote not showing images in editor (404 error)
I'm try create post and add to this post images. And i'm use for this Django-summernote in Django 3.0. Picture upload to folder on hard disk, but not showing in editor. Console show 404 Error. Please, give me advice how to fix it? Thank you! settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' ADMIN_MEDIA_PREFIX = STATIC_URL + "grappelli/" X_FRAME_OPTIONS = 'SAMEORIGIN' SUMMERNOTE_THEME = 'bs4' # Show summernote with Bootstrap4 #MEDIA_ROOT = os.path.join(BASE_DIR, 'blog/media/') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py urlpatterns = [ path('admin/filebrowser/', site.urls), path('summernote/', include('django_summernote.urls')), path('admin/', admin.site.urls), path('', include('blog.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) image = models.ImageField(upload_to="", blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def get_absolute_url(self): return "/api/article/%i/" % self.id def __str__(self): return self.title screenshot from console -
Combining DetailView and CreateView in Django 3.2/4.0, as explained in the docs
I'm building a generic blog and trying to enable users to make comments directly on the article page. I am trying to implement this by combining DetailView with CreateView. The docs present 3 different solutions to this issue: FormMixin + DetailView: this is the answer that Django docs advise against, but that is advised by most answers on SO that I could find DetailView only + write the post method: "a better solution" according to Django docs DetailView + FormView: "an alternative better solution", and the one I'm trying to implement. The "alternative better" solution consists in making a DetailView for articles and a FormView for comments, but the docs state that "This approach can also be used with any other generic class-based views", which means that DetailView + CreateView should be possible. I've gone through a number of SO items that reference this solution, but I am unable to implement any of them. This SO question suggests mixing DetailView and CreateView. However, the explanation in that answer is incomplete. Another SO question, among advice to use FormMixins, has this answer that is close, but different. Other questions (1, 2, etc.) only address the FormMixin and DetailView + post methods. … -
How to divide [filtered list by date(from_date, to_date)] by day. Django
i want to display information about likes. I filtered a model (from_date, to_date) and got list of all likes during this time. Now I need to sort and divide it somehow to make it looks something like this: [ { date: 2021-12-10, likes:[ { user: user1, post: post1 }, { user: user1, post: post1 } ] }, { date: 2021-12-11, likes:[ { user: user1, post: post1 }, ] } ] Could you please give me some advices how it is possible to do. models.py class LikesActivity(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.post} liked by {self.user}, {self.created}" class Meta: verbose_name = 'Likes activity' verbose_name_plural = 'Likes activities' views.py class LikesActivityRangeFilter(APIView): def get(self, request, from_year, from_month, from_day, to_year, to_month, to_day): from_date = f"{from_year}-{from_month}-{from_day}" to_date = f"{to_year}-{to_month}-{to_day}" likes = LikesActivity.objects.filter( created__range=[from_date, to_date]).order_by('created') serializer = LikesActivitySerializer(likes, many=True) return Response(serializer.data) -
ModuleNotFoundError: No module named 'ithogwarts.users' in Django
I am trying to create an extend User model but when I start the server I get a ModuleNotFoundError: No module named 'ithogwarts.users'. Here is a structure of the project: │ db.sqlite3 │ manage.py │ ├───ithogwarts │ │ asgi.py │ │ settings.py │ │ urls.py │ │ wsgi.py │ │ __init__.py │ │ │ └───__pycache__ │ ├───main │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ urls.py │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ │ __init__.py │ │ │ │ │ └───__pycache__ │ │ │ ├───static │ │ └───main │ │ ├───css │ │ │ footer.css │ │ │ header.css │ │ │ index.css │ │ │ │ │ ├───img │ │ │ │ │ └───js │ │ script.js │ │ │ ├───templates │ │ └───main │ │ index.html │ │ layout.html │ │ level_magic.html │ │ │ └───__pycache__ │ ├───templates │ └───registration └───users │ admin.py │ apps.py │ forms.py │ models.py │ tests.py │ urls.py │ utils.py │ views.py │ __init__.py │ ├───migrations │ │ 0001_initial.py │ │ __init__.py │ │ │ └───__pycache__ │ ├───static │ └───users │ └───css │ login.css │ register.css │ ├───templates │ └───users │ login.html … -
value error. model field must be an instance django
I want to save a list of the relational objects using IDs but unfortunately, I'm getting an error from Django which I attached below. error: Cannot assign "[<Tag: Tag object (189)>, <Tag: Tag object (190)>]": "PackageRoom.tag" must be a "Tag" instance. models.py class Tag(models.Model): name = models.CharField(max_length=255, default='') description = models.CharField(max_length=255, default='') singleline = models.ManyToManyField(Singleline) class Meta: db_table = 'tags' class PackageRoom(models.Model): name = models.CharField(max_length=255, default='') tag = models.ForeignKey(Tag, on_delete=models.PROTECT) class Meta: db_table = 'package_rooms' serializers.py class PackageRoomSerializer(serializers.ModelSerializer): tag = serializers.PrimaryKeyRelatedField(queryset=Tag.objects.all(), many=True) class Meta: model = PackageRoom fields = ['id', 'name', 'description', 'tag'] views.py serializer = PackageRoomSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() JSON object which is sent from Frontend: { "name": "example room", "description": "lorem lipsum", "tag": [189, 190] } -
How to resolve this error code below, RelatedObjectDoesNotExist
class Following(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='following', unique=False, verbose_name=('User'), on_delete=models.CASCADE) following_user = models.ManyToManyField(settings.AUTH_USER_MODEL, verbose_name=('Following'), related_name='following_user') created_on = models.DateTimeField(default=timezone.now) class FollowingSerializer(serializers.ModelSerializer): new_following = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(),required=True,write_only=True) class Meta: model = Following fields = [ 'id', 'user', 'following_user', 'new_following', 'created_on' ] read_only_fields = ['following_user'] def create(self, validated_data): user = validated_data['user'] new_following = validated_data['new_following'] user.following.following_user.add(new_following) new_following.followers.following_user.add(user) return user.following class FollowingAPIView(mixins.CreateModelMixin, mixins.DestroyModelMixin,generics.GenericAPIView): permission_classes = [permissions.IsAuthenticated] serializer_class = FollowingSerializer def get_queryset(self): queryset = Following.objects.all() return queryset def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return self.destroy(self, request, *args, **kwargs) This is the full error message. RelatedObjectDoesNotExist at /api/following/ User has no following. Request Method: POST Request URL: http://127.0.0.1:8000/api/following/ Django Version: 3.2.7 Exception Type: RelatedObjectDoesNotExist Exception Value: User has no following. Exception Location: C:\Users\user\Desktop\myhallel-project\venv\lib\site-packages\django\db\models\fields\related_descriptors.py, line 421, in get Python Executable: C:\Users\user\Desktop\myhallel-project\venv\Scripts\python.exe Python Version: 3.9.6 Python Path: ['C:\Users\user\Desktop\myhallel-project\myhallel', 'C:\Users\user\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\user\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\user\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\user\AppData\Local\Programs\Python\Python39', 'C:\Users\user\Desktop\myhallel-project\venv', 'C:\Users\user\Desktop\myhallel-project\venv\lib\site-packages'] -
django_heroku.settings(locals()) KeyError: 'MIDDLEWARE' and 'MIDDLEWARE_CLASSES'
settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ALLOWED_HOSTS = ['my-app.herokuapp.com', '127.0.0.1:8000', 'localhost'] django_heroku.settings(locals()) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'build/assets') ] error (2 exceptions) remote: Traceback (most recent call last): remote: File "/app/.heroku/python/lib/python3.9/site-packages/django_heroku/core.py", line 97, in settings remote: config['MIDDLEWARE_CLASSES'] = tuple(['whitenoise.middleware.WhiteNoiseMiddleware'] + list(config['MIDDLEWARE_CLASSES'])) remote: KeyError: 'MIDDLEWARE_CLASSES' remote: django_heroku.settings(locals()) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django_heroku/core.py", line 99, in settings remote: config['MIDDLEWARE'] = tuple(['whitenoise.middleware.WhiteNoiseMiddleware'] + list(config['MIDDLEWARE'])) remote: KeyError: 'MIDDLEWARE' I am trying to deploy my web app but I am getting this error everytime, cannot find a solution anywhere... nothing wrong with the Procfile, requirements.txt and runtime.txt, any help is appreciated! -
Creating Multible IDs for multible Buttons in one <Input> Tag
I'm working on a TicTacToe game using Django/Djangotemplates, Python and a bit Javascript. I've come across a problem tho. i only have one Button which is for-looped 9 times. its ID is its index. Now I'm not certain how to add the {{index}} which i defined in the for loop in the javascript onclick function. here the html template <div class="grid-container"> {% for index in object.board %} <div class="grid-item"> <input onclick="change(button.id)" class="buttonsize btn-outline-purple" type="submit" value="" name="button" id="{{index}}"> </div> {% endfor %} </div> </div> </article> </form> <script> function change(inputid){ console.log("test") var elem = document.getElementById(inputid); if (elem.value=="") elem.value = "X" } </script> here the models.py class TicTacToe(models.Model): player1 = models.ForeignKey(User, on_delete=models.CASCADE, default="X", related_name="tictactoe_as_player1") player2 = models.ForeignKey(User, on_delete=models.CASCADE, default="O", related_name="tictactoe_as_player2") current_player = models.ForeignKey(User, on_delete=models.CASCADE, related_name="tictactoe_current_player") title = models.CharField(max_length=100) board = models.CharField(max_length=9, default="012345678") def __str__(self): return self.title def get_absolute_url(self): return reverse('tictactoe-detail', kwargs={'pk': self.pk}) and here the views.py class TicTacToeCreateView(LoginRequiredMixin, CreateView): model = TicTacToe template_name = 'website/newgame_form.html' fields = ['player1', 'player2', 'current_player', 'title', 'board'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class TicTacToeDetailView(UpdateView): model = TicTacToe fields = ['player1', 'player2', 'current_player', 'title', 'board'] def clean(self): if 'button0' in self.data: print('button0') i also got a database but there is really not much in there except … -
File Uploading in deployed Django applications
Where to store the images when a Django application is deployed through "Heroku" if I need to upload images using the same application after deployment ? Amazon S3 services provide a solution but the file accessing urls has a certain expiry period, so after maximum of 7days I cannot access the file using the same URL