Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Form is not bound in Django
I'm trying to integrate Django with htmx. I want to render a form inside a table. but when I enter some data and submit it says the form is not bound. This is the view: def hx_payment_item_create(request, payment_id): payment = get_object_or_404(Payment, pk=payment_id) form = forms.PaymentItemCreateFromPaymentForm(request.POST or None) if request.method == "POST": if form.is_valid(): item = form.save(commit=False) item.payment = payment item.save() if request.htmx: return redirect("core:hx-payment-item-detail", pk=item.pk) return redirect("core:payment-item-detail", pk=item.pk) else: print(form.errors) context = {"form": form, "payment": payment} return render(request, "core/partials/payment_item_form.html", context) This is the template that will be rendered inside the table: <tr hx-target="this" hx-swap="outerHTML"> <form method="POST"> {% csrf_token %} {{ form.non_field_errors }} {% for hidden_field in form.hidden_fields %} {{ hidden_field.errors }} {{ hidden_field }} {% endfor %} {% for field in form.visible_fields %} <td> <label for="{{ form.subject.id_for_label }}">{{ field.label }}</label> {{ field.errors }} {{ field }} {{ field.help_text }} </td> {% endfor %} <td> <button type="submit" hx-post="#some_url"> submit </button> </td> <td> <button hx-get="#another_url" type="button"> cancel </button> </td> </form> </tr> -
Migrate a Dash app with multiple outputs to Django app
I have a dash app that in my app.py I have functions with many outputs. Is feasible somehow to migrate to Django? -
Why won't elastic beanstalk render css for the django admin site?
I am following this guide on deploying a django app to AWS Elastic Beanstalk : https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html After running eb open, the css for the admin site does not render. It works when running the development server at 127.0.0.1:8000/admin but not when deployed to EB. I have followed this guidance but it is still not working Elastic Beanstalk does not load the Django admin static files Can someone explain why this is happening? -
Favicon and manifest.json is not loading in Django / React Project Setup
I already have seen possible scenarios to solve this problem with the help of this already posted question and answer. how-to-add-favicon-to-django-app-with-react-front-end? But I'm unable to reproduce the solution. Now the Problem is Favicon is generated automatically with a command: npm run build In the build dir which the Django is serving. This is how the build dir is generated after npm run build command and the build is generated from this public folder index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#000000" /> <meta name="description" content="Web site created using create-react-app" /> <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" /> <!-- manifest.json provides metadata used when your web app is installed on a user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/ --> <link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" /> <!-- Notice the use of %PUBLIC_URL% in the tags above. It will be replaced with the URL of the `public` folder during the build. Only files inside the `public` folder can be referenced from the HTML. Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will work correctly both with client-side routing and a non-root public URL. Learn how to configure a non-root public URL by running `npm … -
Djangorestframework returns: TypeError: get_extra_actions() missing 1 required positional argument: 'self' when declaring get()
I am a little confused in my code I have: from django.db.models import query from django.shortcuts import render from rest_framework.views import APIView from .models import Publication from rest_framework.response import Response from .serializer import PublicationSerializer # Create your views here. class PublicationView(APIView): serial_class = PublicationSerializer() def get_extra_actions(self): return [ self.get() ] def get(self, request): detail = [ {'pub_id': i.pub_id, 'pub_date': i.pub_date, 'title': i.title, 'description': i.description, 'link': i.link} for i in Publication.objects.all() ] return Response(detail) but I am still getting a return the above error. Any thoughts or help? Let me know! -
Django many to many fields
i try to created online movies site, i write models.py this is serial models class Serial(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL") title_english = models.CharField(max_length=100) descritpion = models.TextField(max_length=1000) images = models.ImageField(upload_to="movies") category = models.CharField(choices=CATEGORY_CHOICES, max_length=10) language = models.CharField(choices=LANGUAGE_CHOICES, max_length=30) status = models.CharField(choices=STATUS_CHOICES, max_length=100) year_of_production = models.TextField(max_length=1000) view_count = models.IntegerField(default=0) def get_absolute_url(self): return reverse('post', kwargs={"post_slug_serial": self.slug}) def __str__(self): return self.title this is for add episode and series : example Season 1 --> series 1 and etc season_num = ( (" 1 ", "Season 1"), (" 2 ", "Season 2"), (" 3 ", "Season 3"), (" 4 ", "Season 4"), (" 5 ", "Season 5"), (" 6 ", "Season 6"), (" 7 ", "Season 7"), ("8 ", "Season 8"), (" 9 ", "Season 9"), ) class episodebi(models.Model): """ Information about specific TV Show episodes """ tv_show = models.ForeignKey(Serial, on_delete=models.CASCADE) season = models.CharField(choices=season_num,max_length=50) series = models.IntegerField(max_length=50) title = models.CharField (max_length=50) class Meta: unique_together = ('tv_show', 'season','series') def __str__(self): return self.title and this is my view.py def serieDetails(request,post_slug_serial): get_serie = Serial.objects.filter(slug = post_slug_serial) epis = episodebi.objects.all() return render(request, '2/seriel_desc.html', {"serie":get_serie,"epis":epis}) when i try to add html this cycle HTML {% load static %} {% for i in epis %} <h1>{{ i.tv_show … -
CS50W: Project2 (Commerce) / Django
I am finishing a Django app on auctions. I am required to make a view for each listing showing the current bids on this listing, the details, and a form to be able to place a bid on the listing. I am having one minor issue in updating the listing price when a higher bid is placed by a user. The problem is in the logic of the listing_view function, but I can't spot it: def listing_view(request, listing): this_listing = Listing.objects.get(listing_name=listing) bid_count = this_listing.bids.count() if request.method == "POST": form = BidForm(request.POST) current_user = request.user if form.is_valid(): newest_bid = form.cleaned_data["bid_price"] if newest_bid >= this_listing.current_price: new_bid = Bid(listing=this_listing, bid_price=newest_bid, owner=current_user) new_bid.save() bid_count += 1 this_listing.current_price = newest_bid this_listing.bids.add(new_bid) return HttpResponseRedirect(reverse("auctions:listing_view", kwargs= {'listing':this_listing.listing_name})) else: return HttpResponse("Error") else: return render(request, "auctions/listing.html", { "listing": this_listing, "form": BidForm, "count": bid_count }) If you want the model definition of Listing and Bid, I can provide them, but I believe the issue is in the listing_view logic. -
Django REST Framework: how to make the index route browsable if routes are prefixed?
I've no use for the index route api.domain.tld/. Instead my routes start quite nested: api.domain.tld/v1/some/thing/ api.domain.tld/v1/foo/bar/ When I visit api.domain.tld/ I get a 404 - which makes sense, but I'd like to get browsable suggestions of the nested routes instead. Relevant code: router = routers.DefaultRouter() router.register(r'some', ThingViewSet) router.register(r'foo', BarViewSet) urlpatterns = # path('', '...') - is not in use path('v1/', include(router.urls)) ] Any idea? Thanks in advance! -
Method Not Allowed in Django (Django-get Method)
I want to find the title as I give in the search field as I call the search/get method I get I trying to search the title with his name the error ; Error : Method Not Allowed: /api/tutorials [20/Sep/2021 18:18:35] "GET /api/tutorials?title=creating HTTP/1.1" 405 40 view.py: ' @api_view(['GET']) def tutorial_list(request): if request.method == 'GET': paginator = PageNumberPagination() paginator.page_size = 4 tutorials = Tutorial.objects.all().order_by('-id') title = request.GET.get('title', None) if title is not None: tutorials = tutorials.filter(title__icontains=title) result_page = paginator.paginate_queryset(tutorials, request) tutorials_serializer = TutorialSerializer(result_page, many=True) return paginator.get_paginated_response(tutorials_serializer.data) ' urls.py: ' urlpatterns = [ url(r'^api/tutorials/$', views.tutorial_list), url(r'^api/tutorials$', views.tutorial_post), url(r'^api/tutorials/(?P[0-9]+)$', views.tutorial_detail), url(r'^api/tutorials/published$', views.tutorial_list_published) ] ' -
SimpleJWT cannot authorize after changing the SECRET_KEY in django
I have a really weird problem with rest_framework_simplejwt package. It was working until I decided to change the SECRET_KEY of my django project. After that I can get the access and refresh token, but they don't work as expected. { "type": "authentication_error", "code": "token_not_valid", "detail": "Given token not valid for any token type", "attr": "detail" } All I did was changing only one character in my secret key. I'm using: Django 3.1.13 rest_framework_simplejwt 4.7.1 It would be awesome if I can get some help. Thanks. -
How to solve graphdoc markdown error in Django
I am trying to output the graphql docs in Django using graphdoc package and the following source code: return HttpResponse( graphdoc.to_doc(FileUploadGraphQLView().schema), content_type='text/html' ) however, I get the following error: -
How can I use uWSGI Spooler in Django?
I'm trying to run concurrent tasks using uWSGI Spooler instead of Celery in Django. I have found a few resources like this, this, and this, but nothing works. I have encountered many errors in this journey, and I have fixed them using solutions I found online, and right now this is what I have: Setup uwsgi.ini [uwsgi] pythonpath = /path/to/djproj wsgi-file = /path/to/djproj/wsgi.py uid = myuid module = wsgi:application master = true processes = 1 threads = 10 lazy-apps = true http = 0.0.0.0:8080 vacuum = true log-format = %(ltime) Worker: %(wid) %(status) %(method) %(uri) Size: %(size) log-date = %%Y %%m %%d %%H:%%M:%%S.000 # Let django handle most of the logging disable-logging = true log-5xx = true harakiri = 60 harakiri-verbose = true stats = /tmp/djproj_stats.socket # Spooling spooler = /path/to/tasks spooler-harakiri = 600 import = djproj.tasks tasks.py import logging logger = logging.getLogger(__name__) try: from uwsgidecorators import spool logger.warning("Imported spool successfully.") except Exception: logger.warning("Couldn't import spool.") def spool(func): def func_wrapper(**arguments): return func(arguments) return func_wrapper @spool def run_task(arguments): logger.warning("Running in spool.") from djproj.myapp.models import MyModel obj = MyModel.objects.get(id=arguments["obj_id"]) obj.run() djproj/myapp/models.py # ... def prepare_spooler_args(**kwargs): args = {} for name, value in kwargs.items(): args[name.encode("utf-8")] = str(value).encode("utf-8") return args class MyModel(models.Model): # ... … -
Task celery succeeded in 0.09006300568580627s: None
I have a project where I use Django with celery and I noticed when a task has errors I always have that message : Task celery succeeded in 0.09006300568580627s: None So I understand the task is finished but sometimes there are errors and I have succeeded which is for me not true. Besides, I have None and no informations. Do you know if it is possible to get more informations instead of None ? Thank you very much ! -
DJ_REST_AUTH Error : NameError: name 'dj_rest_auth' is not defined
I have installed dj-rest-authfor Token Authentication. My urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('customer/', include('customer.urls')), #new path('api-auth/', include('rest_framework.urls')), # new path('customer/dj-rest-auth/', include(dj_rest_auth.urls)), ] Settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'customer', 'rest_framework.authtoken', # new 'dj_rest_auth', ] My Requirements.txt: asgiref==3.4.1 dj-rest-auth==2.1.11 Django==3.2.7 django-rest-auth==0.9.5 djangorestframework==3.12.4 psycopg2-binary==2.9.1 pytz==2021.1 six==1.16.0 sqlparse==0.4.2 But when I am trying to runserver It's giving me NameError: name 'dj_rest_auth' is not defined What am I doing wrong? -
How to retry a task if it's the last retry in celery?
I'm writing a send_mail task, which, if another instance of it is running, has to retry after 2 seconds. The number of retries is limited by 300. If there is a running instance and the last retry is currently running - the function has to send the mail, regardless of the other instance is running. If it fails - asynchronous recording to the log. How to implement the following with Celery? -
Nginx fastcgi_cache_path file naming / design / best practice
I'm trying to configure Nginx as a reverse proxy "properly". So many documentation, so many website advising bad practices... well I've come up with this: the folder conf.d was created by Nginx to include once all files in it. That's where I've made global_custom.conf In conf.d/global_custom.conf I define all the "cache" type that might be used like this: fastcgi_cache_path /var/run/nginx-cache-wordpress levels=1:2 keys_zone=WORDPRESS:50m max_size=10g inactive=60m use_temp_path=off; fastcgi_cache_path /var/run/nginx-cache-django levels=1:2 keys_zone=DJANGO:50m max_size=10g inactive=60m use_temp_path=off; fastcgi_cache_key "$scheme$request_method$host$request_uri"; fastcgi_cache_use_stale error timeout invalid_header http_500; I did nginx-cache with multiple aliases and multiple files like I do /var/run/nginx-cache-wordpress, /var/run/nginx-cache-django and then use them like this: server { server_name django.myserver.com fastcgi_cache DJANGO; # blabla } server { server_name wordpress.myserver.com fastcgi_cache WORDPRESS; # blabla } Is it a good practice, if not, how should I do? I can't find any valuable information for a good sample for a good nginx reverse proxy configuration. -
remove {} from OrderedDict
I have an OrderedDict given as result in my function in below: [ { "name": "tetst", "date": [ { "dates": "20/09/2021 15:14:00", "id": 146 }, { "dates": "20/09/2021 15:14:00", "id": 145 } ] }, {} ] I want remove {} objects from Dict and ı want to get dict like: [ { "name": "tetst", "date": [ { "dates": "20/09/2021 15:14:00", "id": 146 }, { "dates": "20/09/2021 15:14:00", "id": 145 } ] } ] -
Sentry delete issues (logs)
I'm running Self-Hosted Sentry 21.6.1 on-premise with docker-compose up -d and Django database is getting full very fast because of large number of collected issues. 3,218,732 Total Errors in 8 days. Filesystem Size Used Avail Use% Mounted on /dev/sda1 504G 130G 349G 28% / How can I delete old issues (let's say older than 30 days) from the database or set new issues to overwrite the old ones once the disk is full? Or is there a better solution for this problem? -
Data is not fetching from database in python django
I have saved some lists in the database and i am fetching posts to show in list.html. But data is not Showing. main Urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls',namespace='blog')), ] app url.py from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('',views.post_list,name='post_list'), path('<int:year>/<int:month>/<int:day>/<slug:post>/',views.post_detail,name='post_detail'), ] Views.py from django.core import paginator from .models import Post from django.shortcuts import render, get_list_or_404 def post_list(req): posts = Post.published.all() return render(req,'blog/post/list.html',{'posts':posts}) def post_detail(req, year,month,day,post): post = get_list_or_404(Post,slug=post,status='published',publish__year=year,publish__month=month,publish__day=day) return render(req,'blog/post/detail.html', {'post':post}) -
save formset data to which data is passed from a form
I can't save multiple objects in the db, I created the formset but at the time of saving it only saves me the first compiled object if request.method == "POST": schede_form = SchedeForm(request.POST, prefix='schede') gruppi_formset = gruppiFormSet(request.POST, prefix='gruppi') if schede_form.is_valid(): schedaName = schede_form.cleaned_data['nome_scheda'] scheda = schede_form.save(commit = False) scheda.utente = request.user scheda.save() if gruppi_formset.is_valid(): for gruppo in gruppi_formset: gruppi_instance = gruppo.save(commit = False) gruppi_instance.gruppi_scheda = Schede.objects.get(nome_scheda=schedaName) gruppi_instance.save() -
django allauth and api call to eveonline
I have successfully added django-allauth to my bare application. What I want to do now is call API, but I do not know how. I use eve online provider. It returns a auth code to be used to exchange it for bearer token, just as many other applications. How do I get a bearer token from django-allauth tables or utilities to make a call? What I understand, I need to log in first and than make a call to api to get bearer token. The EVE Online website after login redirects to {SERVER}/callback?code={CODE_FROM_LOGIN} curl -XPOST -H "Content-Type:application/json" -H "Authorization:Basic {CODE_FROM_LOGIN}" -d '{"grant_type":"authorization_code", "code":"{APPLICATION_CALL"}' https://login.eveonline.com/oauth/token -
LDAP Connection at nginx.conf
I declareted LDAP settings in settings.py (i have an django app). This is how ut works now: AUTH_LDAP_SERVER_URI = 'ldap://my_url' AUTH_LDAP_BIND_DN = f'uid{LDAP_BIND_USER}, cn=bind_user,ou=service accounts,dc=something,dc=something_else' AUTH_LDAP_BIND_PASSWORD = LDAP_BIND_PASSWORD AUTH_LDAP_USER_SEARCH = LDAPSearch( 'cn=users,dc=something,dc=something_else,dc=ac,dc=uk', ldap.SCOPE_SUBTREE, '(uid=%(user)s)') AUTH_LDAP_GROUP_SEARCH = LDAPSearch( 'OU=Groups,dc=something,dc=something_else,dc=ac,dc=uk', ldap.SCOPE_SUBTREE, '(objectClass=groupOfNames)') AUTH_LDAP_GROUP_TYPE = GroupOfNamesType() i need to transfer this piece of code to nginx.conf. I know about nginx_ldap_auth, but I can't undestand how to use AUTH_LDAP_GROUP_SEARCH and SCOPE_SUBTREE there. Now i have something like that: proxy_set_header X-Ldap-URL "ldap://my_url"; proxy_set_header X-Ldap-BindDN "uid=LDAP_BIND_USER, cn=bind_user,ou=service accounts,dc=something,dc=something_else"; proxy_set_header X-Ldap-BindPass LDAP_BIND_PASSWORD; -
Django Radio Buttons in Columns
I have a radio button with n choices, the choices themselves being picked up from a Database. Forms.py class FilterForm(forms.Form): DressTable = mydb['DressInfo'] ColorTable =mydb['ColorInfo'] dress = forms.ChoiceField(widget=forms.RadioSelect,choices=[(obj['subcatvalue'], obj['subcategory']) for obj in DressTable.find({})]) color = forms.ChoiceField(widget=forms.RadioSelect,choices=[(obj['subcatvalue'], obj['subcategory']) for obj in ColorTable.find({})]) This is my views.py def dayview(request): form = FilterDaywiseNew() return render(request, 'searchpage.html',{'form': form}) This is my template file searchpage.html <form method="post" action="SearchDisplay" id="searchFilter"> <div id="checkbox"> <ul> {{ form.dress }} </ul> </div> <div id="checkbox"> <ul> {{ form.color}} </ul> </div> </form> I want the choices to be displayed as radio buttons in two columns per row, equally spaced. I have tried crispy options, but that is for the entire form I guess. How do I get the desired result like shown : -
Django migrations doens't recognize change in IntegerChoices
I have the following model: class Job(models.Model): class Status(models.IntegerChoices): OPEN = 1 DECLINED = 2 ACCEPTED = 3 and for consistency, I'd like the change the capitalization to title cases: class Job(models.Model): class Status(models.IntegerChoices): Open = 1 Declined = 2 Accepted = 3 Django does error when I change this, but doesn't recognize the changes when I run python manage.py makemigrations. I've had troubles with this before, as these changes can go unnoticed when other changes have been applied, crashing the app in the future. I've tried to find an answer in the docs & stack, but with no luck. What can I do to properly propagate these changes? -
Making an Order button on Details page work-Django
i am developing my ecommerce platform using django. I have implemented the order functionalities. When the user click s on teh add to cart, it works okay. But when he cicks on the product, to get more details, when he wants to click now the add to cart button, it doesnt respond. I have given it the same functionality like other button before coming to details page of single product. The problems seemed to be teh place where it doesnt find teh correct path. How can i implement that one button. Here is my views.py def processOrder(request): transaction_id = datetime.datetime.now().timestamp() data = json.loads(request.body) print(data) if request.user.is_authenticated: customer = request.user order, created = Order.objects.get_or_create( customer=customer, complete=False) total = order.get_cart_totals order.transaction_id = transaction_id if total == order.get_cart_totals: order.complete = True order.save() if order.shipping == True: print("Wrong") ship = ShippingAddress( customer=customer, order=order, firstname=data['shipping']['firstname'], lastname=data['shipping']['lastname'], address=data['shipping']['address'], city=data['shipping']['city'], zipcode=data['shipping']['zipcode'] ) ship.save(force_insert=True) else: print("User doesn't exist") print('Data:', request.body) return JsonResponse('Payment Submitted', safe=False) Here is my model.py class Order(models.Model): customer = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) def __str__(self): return str(self.id) @property def shipping(self): shipping = False orderItems = self.orderitem_set.all() for i in orderItems: if i.product.digital == False: …