Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add filtering parameters in drf_yasg Swagger in django-rest-framework Viewsets
I am using django-rest-framework Viewset and i have one list API in that i have to add filtering parameters start_date and end_date in request body in swagger. class SchoolManagementView(ViewSet): def __init__(self, *args, **kwargs): super().__init__(**kwargs) self.payload = {} self.college_list_service = CollegeListService(view=self) @swagger_auto_schema( operation_description="Listing Inward Document", responses={status.HTTP_200_OK: "Success"} ) def list(self, request, *args, **kwargs): self.payload = self.college_list_service.execute(request) return ResponseHandler.success(payload=self.payload) Note: Here i am using all my filter backends in "college_list_service" file -
Is it possible to feed data from a React POST request into a Django form without rendering that form on the frontend?
I am working on a basic login form for a hybrid React/Django web app. I would like to use the built in data-cleaning and validating methods of the Django LoginForm, but our frontend is pure React. Everything works as far as logging in, but I am feeding the raw body data into the authenticate function as shown here. def login_view(request): if request.method == "POST": form_data = json.loads(request.body.decode('utf-8')) user = authenticate(request, email=form_data["username"], password=form_data["password"]) if user == None: request.session["invalid_user"] = 1 logging.warning("Login form contains no user") login(request, user) My question is, is there any way to feed this form_data into the Django native LoginForm when I instantiate it? I would prefer to not recode all of the input validation that Django does already. I've tried instantiating a LoginForm like so: form = LoginForm(data=form_data) And then tried running form.full_clean(), but it doesn't seem to work. Any help would be greatly appreciated, thank you! -
Site downtime becuase of gunicron cpu utilization is 96%
We have djanog application that run with gunicorn. We eware facing site downtime because of high trafic. Gunicorn is utilizng 96 % of the cpu that what cauing the issue. Our system specification: 8 GB ram, 4 cpu How to setup gunicron in such way that it can handle more than 100 request per second ? What are the system specifcation required for handling 100 request per second ? Is gunicorn workers are cpu count ? -
model register but not creating table
on my django application I try to register model , python manage.py makemigrations , migrate works , but no database table found on admin.. `from django.contrib import admin.. << admin.py >> from .models import Product class ProductAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('product_name',)} list_display = ('product_name', 'price', 'stock', 'category', 'modified_date', 'is_available') admin.site.register(Product, ProductAdmin) ` -
Celery executing only one task at a time
I'm running celery on windows through this command celery -A project worker --concurrency=1 --loglevel=info -E -P gevent -Ofair but it only executes one task at a time, even tried to add some configurations import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") app = Celery("django_celery") app.conf.worker_prefetch_multiplier = 1 app.conf.task_acks_late = True app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() I've no idea what I'm doing wrong -
How Django process the post request sent from React? I have extracted the data from the POST request, but how show the data in a web browser?
I'm absolutely new to the field of frontend and backend. I sent a request from React to Django using "POST" and I have extracted data from the request I can print it in the terminal, but how to show the result in web browser from Django (i.e.8000/result/) it seems to use "GET" method but it fails because my data is extracted from POST request. So basicacly, I input a text and submitted to localhost:8000/result, so I want to show the result on this url or redirect to another and send it back to React. I don't know how to achieve this I used a pretty dumb method I save the data of request in tempory json and read the json in another function to render a browser through "GET". I tried to render or redirect to some url pages directly after process the "POST" request, but it apprently fails. views.py @api_view(["GET","POST"]) #class SubmitTextView(View): def post(request): if request.method =="POST": #print(True) text = request.body #print(type(text)) result = json.loads(text)["text"] json_data = json.dumps({"text":result}) #return HttpResponse(json_data, content_type='application/json') #return JsonResponse({"text":result}) #context = {'result':result,'headline':'Result Searched from Wikipedia'} #return render(request, 'my_template.html', context) with open("sample.json", "w") as outfile: outfile.write(json_data) return JsonResponse({"status":"success"}) def upload(request): with open('sample.json', 'r') as openfile: # … -
Django 'STATIC_ROOT' url giving PermissionError
I'm running collectstatic with docker-compose and nginx. When I run the command python manage.py collectstatic, I get a Permission denied error such as this: PermissionError: [Errno 13] Permission denied: '/project/static' I'm trying to link it also with nginx. Trying different combinations it doesn't seem to accept my static files and this error is popping out most of the times. I tried using changing ownership with chown but it tells me I'm not allowed to change ownership, and when adding sudo in before it says sudo: not found (I'm running the scripts through a .sh script file). This is django settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') And this nginx configuration: server { listen ${LISTEN_PORT}; location /static { alias /static/; } location / { uwsgi_pass ${APP_HOST}:${APP_PORT}; include /etc/nginx/uwsgi_params; client_max_body_size 10M; } } Also changing the name of the folder in STATIC_ROOT didn't work. What am I doing wrong? -
editing a list in a different file
I am trying to edit a list in a different file in python django. I have a file called models.py and a file called details.py, details.py: DATA = [ {'height': '184', 'width': '49'} {'height': '161', 'width': '31'} {'height': '197', 'width': '25'} {'height': '123', 'width': '56'} {'height': '152', 'width': '24'} {'height': '177', 'width': '27'} ] def edit_list(h,w): for info in DATA: if info['height'] == h: info['width'] = w return True models.py: from abc.details import edit_list height = '161' new_width = '52' update_data = edit_list(height, new_width) #this doesn't work, when I check the file nothing changes in the list :/ What is the best approach to make this possible?? (I don't want to import this list to DB and just update the width there, I want the width to update inside the file itself, removing details.py file and creating a new one using python whenever an edit takes place is not possible because few other functions are taking data from the list as well all the time. -
Django, ReactJS & Babel: Integrating a React App with Django
I'm using Django 4 and wish to integrate a ReactJS application within the Django framework. I chose to use the exact approach here to start and installed it identically as outlined: https://dev.to/zachtylr21/how-to-serve-a-react-single-page-app-with-django-1a1l Here's a list of the installed components and versions: ├── @babel/core@7.20.12 ├── @babel/preset-env@7.20.2 ├── @babel/preset-react@7.18.6 ├── babel-loader@9.1.2 ├── clean-webpack-plugin@4.0.0 ├── css-loader@6.7.3 ├── react-dom@18.2.0 ├── react@18.2.0 ├── style-loader@3.3.1 ├── webpack-bundle-tracker@0.4.3 ├── webpack-cli@5.0.1 └── webpack@5.75.0 I do not want to post all of my code here since it is 100% identical to the code in the link above. Unfortunately, I'm receiving a strange error in the console: GET http://127.0.0.1:8001/frontend/static/frontend/frontend-dc3188e75be82e0a01e0.js net::ERR_ABORTED 404 (Not Found) 127.0.0.1/:1 Refused to execute script from 'http://127.0.0.1:8001/frontend/static/frontend/frontend-dc3188e75be82e0a01e0.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. This appears to be related to the path, but the referenced JS filename is spelled correctly and exists at the exact referenced path. The server console also displays a similar error: Not Found: /frontend/static/frontend/frontend-dc3188e75be82e0a01e0.js If anyone has insight or experience here, please let me know. I'm at a loss and need to walk away...again. Thank you in advance! -
Inventory table and sales table - Python | django
I created an inventory table called Products. How do I make a sales table with the products in the inventory table and the products in the sales table replicate according to the quantity in the inventory table. And when I sell a product in the sales table, it decreases in the quantity of the stock table. -
How to Call Two Fields From One Model in Django View
I now have a model and I want to display two fields of it in the same view.Then display them in the details template. What is the best way to do that? my model: class Book(models.Model): class Meta : verbose_name_plural = 'Books' category = models.ForeignKey(Categorie,on_delete=models.CASCADE,null=True, related_name="apps") book_slug = models.SlugField(blank=True,allow_unicode=True,editable=True) book_title = models.CharField(max_length=50 , null=True) book_picture = models.ImageField(upload_to='imgs' , null=True) book_description = RichTextUploadingField(null=True,blank=True) book_size = models.CharField(max_length=20 , null=True) book_created_at = models.DateField(auto_now_add=True) book_updated_at = models.DateField(auto_now=True) book_auther = models.CharField(max_length=100 , null=True) my views: def book_details(requset ,book_slug): book = get_object_or_404 (Book, book_slug = book_slug) try : book = Book.objects.filter(book_slug = book_slug) except : raise Http404 similar_books = Book.objects.filter(book_auther = book_slug) ------ >>> Here is my query context ={ 'book' :book, 'similar_books':similar_books, } return render( requset,'book.html',context) my template: <div class="row"> {% for b in book %} <div> <img src="{{ b.book_picture.url }}" class="Rounded circle Image" height="150" width="150" alt=""> <a href="{{b.get_absolute_url}}">{{b.book_title}}</a> </div> {% endfor %} </div> <div class="row"> {% for sb in similar_books%} <div> <img src="{{ sb.book_picture.url }}" class="Rounded circle Image" height="150" width="150" alt=""> <a href="{{sb.get_absolute_url}}">{{sb.book_title}}</a> </div> {% endfor %} </div> -
Stock checker in python, test several objects simultaneously
Ultimately, my goal is to to know if one of my users submitted an existing Stock Symbol in my webapp's form. So, I have a string with several words. I want to identify an active finance symbol (EURUSD=X, AAPL, ...). Because the string will count no more than 10 words, I decided to test all word independently through a yfinance request. If the stock symbol exists, Yahoo API will send me data, otherwise there is an error message 'Unknown Stock symbol'. import yfinance as yfs string = str("23/01/2023 24/02/2021 hello Xlibidish sj monkey jhihi EURUSD=X") x = string.split() #API CALL Tickertest = yf.Ticker(x) ainfo = Tickertest.history(period='1y') print(len(ainfo)) Therefore, I need a function that: split all string's variable into words. Done. Test all words, one by one in the API Identify the API call that sends data (might be done with a length condition as the unknown symbols all have length < 40. -
Reverse for 'update-project' with arguments '('',)' not found. 1 pattern(s) tried: ['update\\-project/(?P<pk>[0-9]+)/\\Z']
Trying to create an update function for a Project Model in Django but i've run into a problem. Here's what i have so far update view function @login_required def updateProject(request, pk): project = Project.objects.get(id=pk) form = ProjectForm(instance=project) if request.method == 'POST': project.name = request.POST.get('name') project.description = request.POST.get('description') project.save() return redirect('project', pk=project.id) context = {'form': form, 'project': project} return render(request, 'projects/project_form.html', context) This is how I'm calling it in the template <li><a href="{% url 'update-project' project.id %}">Edit</a></li> and this is what the urlpattern is path('update-project/<int:pk>/', views.updateProject, name='update-project'), What am I missing? -
Use Python/Django Virtual Environment without MySQL
I'm following this tutorial for beginner Python/Django in VS Code: https://code.visualstudio.com/docs/python/tutorial-django I ran the following commands in my workspace folder: py -3 -m venv .venv .venv\scripts\activate The first command ran fine, but the second errored out: 'MySQL' is not recognized as an internal or external command, operable program or batch file. I see many answers for how to solve this online... by installing MySQL. But I don't want to use MySQL in the app I'm building. So, my question is... how do I remove this dependency that seems to have added itself? Note: I looked in the activate script, and I don't see anything directly referencing MySQL there, so I'm at a bit of a loss as to why it's trying to invoke it at all. Is MySQL just a base dependency of Python? -
django adding real time probelm
this is html include that add the product and make multi adding random , once it dosnt make duplicate , and once work normally . {% load i18n %} {% load static %} <form > <div class="tab_content active" data-tab="fruits"> <div class="row "> {% for productss in my_products %} <div class="col-lg-3 col-sm-6 d-flex " > <div class="productset flex-fill" > <div class="productsetimg"> {% if productss.product_icon %} <img src="{% url 'productss.product_icon.url' %}" alt="img"> {% else %} <img src="{% static 'assets/img/product/product1.jpg' %}" alt="img"> {% endif %} <h6>{% translate "Qty" %}: {{productss.bpq_real_quantity}}</h6> <div class=""> <i class=""></i> </div> </div> <div class="productsetcontent"> <h4><span id="productee_namee{{productss.id}}">{{productss}}</span></h4> <h6>{{productss.bpq_product_sell_price}}</h6> <div class="increment-decrement"> <div class="input-groups"> <input type="button" value="-" onclick="decrementValue{{productss.id}}()" class="button-minus dec button"> <input type="text" name="child" value="1" class="quantity-field" id="plus_field{{productss.id}}" name="quantity_required"> <input type="button" value="+" onclick="incrementValue{{productss.id}}()" class="button-plus inc button" > <input type="submit" value="{% translate "Add" %}" id="add_item_{{productss.id}}"> </div> </div> </div> </div> </div> </form> <script> console.log('plus_field{{productss.id}}') function incrementValue{{productss.id}}() { var value = parseInt(document.getElementById('plus_field{{productss.id}}').value, 10); value = isNaN(value) ? 0 : value; value++; document.getElementById('plus_field{{productss.id}}').value = value; } function decrementValue{{productss.id}}() { var value = parseInt(document.getElementById('plus_field{{productss.id}}').value, 10); value = isNaN(value) ? 0 : value; if (value > 1 ) { value--; } document.getElementById('plus_field{{productss.id}}').value = value; } </script> {% comment %} var quantity = $("#quantity_required").val(); $.ajax({ type: "POST", url: {% url … -
Create the cXML punch-out API in the Determine P2P application django project
I created an e-commerce site with django. I would like to integrate a cxml punchout to link the ecommerce site and the systems of my buyers, I would like to know here how to configure the cXML file below: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE cXML SYSTEM "http://xml.cxml.org/schemas/cXML/1.2.028/cXML.dtd"> <cXML payloadID="?" timestamp="?" xml:lang="en-US"> <Header> <From> <Credential domain="?"> <Identity>?</Identity> </Credential> </From> <To> <Credential domain="?"> <Identity>?</Identity> </Credential> </To> <Sender> <Credential domain="?"> <Identity>?</Identity> <CredentialMac type="FromSenderCredentials" algorithm="HMAC-SHA1-96" creationDate="?" expirationDate="?">?</CredentialMac> </Credential> <UserAgent>Test</UserAgent> </Sender> </Header> <Request deploymentMode="test"> <PunchOutSetupRequest operation="create"> <BuyerCookie>1234ABCD</BuyerCookie> <Extrinsic name="User">which user</Extrinsic> <BrowserFormPost><URL>https://example.com/?BrowserFormPost</URL></BrowserFormPost> <Contact> <Name xml:lang="en-US">myname</Name> <Email>whichmail@email</Email> </Contact> <SupplierSetup><URL>https://testapp.com/?SupplierSetup</URL></SupplierSetup> </PunchOutSetupRequest> domaine of my app : www.testapp.com For other information how to inform them ??? to adapt it to my project -
Write reusable template part django
In my templates, in many places, I've got repeating parts, like: <th class="column-title"> <a href="?{% query_transform order_by='x' %}"> {{ objForm.x.label_tag }}</a> </th> <th class="column-title"> <a href="?{% query_transform order_by='y' %}"> {{ objForm.y.label_tag }}</a> </th> <th class="column-title"> <a href="?{% query_transform order_by='z' %}"> {{ objForm.z.label_tag }}</a> </th> Is there a way, to write some "function" to render such html part like: (pseudocode) in html: render("x") render("y") render("z") in python: def render(param): return " <th class="column-title"> <a href="?{% query_transform order_by='+param+' %}"> {{ objForm'+param+'.label_tag }}</a> </th>" PS. I know, that theoreticaly I can prepare ordered list in view, and then iterate over it in a template, but I think it is not a good solution ,as I prefer to build my view, fields order etc on the template side. -
How to sort TextFields (strings) in Django using ElasticSearch-dsl?
I cannot find the solution for this online so i hope anyone here could help. I have a ChardField in models.py i want to sort after rebuilding the index in ElasticSearch (version 7). I'm using 'django_elasticsearch_dsl' as my pip. I read something about adding 'fielddata' as a property in 'documents.py' or changing the TextField() type to KeywordField() but i have no idea how to do this properly. My documents.py so far: from django_elasticsearch_dsl import Document, fields from django_elasticsearch_dsl.registries import registry from .models import Journey @registry.register_document class JourneyDocument(Document): class Index: name = 'journeys' settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = Journey # The model associated with this Document fields = [ 'id', 'departure_time', 'return_time', 'departure_station_name', 'return_station_name', 'covered_distance', 'duration', ] ..and my models.py is: class Journey (models.Model): id = models.BigAutoField(primary_key=True) departure_time = models.DateTimeField(auto_now = False, auto_now_add = False, default=timezone.now) return_time = models.DateTimeField(auto_now=False, auto_now_add=False, default=timezone.now) departure_station = models.ForeignKey(Station, on_delete=models.CASCADE, related_name='departure_station') departure_station_name = models.CharField(max_length=50, default="-") return_station = models.ForeignKey(Station, on_delete=models.CASCADE, related_name='return_station') return_station_name = models.CharField(max_length=50, default="-") covered_distance = models.DecimalField(max_digits=12, decimal_places=2, validators=[MinValueValidator(10, "Covered distance of the journey has to be bigger than 10.")]) duration = models.PositiveIntegerField(validators=[MinValueValidator(10, "Duration of the journey has to be bigger than 10s.")]) So how can i sort the query results … -
My React app's proxy not working in docker container
When I working without docker(just run React and Django in 2 sep. terminals) all works fine, but when use docker-compose, proxy not working and I got this error: Proxy error: Could not proxy request /doc from localhost:3000 to http://127.0.0.1:8000. See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNREFUSED). The work is complicated by the fact that each time after changing package.json, you need to delete node_modules and package-lock.json, and then reinstall by npm install (because of the cache, proxy changes in package.json are not applied to the container). I have already tried specifying these proxy options: "proxy": "http://localhost:8000/", "proxy": "http://localhost:8000", "proxy": "http://127.0.0.1:8000/", "proxy": "http://0.0.0.0:8000/", "proxy": "http://<my_ip>:8000/", "proxy": "http://backend:8000/", - django image name Nothing helps, the proxy only works when running without a container, so I conclude that the problem is in the docker settings. I saw some solution with nginx image, it doesn't work for me, at the development stage I don't need nginx and accompanying million additional problems associated with it, there must be a way to solve the problem without nginx. docker-compose.yml: version: "3.8" services: backend: build: ./monkey_site container_name: backend command: python manage.py runserver 127.0.0.1:8000 volumes: - ./monkey_site:/usr/src/monkey_site ports: - "8000:8000" environment: - DEBUG=1 - DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 - CELERY_BROKER=redis://redis:6379/0 - CELERY_BACKEND=redis://redis:6379/0 … -
Receiving "NotImplementedError" when using TruncMonth in Django QuerySet
I am a complete beginner when it comes to programming and Django. What I am using: Django 2.2.8 pymongo 3.12.1 djongo 1.3.6 MongoDB 3.6.23 I am trying to create a queryset in which I take a date from my database and group it by month. The date from the database I am pulling from is formatted as "2022-11-26T00:00:00.000+00:00". So I am trying to annotate a new field of just the month using TruncMonth so that I can then group by months. I have also tried using "extract" but that doesn't seem to work either. I am trying to avoid using a method that uses "extra" as it has been deprecated. I have been doing this in python shell until I get the results I want. Here is my code: models.py: class Charts(models.Model): severity_type = models.CharField(max_length=25) num_findings = models.IntegerField() finding_date = models.DateTimeField() python shell: `>>>from charts.models import Charts from datetime import datetime from django.db.models.functions import TruncMonth Charts.objects.annotate(month=TruncMonth('finding_date')).values('month')` #Which throws this error `NotImplementedError: subclasses of BaseDatabaseOperations may require a datetime_trunc_sql() method` From what research I have done, it has something to do with the field being a datetime vs a date I believe. I found this article that seems to be on … -
How to use Visual Basic ".vb" methods in a Django Project
In my actually job they're using an old Visual Basic WinForms apps and can't do a migration to another language. The question is, i want to use the ".vb" files which exists and consume their methods whit python in a Django project. Sending and returning values and data from each one. How can i do this? Connect a "Visual Basic" code with Django/Python -
'form.save(commit=True)' not saving to database
I am trying to use a ModelForm to create a new model in my database. The thing is, it's not saving it to there when I call form.save(commit=True). I am using Elastic Beanstalk (the free tier) to host my website. I feel like this has something to do with the problem. This is my forms.py: from datetime import date from .models import Itinerary class CreateItinerary(forms.ModelForm): class Meta: model = Itinerary exclude = ["sights"] destination = forms.CharField(max_length=100) start = forms.DateField(widget=forms.NumberInput(attrs={'type': 'date'}), initial=date.today) end = forms.DateField(widget=forms.NumberInput(attrs={'type': 'date'})) class FindPlaces(forms.Form): types = ((1, "restaurants"), (2, "attractions"), (3, "parks"), (4, "national parks"), (5, "clothing stores"), (6, "malls"), (7, "department stores"), (8, "stadiums")) place_type = forms.ChoiceField(choices=types) This is my views.py file: from django.views import generic from .models import * from .forms import * class createItinerary(generic.TemplateView): template = "itineraries/create.html" def get(self, request, *args, **kwargs): return render(request, self.template, { "form" : CreateItinerary(request.POST, request.FILES), }) def post(self, request, *args, **kwargs): form = CreateItinerary(request.POST) if form.is_valid(): new = form.save(commit=True) return redirect("/sights/") else: form = CreateItinerary return render(request, self.template, { "form" : form, }) def plan_redirect(request, id): return redirect("/plan/%s" % id, request) class plan(generic.TemplateView): find_places_form_class = FindPlaces template = "itineraries\plan.html" def get(self, request, id, *args, **kwargs): object = get_object_or_404(Itinerary, pk=id) … -
get() returned more than one Post -- it returned 2
I got problem in django. Im creating online shop website and I add products section where my products listed(html). I add my products from admin site (models.py). When I want to add to products i give error like this : get() returned more than one Post -- it returned 2! These are my codes : views.py class PostDetail(generic.DetailView): model = Post template_name = "shop-single.html" def get_context_data(self, **kwargs): models = Post.objects.get() context = super().get_context_data(**kwargs) client = Client(api_key = settings.COINBASE_COMMERCE_API_KEY) domain_url = "https://www.nitroshop.store/" product = {"name" : f'{models.title}' , 'description': f'{models.subject}' , "local_price" : {'amount' : f'{models.product_price}' , "currency" : "USD"} , "pricing_type" : "fixed_price" , "redirect_url" : domain_url + "NXnUijYpLIPy4xz4isztwkwAqSXOK89q3GEu5DreA3Ilkde2e93em8TUe99oRz64UWWBw9gEiiZrg60GMu3ow" , "cancel_url" : domain_url + "products"} charge = client.charge.create(**product) context['charge'] = charge return context models.py from django.db import models from django.contrib.auth.models import User # Create your models here. STATUS = ( (0 , "Draft"), (1 , "Publish") ) class Post(models.Model): title = models.CharField(max_length = 200 , unique = True) slug = models.SlugField(max_length = 200 , unique = True) author = models.ForeignKey(User , on_delete = models.CASCADE , related_name = "shop_posts") updated_on = models.DateTimeField(auto_now = True) subject = models.CharField(max_length = 200 , default = "We offer you pay with Tether or Litecoin") caption … -
I'm getting a validation error with django form
I'm facing with a validation form problem. I have this model: class Documenti(models.Model): descr = models.CharField('descrizione ', max_length=200) data = models.DateField('data', blank=True) objects = models.Manager() class Meta: verbose_name = 'Documenti' this is the form: class DocForm(ModelForm): def __init__(self, *args, **kwargs): super(DocForm, self).__init__(*args, **kwargs) class Meta: model = Documenti exclude = ['id'] widgets = { 'data': forms.DateInput(format=FORMATO_INPUT_DATE, attrs={'type': 'date', 'class': 'stdh-data'}), 'descr': forms.TextInput(attrs={SIZE: '80'}), } and this is the edit function: def edit_doc(request, doc_id=None): """ :param request: :param doc_id: """ if not (doc_id is None): doc_that = get_object_or_404(Documenti.objects.all(), pk=doc_id) titolo = ED_DOCUMENTO else: doc_that = Documenti() titolo = INS_DOCUMENTO form = DocForm(request.POST or None, instance=doc_that) redirect_to = Documenti().get_absolute_url() + current_page(request) if form.is_valid(): # All validation rules pass doc = form.save(commit=False) doc.save() return HttpResponseRedirect(redirect_to) # Redirect after POST else: print(form) from documenti.urls import url_views_lista_doc url_after_close = full_url(request, 'doc:%s' % url_views_lista_doc) dizio = {FORM: form, TitleScheda: titolo, TAG_url_after_close: url_after_close, } return generic_render(request, HTML_generic_edit, dizio) I always get FALSE when I check form.is_valid(). I tried to get error list with {{ form.non_field_errors }} {{ form.field_errors }} but they seems void. No idea. many thanks in advance -
'tuple' object has no attribute 'split_contents'
I'm trying to use django-advanced-filters. Python 3.8.10 Django==3.2 django-advanced-filters==2.0.0 sqlparse==0.4.3 settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'advanced_filters', 'semantics', 'sites', ] Urlpatterns urlpatterns = [ path('admin/', admin.site.urls), url(r'^advanced_filters/', include('advanced_filters.urls')), ] Admin class SemanticsClusterAdmin(AdminAdvancedFiltersMixin, admin.ModelAdmin): raw_id_fields = ("page",) list_display = ["id", "detail_view", "page", "name", ] advanced_filter_fields = ( 'id', 'page', ) exclude = [] admin.site.register(SemanticsClusters, SemanticsClusterAdmin) Traceback $ python manage.py migrate 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/michael/Documents/PyCharmProjects/marketing3/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/michael/Documents/PyCharmProjects/marketing3/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/michael/Documents/PyCharmProjects/marketing3/venv/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/michael/Documents/PyCharmProjects/marketing3/venv/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/michael/Documents/PyCharmProjects/marketing3/venv/lib/python3.8/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/home/michael/Documents/PyCharmProjects/marketing3/venv/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 75, in handle self.check(databases=[database]) File "/home/michael/Documents/PyCharmProjects/marketing3/venv/lib/python3.8/site-packages/django/core/management/base.py", line 419, in check all_issues = checks.run_checks( File "/home/michael/Documents/PyCharmProjects/marketing3/venv/lib/python3.8/site-packages/django/core/checks/registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/michael/Documents/PyCharmProjects/marketing3/venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/michael/Documents/PyCharmProjects/marketing3/venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/michael/Documents/PyCharmProjects/marketing3/venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 412, in check for pattern in self.url_patterns: File "/home/michael/Documents/PyCharmProjects/marketing3/venv/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/michael/Documents/PyCharmProjects/marketing3/venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 598, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/michael/Documents/PyCharmProjects/marketing3/venv/lib/python3.8/site-packages/django/utils/functional.py", …