Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Generic m2m relation or two m2m relations?
I'm building a Movie database. The thing is each movie can have many producers and many directors. The directors can be either persons or collectives, and the producers might be persons, collectives or institutions (or a mixture of all these things). I also want to store different information for these kinds of entities (persons, collectives and institutions). Furthermore, I need: To have order (director1, director2) is different from (director2, director1) The admin to be able to handle producer/director adding, modifying, etc. from the Movie module. To organize my models I've thought of having a generic m2m relation (inspired in this answer) --only for directors, to simplify: class Movie(models.Model): name = models.CharField(max_length=100) # etc... class Person(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) director_of = GenericRelation('Directorship') class Collective(models.Model): name = models.CharField(max_length=100) number_of_participants = models.IntegerField() director_of = GenericRelation('Directorship') class Directorship(models.Model): movie = models.ForeignKey(Movie, on_delete=models.CASCADE, related_name='directors') content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') order = models.PositiveIntegerField() The problem with this solution is that the Movie admin with a Directorship inline looks awful: I could customize the admin form to display a specific ModelForm depending on the choice of the first combobox, but that looks like an awful lot of work … -
POST method not being submitted by form django
I have two radio buttons and i want one of them to be selected and send to my Django views.py template.I can't use django.forms for specific reasons.The page hardwareq1 is linked to hardware1 in urls.py .My problem is a None Object is sent to the backend after i press submit. Please tell what is wrong with my code. HTML:- <form action="{% url 'hardwareq1' %}" method="POST"> <label class="btn btn-success"> <input type="radio" id="control_1" name="question_type" value="Indoor" />Indoor </label> <label class="btn btn-success" > <input type="radio" id="control_1" name="question_type" value="Outdoor" />Outdoor </label> <input type="submit" value="Submit" class="btn btn-secondary btn-block" /> </form> urls.py path('hardwareq1',views.hardware1,name='hardwareq1'), views.py:- def hardware1(req): h=HardwareModel.objects.all().filter(productid=1) print(req.POST.get('question_type')) if req.method=='POST': h.q1=req.POST.get('question_type') h.save(force_update=True) context={ 'hardware':h } return render(req,'pages/shardware1.html',context) -
AttributeError: 'module' object has no attribute 'lru_cache' in Apache using Python3
I'm having trouble running my Django application through Apache. Running Django on the built in development server works fine, as does serving html files directly through Apache. I originally had the error 'no module named django.core.wsgi' which I remedied by updating the WSGIPythonHome directive to point to the python3.6/site-packages directory. After doing this from looking at the traceback the server appears able to locate django.core.wsgi but now throws the error: AttributeError: 'module' object has no attribute 'lru_cache' I read it could potentially be a Python2 / Python3 issue with Apaches version of mod_wsgi so I reconfigured Apache and reran make, make install but no luck there. I found the same question posted here: AttributeError: 'module' object has no attribute 'lru_cache' and tried the recommended solution of removing libapache2-mod-wsgi and installing libapache2-mod-wsgi-py3 both system wide and within the virtual environment I'm pointing to in my httpd.conf file. This didn't fix the issue either. What could be the cause ? Help is greatly appreciated ! Full traceback: [Sat Jun 06 10:00:57.085731 2020] [wsgi:error] [pid 14226:tid 139691700082432] [client 127.0.0.1:60174] Traceback (most recent call last):, referer: http://127.0.1.1/ [Sat Jun 06 10:00:57.085749 2020] [wsgi:error] [pid 14226:tid 139691700082432] [client 127.0.0.1:60174] File "/WEBPAGE/myproject/wsgi.py", line 12, in <module>, … -
django.db.utils.IntegrityError: UNIQUE constraint failed: core_user.email
I'm trying to do a unit test for my model, but it kept throwing IntegrityError. I've researched many articles and in StackOverflow to find solutions but couldn't find. I am trying to create a unit test for the admin app of Django application Commands to reproduce: docker-compose runs app sh -c "python manage.py test" This is the output: ====================================================================== ERROR: test_users_listed (core.tests.test_admin.AdminSiteTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: UNIQUE constraint failed: core_user.email The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/core/tests/test_admin.py", line 14, in setUp self.user = get_user_model().objects.create_user( File "/app/core/models.py", line 11, in create_user user.save(using=self._db) File "/usr/local/lib/python3.9/site-packages/django/contrib/auth/base_user.py", line 66, in save super().save(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 745, in save self.save_base(using=using, force_insert=force_insert, File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 782, in save_base updated = self._save_table( File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 887, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 924, in _do_insert return manager._insert( File "/usr/local/lib/python3.9/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 1204, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "/usr/local/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1392, in execute_sql cursor.execute(sql, params) File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 68, … -
How can I select two ranges of the same field in Django?
With the following model: class Event(models.Model): latitude = models.FloatField() longitude = models.FloatField() I would like to execute the following logic: Select all events where latitude is in range(float1, float2) or in range (float3, float4) This looks like this in SQL: SELECT * FROM event WHERE latitude (BETWEEN float1 and float2) or (BETWEEN float3 and float4); I tried this in Django but I get a "SyntaxError: keyword argument repeated": Events.objects.filter(latitude__range(float1, float2), latitude__range(float3, float4) -
my detail view is updating but not redirecting me to my blog post Django
i have a single Blog,which is still the main Detailview,so i am trying to add class base view,for CRUD,so i redirected my detailview to my blogpost,but when i add new post it will only show the pagination,but the post will already be added to my blogpost not until i go to the blog home page,even when i search blog with http://127.0.0.1:8000/pages/blog/22/?= , but wont show the post views.py class BlogDetailView(DetailView): model = Blog template_name = 'pages/blog.html' context_object_name = 'blog' ordering = ['-timestamp'] urls.py path('blog/', blog, name='blog'), path('blog/<int:pk>/', BlogDetailView.as_view(), name='blog'), -
how to call function based view using DefaultRouter in?
I tried to run run server in Django but unfortunately i have got an error AttributeError: 'function' object has no attribute 'get_extra_actions'. urls.py here is the url file where router is defined for the view. from rest_framework.routers import DefaultRouter from django.conf.urls import url, include from enable_app import views router = DefaultRouter() router.register(r'practice', views.practice, basename='practice') url patterns = [ url(r'^', include(router.urls)), ] views.py here is the views file where function based view is written from rest_framework.response import Response from rest_framework import viewsets def practice(request): return Response('hello world') here is the errors. errors Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/getmyparking/PycharmProjects/enable_practice/venv_prac/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/getmyparking/PycharmProjects/enable_practice/venv_prac/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/Users/getmyparking/PycharmProjects/enable_practice/venv_prac/lib/python3.7/site-packages/django/core/management/base.py", line 395, in check include_deployment_checks=include_deployment_checks, File "/Users/getmyparking/PycharmProjects/enable_practice/venv_prac/lib/python3.7/site-packages/django/core/management/base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "/Users/getmyparking/PycharmProjects/enable_practice/venv_prac/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/Users/getmyparking/PycharmProjects/enable_practice/venv_prac/lib/python3.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/Users/getmyparking/PycharmProjects/enable_practice/venv_prac/lib/python3.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/Users/getmyparking/PycharmProjects/enable_practice/venv_prac/lib/python3.7/site-packages/django/urls/resolvers.py", line 407, in check for pattern in self.url_patterns: File "/Users/getmyparking/PycharmProjects/enable_practice/venv_prac/lib/python3.7/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/getmyparking/PycharmProjects/enable_practice/venv_prac/lib/python3.7/site-packages/django/urls/resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, … -
CSRF verification always fails when accessing Django admin page through nginx proxy
I have gunicorn serving a Django (v3.0.6) project on my server (at port 8000). I have the host name (and variations on localhost) in the ALLOWED_HOSTS variable of my Django project. And I have nginx set up to serve various apps within my Django project via a reverse proxy, like this: location /guestbook/ { proxy_pass http://localhost:8000/guestbook/ ; } These all seem to work just fine, for the record. What isn't working fine is the Django admin app. Initially I set it up with a very simple reverse proxy as shown above, but over time, as I was experiencing problems with it, I started incorporating various suggestions I found online until now it looks like this: location /admin/ { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-NginX-Proxy true; proxy_set_header Upgrade $http_upgrade; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://localhost:8000/admin/ ; } but my problem persists: If I visit the admin site (via the nginx proxy) remotely after clearing all my cookies, the admin page loads just fine. I type in my login credentials, hit "login" and nothing happens. If I hit login again, the CSRF verification fails, and if I have DEBUG set to True Django says the CSRF … -
Django REST Framework. Keep getting KeyError in all the methods
After some time of testing my Django REST Api i started to get KeyError when using request.data. The problem didn't occured before that, it just randomly started to happen. Im using Python 3.8 and Django REST 3.11 Here are my serializers and views. I'll appreciate any help. serializers.py class InterestSerializer(serializers.ModelSerializer): class Meta: model = Interest fields = '__all__' class UserIntrestSerializer(serializers.ModelSerializer): interest = InterestSerializer() class Meta: model = UserInterest fields = ('id','interest') views.py class UserInterestView(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserIntrestSerializer def get_user_interests(self, request): try: user = get_object_or_404(User, pk=request.data['id']) interests = UserInterest.objects.all().filter(user__id = user.id) serializer = UserIntrestSerializer(interests, many=True) return Response(serializer.data, status=status.HTTP_200_OK) except MultiValueDictKeyError: return Response("No data given", status=status.HTTP_204_NO_CONTENT) def create_user_interests(self, request): try: user = User.objects.get(pk=request.data['id']) interest_list = [Interest.objects.all().filter(name=interest)[0] for interest in request.data['interests']] print(interest_list) for interest in interest_list: UserInterest(user=user, interest=interest).save() return Response("User interests created properly") except IndexError: return Response("Interest not found", status=status.HTTP_404_NOT_FOUND) except User.DoesNotExist: return Response("User not found") def delete_interest(self, request): try: userinterest = UserInterest.objects.get(interest__name=request.data["interest_name"], user__id=request.data["user_id"]) userinterest.delete() return Response("User's interest deleted properly", status=status.HTTP_200_OK) except UserInterest.DoesNotExist: return Response("User or User's interest not found", status=status.HTTP_404_NOT_FOUND) def update_interest(self, request): try: user = User.objects.get(pk=request.data['id']) current_interests = [user_interest.interest for user_interest in UserInterest.objects.all().filter(user__id=user.id)] new_interests = [Interest.objects.get(name=interest) for interest in request.data['new_interests']] for current_interest in current_interests: if current_interest not in … -
How to display posts on homepage? Django
In my system, admin create posts and I want to display them on homepage with paginators. But when I add homepage, nothing is showing up on the page. When I view source from browser, I cannot see for loop like templates/homepage.html ... <div> {% for post in self.posts %} <div class="panel panel-primary"> <div class="panel-heading text-center"> <a style="color: black"> <h3>{{posts.title}}</h3> </a> </div> <div class="panel-body"> <h4><p class="text-success">Title: <small>{{post.title}}</small></h4> <h4><p class="text-success"> <small>{{post.text}}</small></h4> <h5><p class="text-warning">Created Date: {{post.created_date}}</h5> </div> </div> {% endfor %} </div> <ul> <div class="row" > <div class="col-md-6 col-md-offset-3"> <ul class="pagination"> <div class="pagination"> <span class="step-links pagination"> {% if posts.has_previous %} <li><a href="?page={{ posts.previous_page_number }}{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}">Previous</a> {% endif %}</li> <li ><span class="current"> Page {{ posts.number }} of {{ posts.paginator.num_pages }}. </span></li> <li>{% if posts.has_next %} <a href="?page={{ posts.next_page_number }}{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}">Next</a> {% endif %} </li> </span> </div> </div> </div> </ul> </div> . . . blog/views.py def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') query = request.GET.get('q') if query: posts = posts.filter( Q(title__icontains=query) | Q(text__icontains=query) | Q(created_date__icontains=query) | Q(published_date__icontains=query) ) paginator = Paginator(posts, 5) # Show 5 contacts per page page = request.GET.get('page') try: patients = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver … -
Trying to create a dynamic search/filter table for 25 thousand rows of NBA data using Django, Postgresql, and Jquery
But I have no idea what I'm doing. Now this is how far I've gotten: views.py: statsReg = list(seasonstats.objects.filter(pts__gt=2000).order_by('pts')[0:5].values()) stats = simplejson.dumps(statsReg) return render(request, 'djangotest.html', {'stats': stats}) html: <table border="1", id="players", class="text-center"> <tr> <th>Year</th> <th>Player</th> <th>Pos</th> <th>Age</th> <th>Tm</th> <th>G</th> <th>GS</th> <th>MP</th> <th>PER</th> <th>TS%</th> <th>Points</th> </tr> <tbody id="myTable"></tbody> </table> <script> var myArray = {{ stats|safe }}; buildTable(myArray) function buildTable(data){ var table = document.getElementById('myTable') for (var i = 0; i < data.length; i++){ var row = `<tr> <td>${data[i].year}</td> <td>${data[i].player}</td> <td>${data[i].pos}</td> <td>${data[i].age}</td> <td>${data[i].tm}</td> <td>${data[i].g}</td> <td>${data[i].gs}</td> <td>${data[i].mp}</td> <td>${data[i].per}</td> <td>${data[i].tspercent}</td> <td>${data[i].pts}</td> </tr>` table.innerHTML += row } } </script> So this code displays five rows of statistics correctly in a table on my page, but I have a few questions on where to go from here. My first question is if i'm even accessing postgres with this mode.objects call, I've migrated the model to my database and can browse it in psql, but I just don't get how this works. My second question is how I would alter the query by use of a button to for instance, increase the value in the [0:5] part of the query, or change the filter or order. Any comments would be greatly appreciated! -
WSGI: (11) Couldn't create worker thread
I set up an apache2 server running 2 different django projects as virtual hosts using their own subdomain. Both hosts got their own demon WSGI process. However, when I start the apache2 server only one of those 2 projects run properly. Trying to open the index page of project 2 leads to an endless loading try by the browser. So I checked the error.log of apache2 and saw, that it was full of [wsgi:alert] [pid xxxx:tid xxxxxxx] (11)Resource temporarily unavailable: mod_wsgi (pid=xxxx): Couldn't create worker thread x in project2 process project2 It logs this message every 5 sec. or whenever a request for project 2 comes in. That explains, why there is this infinite waiting loop in the browser, but I don't get, why no thread could be spawned. I already looked around the web for a possible solution, but did not find anything helpfull. Most of the findings were either different problems, had no solution or had a solution that was out of date or used files I can't find on my system. Using top I did not find any unexpectedly high usage of CPU or Memory that could explain, why no thread was spawned. I already tried to … -
Django ModuleNotFoundError: No module named 'architect' when start from docker
When I trying start Django from docker I get an error server_1 | return _bootstrap._gcd_import(name[level:], package, level) server_1 | File "<frozen importlib._bootstrap>", line 1014, in _gcd_import server_1 | File "<frozen importlib._bootstrap>", line 991, in _find_and_load server_1 | File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked server_1 | File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed server_1 | File "<frozen importlib._bootstrap>", line 1014, in _gcd_import server_1 | File "<frozen importlib._bootstrap>", line 991, in _find_and_load server_1 | File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked server_1 | ModuleNotFoundError: No module named 'architect' openfoundation-container_server_1 exited with code 1 But when I run Django manually "python 3 manage.py runserver 7000" then the server starts correctly my dockerfile my docker-compose version: "3" services: server: build: server/ command: "python3 ./manage.py runserver" ports: - 7000:7000 client: build: client/ command: "npm run dev" network_mode: host ports: - 3333:3333 depends_on: - server tree Can u help me please? Thnk! -
DisallowedHost Django deployment in Kubernetes cluster: Invalid HTTP_HOST header
I have a Django deployment for a frontend service in my Azure Kubernetes cluster with some basic configuration. But note that the same question applies for my local Minikube cluster. I fetch my Django frontend container image from my remote container registry and expose port 8010. My service configuration is quite simple as well. frontend.deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: frontend-v1 labels: app: frontend-v1 spec: replicas: 1 selector: matchLabels: app: frontend-v1 template: metadata: labels: app: frontend-v1 spec: containers: - name: frontend-v1 imagePullPolicy: Always image: yourremotename.azurecr.io/frontend-remote:v1 ports: - containerPort: 8010 imagePullSecrets: - name: acr-secret frontend.service.yaml kind: Service apiVersion: v1 metadata: name: frontend-v1 spec: selector: app: frontend-v1 ports: - NodePort: protocol: TCP port: 8010 targetPort: 8010 type: NodePort Now, when I access my deployed frontend service in the browser i.e. http://172.17.194.253:31436 with Django's setting DEBUG = True, I get the error: Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/utils/deprecation.py", line 93, in __call__ response = self.process_request(request) File "/usr/local/lib/python3.6/dist-packages/django/middleware/common.py", line 48, in process_request host = request.get_host() File "/usr/local/lib/python3.6/dist-packages/django/http/request.py", line 122, in get_host raise DisallowedHost(msg) Exception Type: DisallowedHost at / Exception Value: Invalid HTTP_HOST header: '172.17.194.253:31436'. You may need to add '172.17.194.253' to ALLOWED_HOSTS. But … -
error: failed to push some refs to 'https://git.heroku.com/boytalksaboutcoding.git'
I know that there are a lot of questions like this out there, but none match my problem exactly. I recently made a django blog, and I just added staticfiles(pictures, css etc.). When I pushed to Heroku, it gave me this: Enumerating objects: 41, done. Counting objects: 100% (41/41), done. Delta compression using up to 4 threads Compressing objects: 100% (28/28), done. Writing objects: 100% (30/30), 245.74 KiB | 18.90 MiB/s, done. Total 30 (delta 11), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! Python has released a security update! Please consider upgrading to python-3.7.7 remote: Learn More: https://devcenter.heroku.com/articles/python-runtime remote: -----> No change in requirements detected, installing from cache remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: -----> $ python manage.py collectstatic --noinput remote: /app/.heroku/python/lib/python3.7/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. remote: """) remote: Traceback (most recent call last): remote: File "manage.py", line 21, in <module> remote: main() remote: File "manage.py", line 17, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in … -
How do I maintain session across requests in django if I'm using cache / db based session?
I'm implementing a in-memory cache-based session in django: https://docs.djangoproject.com/en/3.0/topics/http/sessions/#using-cached-sessions session_store = SessionStore() session_store['key'] = value session_store.create() but i found that even though the data does persist in memory across multiple requests, but it wont set the session_key in the cookie. Is the intended usage to just pass the key to client and have them send back as a param? right now im manually setting and retrieving the cookie (as request.session['session_key'] doesnt work for me) CREATE response = Response(serializer.data, status=status.HTTP_201_CREATED) response.set_cookie('session_key', session.session_key) RETRIEVE session_key = request.COOKIES['session_key'] -
Stripe does not work correctly - invoice paid but it does not send randomly 'invoice.payment_succeeded' webhook response - bug?
I am using Stripe Webhook and this is phenomenal. I use Stripe webhook in my Django app like this: class StripeView(GenericAPIView): serializer_class = UserNameSerializer def post(self, request): payload = request.body event = None try: event = stripe.Event.construct_from( json.loads(payload), stripe.api_key ) except ValueError as e: # Invalid payload return HttpResponse(status=400) print(event.type) if event.type == 'invoice.payment_succeeded': payment_invoice = event.data.object ... Every single time I use exactly the same method exactly the same way and it is executed without any errors in the same way. It looks like this: customer = stripe.Customer.create( email=user.email, source=request.data['token'] ) subscription = stripe.Subscription.create( customer=customer.id, items=[ { 'plan': 'plan_H8K23228WmaQM', 'quantity': request.data['amount'], }, ], expand=['latest_invoice.payment_intent'], ) Once Stripe generate requests in this way: 2020-06-05 22:48:21 --> payment_method.attached [evt_no] 2020-06-05 22:48:21 <-- [400] POST http://localhost:8007/stripe/ [evt_no] 2020-06-05 22:48:22 --> customer.created [evt_no] 2020-06-05 22:48:22 <-- [400] POST http://localhost:8007/stripe/ [evt_no] 2020-06-05 22:48:23 --> charge.succeeded [evt_no] 2020-06-05 22:48:23 <-- [400] POST http://localhost:8007/stripe/ [evt_no] 2020-06-05 22:48:23 --> invoice.created [evt_no] 2020-06-05 22:48:23 <-- [400] POST http://localhost:8007/stripe/ [evt_no] 2020-06-05 22:48:24 --> invoice.finalized [evt_no] 2020-06-05 22:48:24 <-- [400] POST http://localhost:8007/stripe/ [evt_no] 2020-06-05 22:48:24 --> payment_intent.succeeded [evt_no] 2020-06-05 22:48:24 <-- [400] POST http://localhost:8007/stripe/ [evt_no] 2020-06-05 22:48:27 --> customer.source.created [evt_no] 2020-06-05 22:48:27 <-- [400] POST http://localhost:8007/stripe/ [evt_no] Other times he … -
TemplateDoesNotExist django rest framewok
I try to return HTML responses, but i have a TemplateDoesNotExist problem. ModelViewSet class ProfileList(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'test.html' def get(self, request): queryset = Profile.objects.all() return Response({'profiles': queryset}) Strucute of app -
Is there a way to use optgroup to group results in Django admin select2 autocomplete fields?
I've got a Django application that allows people to set a foreign key to city, state, and country models on a Post model. I have set up the Django admin form to use the built-in autocomplete fields for each of the location fields of the Post instance. I would like to be able to use the built-in select2 ability of generating <optgroup>s to nest the cities in the list inside a group for their state to keep things tidy and allow the user to visually distinguish between cities in different states with the same name. I have already added the state name to the string representation of the city, and expanded the search fields of the city admin to include the state's name in addition to the city's name. At the moment, admins can type Alaska in the city select2 field and return all cities whose name or whose state's name contains the string Alaska. However, I can't seem to find any documentation or anyone who's ever asked about providing a way to group the select2 results. The closest thing that's I've found is this support ticket for Django where someone wanted to add the autocomplete functionality and suggested using … -
CSS is loading to the page, but not showing up fully
padding-top is working correctly, but background-color is crossed out how to fix it? -
Could not parse the remainder:
I saw many questions about this error, but all are distincts and not apply to me, so... My models.py # Category class Category(models.Model): category_name = models.CharField(max_length=64) def __str__(self): return f"{self.category_name}" # Item class Item(models.Model): item_name = models.CharField(max_length=64) category = models.ForeignKey(Category, on_delete= models.CASCADE, related_name="items_by_category") price_small = models.DecimalField(help_text="Price in U$S",max_digits=6, decimal_places=2, default= 0) price_large = models.DecimalField(help_text="Price in U$S",max_digits=6, decimal_places=2, default= 0) nradd = models.IntegerField(default=0) def __str__(self): return f"{self.category} {self.item_name} - Qty.of Adds: {self.nradd} - Price Small: {self.price_small} - Price Large: {self.price_large}" My views.py def menu(request): products = list(Item.objects.all().values().order_by('category')) categories = list(Category.objects.all().prefetch_related('items_by_category')) extras = list(Extra.objects.filter(category="T")) subsextras = list(Extra.objects.filter(category="S")) context = { 'Products' : products, 'Categories': categories, 'Extras' : extras, 'Subextras' : subsextras } return render(request, 'orders/menu.html',context) First, I'm trying to simply list the categories with the items who belongs to: My menu.html: {% extends 'orders/base.html' %} {% load static %} {% block title %} Menu {% endblock %} {% block body %} <ul> {% for cate in Categories %} <li>{{ cate.category_name }}</li> <ul> {{% for myitem in cate.items_by_category.all %}} <li>{{ myitem.item_name }}</li> {{% endfor %}} </ul> {% endfor %} </ul> {% endblock %} the error appears in the line: {{% for myitem in cate.items_by_category.all %}} Same commands in the shell goes well: cate … -
Delete button form tag causes line break
I'm trying to have the edit and delete button in the code below side-by-side. They are until i add the form tag for the 'delete_dealer_view'. I'm also wondering why I need the form can't I just use an anchor tag and call the url? <div class="card"> <div class="card-header card-header-success"> All Dealers </div> <div class="card-body"> <table class="table"> <tbody> {% for dealer in dealers %} <tr> <td>{{dealer.name}}</td> <td class="td-actions text-right"> <button type="button" rel="tooltip" title="Edit Dealer" class="btn btn-white btn-link btn-sm"> <i class="material-icons">edit</i> </button> <form method="POST" action="{% url 'dealers:delete_dealer_view' dealer.slug %}"> {% csrf_token %} <button type="submit" rel="tooltip" title="Remove" class="btn btn-white btn-link btn-sm"> <i class="material-icons">close</i> </button> </form> </td> </tr> {% endfor %} </tbody> </table> </div> </div> -
How to convert a datetime from a specific timezone to its UTC version using the django.utils.timezone library?
I am looking for a function from the django.utils.library that would take a datetime from a specified timezone and return its UTC equivalent. Does such a function exist? -
I want to switch the pages in Navigation bar dynamically in django, But my error is page not found 404
Homepage.html <a href="{% url 'home' %}"></a> views.py def home(request): return render(request,'test_homepage.html') urls.py urlpatterns = [ path('admin/', admin.site.urls), path('',views.home,name="home"), ] -
Django Admin TypeError args[0] = str(args[0]), cannot update or delete objects
Jun 04 18:21:25 dev-strandbase app/web.1 [2020-06-05 01:21:24 +0000] [10] [ERROR] Error handling request /admin/parts_table/part/35/change/ Jun 04 18:21:25 dev-strandbase app/web.1 Traceback (most recent call last): Jun 04 18:21:25 dev-strandbase app/web.1 File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/sync.py", line 134, in handle Jun 04 18:21:25 dev-strandbase app/web.1 self.handle_request(listener, req, client, addr) Jun 04 18:21:25 dev-strandbase app/web.1 File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/sync.py", line 175, in handle_request Jun 04 18:21:25 dev-strandbase app/web.1 respiter = self.wsgi(environ, resp.start_response) Jun 04 18:21:25 dev-strandbase app/web.1 File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/wsgi.py", line 133, in __call__ Jun 04 18:21:25 dev-strandbase app/web.1 response = self.get_response(request) Jun 04 18:21:25 dev-strandbase app/web.1 File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/base.py", line 75, in get_response Jun 04 18:21:25 dev-strandbase app/web.1 response = self._middleware_chain(request) Jun 04 18:21:25 dev-strandbase app/web.1 File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/exception.py", line 36, in inner Jun 04 18:21:25 dev-strandbase app/web.1 response = response_for_exception(request, exc) Jun 04 18:21:25 dev-strandbase app/web.1 File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/exception.py", line 90, in response_for_exception Jun 04 18:21:25 dev-strandbase app/web.1 response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) Jun 04 18:21:25 dev-strandbase app/web.1 File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner Jun 04 18:21:25 dev-strandbase app/web.1 response = get_response(request) Jun 04 18:21:25 dev-strandbase app/web.1 File "/app/.heroku/python/lib/python3.7/site-packages/django/utils/deprecation.py", line 94, in __call__ Jun 04 18:21:25 dev-strandbase app/web.1 response = response or self.get_response(request) Jun 04 18:21:25 dev-strandbase app/web.1 File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/exception.py", line 36, in inner Jun 04 18:21:25 dev-strandbase app/web.1 response …