Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating a button to change a boolean using htmx
I am trying to create a workflow using django and htmx were a user needs to accept an entry by clicking a button. In the backend this is supposed to change a boolean from False to True. I followed this tutorial HTMX 09 - Like e unlike com HTMX trying to adapt the "Like" functionality to my purposes, however in my case there is no template (at least non that makes sense to me) and this results in a 403 error. What is my error of thought here? <models.py> from django.db import models from django.db.models import Model class PurchaseOrder(Model): name = models.CharField(max_length=200) approved = models.BooleanField(default=False) <views.py> from .models import PurchaseOrder from django.views.decorators.http import require_http_methods @require_http_methods(['POST']) def po_accept(request, pk): order = get_object_or_404(PurchaseOrder, pk=pk) order.approved_accounting = True order.save() context = {'order': order} return render(request, context) def my_approvals(request): orders = PurchaseOrder.objects.all() template = 'procurement/my_approvals.html' context = {'orders': orders} return render(request, template, context) <urls.py> from django.urls import path from . import views app_name = 'procurement' urlpatterns = [ path('', views.index, name='index'), path('my_approvals/', views.my_approvals, name='my_approvals'), path('po_accept/<int:pk>', views.po_accept, name='po_accept') ] <my_approvals.html> {% for order in orders %} {{ order.name }} <button type="button" class="btn btn-success m-3" hx-post="{% url 'procurement:po_accept' order.pk %}" > Accept </button> {% endfor %} -
change the category of multiple posts at once in django admin panel
i have a django project that in admin panel i want to have a dropdown menu to selec multiple posts and can change its categories at once and the page just shows categoriy based on post's law! thanks here is my admin.py from django import forms from django.contrib import admin from mptt.admin import MPTTModelAdmin from .models import Law, Category, Post class CategoryInline(admin.TabularInline): model = Category extra = 0 def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'parent': # get the selected law from the parent Post model try: law_id = request.resolver_match.kwargs['object_id'] except KeyError: return super().formfield_for_foreignkey(db_field, request, **kwargs) # filter categories based on the selected law kwargs['queryset'] = Category.objects.filter(law_id=law_id) return super().formfield_for_foreignkey(db_field, request, **kwargs) class PostInline(admin.TabularInline): model = Post extra = 0 class CategoryAdminForm(forms.ModelForm): class Meta: model = Category fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) law_id = self.instance.law_id if self.instance else None self.fields['parent'].queryset = Category.objects.filter(law_id=law_id) def save(self, commit=True): instance = super().save(commit=False) instance.slug = slugify(instance.name, allow_unicode=True) if commit: instance.save() return instance class CategoryAdmin(MPTTModelAdmin): form = CategoryAdminForm list_display = ['name', 'law'] list_filter = ['law'] def get_inline_instances(self, request, obj=None): if obj: self.inlines = [PostInline] else: self.inlines = [] return super().get_inline_instances(request, obj) class LawAdmin(admin.ModelAdmin): inlines = [CategoryInline] class PostForm(forms.ModelForm): class Meta: model = … -
getting error ['djongo' isn't an available database backend or couldn't be imported] wihile running makemigrations cmd in django
I have create one simple django project and try to connect with mongodb database but when hit python manage.py makemigrations or migrate cmd getting error- django.core.exceptions.ImproperlyConfigured: 'djongo' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' python python v- 3.10 please help me out. pip list- Package Version asgiref 3.6.0 Django 4.1.7 djongo 1.3.6 dnspython 2.3.0 pip 23.0.1 pymongo 4.3.3 setuptools 67.6.0 sqlparse 0.2.4 tzdata 2022.7 setting.py file db connection and install app INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dapp', 'djongo', ] DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'testdb', 'HOST': 'localhost', 'PORT': 27017, } } -
Windows 10 Run django project on virtual Ubuntu server
I have Windows 10 on my laptop. I faced with some problems using Windows for develop django app. For example, celery library couldn't run tasks on Windows 10. So I want to install ubuntu and use it with my pycharm for django projects. I download ubuntu in Windows Store. But how can I set it for work with my django projects and his virtual environment? -
INSTALLED_APPS not defined in cartoview?
I am trying to install geoserver and this error comes in cartoview when i run paver setup_geoserver: File "/home/developer/cartoview/cartoview/settings.py", line 24, in <module> INSTALLED_APPS += CARTOVIEW_INSTALLED_APPS NameError: name 'INSTALLED_APPS' is not defined I don't know why this error is coming. I have tried to manually define the variables but it is giving other errors like index out of range. can someone kindly help? -
How can I display multiple render calls on webpage?
I'm getting started with the Django framework but can't figure out how to have multiple render calls from the views python file appear on my webpage. Within the url python file, I tried adding a new path and calling the function similar to how I did for the createPunnettSquare (which worked fine). My project ran fine but I was expecting the title to say 'punnett square' but only 'punnett' appears. Thanks in advance for any help as this is my first post. If more information is needed I can defintely provide it. webpage output views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. # request -> response # request handler def createPunnettSquare(request): genotype1 = "Aa" genotype2 = "Bb" l_offsprings = [] punnett_square = [[""]*len(genotype1) for i in range(len(genotype2))] for i in range(len(genotype1)): for j in range(len(genotype2)): p_offspring = fill_array(request, j, i, genotype1, genotype2) l_offsprings.append(p_offspring) dy_offsprings = {"offsprings": l_offsprings} return render(request, 'hello.html', dy_offsprings) def fill_array(request, j, i, genotype1, genotype2): offspring = genotype1[j] + genotype2[i] if offspring[0].isupper() == False: offspring = offspring[::-1] return offspring def sayhi(request): return render(request, 'hello.html', {"name": "square"}) urls.py from django.urls import path from . import views # URL configuration module (every app can … -
I have a error in django html file where the IF statement is not working properly
So I have a like button and i want it to show an already liked button if the user has already liked the post. Here is my html {% for post in posts %} <div class="border-solid border-2 mr-10 ml-10 mt-3 px-2 pb-4"> <h1 class="text-2xl font-bold mt-2 mb-2"><a href="/user/{{post.User}}">{{post.User}}</a></h1> {% if post.User == request.user.username %} <button id="btn_{{post.id}}" type="submit">Edit</button> <div id="text_{{post.id}}" class="hidden"> <textarea required="" maxlength="300" class="border-solid border-2 w-full h-20" name="text" id="textarea_{{post.id}}" cols="30" rows="10">{{post.Content}}</textarea> <button id="btn1_{{post.id}}" class="bg-blue-600 rounded-lg px-4 py-2 mt-1 text-white">Confirm</button> </div> <script> document.querySelector('#btn_{{post.id}}').addEventListener('click', function() { document.querySelector('#Content_{{post.id}}').className = "hidden"; document.querySelector('#text_{{post.id}}').className = 'block'; }) document.querySelector('#btn1_{{post.id}}').addEventListener('click', function() { fetch('/edit/{{post.id}}', { method: "POST", body: JSON.stringify({ content: document.querySelector('#textarea_{{post.id}}').value }) }) .then(response => response.json()) .then(result => document.querySelector('#p_{{post.id}}').innerHTML = result.Content ); document.querySelector('#Content_{{post.id}}').className = "block"; document.querySelector('#text_{{post.id}}').className = 'hidden'; }) </script> {% endif %} <div id="Content_{{post.id}}"> <p id="p_{{post.id}}" class="text-xl">{{post.Content}}</p> <input id="" type="hidden" value="{{post.Content}}"> </div> <p>{{post.Date}}</p> {% if post.User != request.user.username %} <button id="btn3_{{post.id}}"> like </button> <script> document.querySelector('#btn3_{{post.id}}').addEventListener('click', function() { fetch('/like/{{post.id}}', { method: "post", }) .then(response => response.json()) .then(result => document.querySelector('#likes_{{post.id}}').innerHTML = result.likes ); }) </script> {% endif %} {% if post.id in has_liked %} <button class="btn4_{{post.id}}"> Unlike </button> {% endif %} <p id="likes_{{post.id}}">{{post.likes}}</p> </div> {% endfor %} This is the views.py function : def index(request): if request.method == "POST": text … -
How to display the GenericRelation field value in djagno admin
I have a model A class XYZ(TimeStampedModel): content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT, null=True, blank=True) object_id = models.PositiveIntegerField(null=True, blank=True) content_object = GenericForeignKey('content_type', 'object_id') my other model B is this where I have defined the GenericRelation field class MNO(models.model): tin = GenericRelation( XYZ, content_type_field='content_type', object_id_field='object_id', null=True, blank=True, on_delete=models.SET_NULL, ) I want to show this field tin in my MNO's model admin. On adding the field name to the list_display I get the following two errors - django.core.exceptions.FieldDoesNotExist (main culprit) TypeError: call() missing 1 required keyword-only argument: 'manager' How can I get its value to be displayed like a normal model field? -
How to get data from select from frontend Django
I have ListView and select with options in my Django template and i want to get value from select in my listview to change response by this data but i got None when i try to print that How am i suppose to do that? views.py def get_queryset(self): url = config('REPORT_PROJECT_BUDGET') select_front = self.request.GET.get('selection') payload = {'ObjectGUID': select_front, } print(payload) # response = requests.get(url, auth=UNICA_AUTH, params=payload).json() # print(response) queryset = [] return queryset def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) context['OBJECTS'] = ObjectList.objects.all() return context template.html <div class="select"> <select id="g1" name="selection"> {% for obj in OBJECTS %} <option value="{{ obj }}">{{ obj }}</option> {% endfor %} <option value="1">1</option> </select> </div> -
how to filter passing a string value and get data from database
event_id:"3", event name: "BTC price increases to ₹18,50,000.00 or more by next 24 hours? i am passing event name " BTC price" and filter Multiple event stored on a database, and i filter event name of "BTC price"..how to get this data -
Redis Authentication Error on Django Python
When I try to log in to the admin panel either it returns an invalid password error or Client Sent AUTH, but no password is set. The application is built using python Django but Redis is the one that results in the error. I have tried available online solutions to set password/keys, remove password but it seems none is working. It still results in either of the errors. The reason why Redis is used is so that a user can attempt a wrong password only specific number of times before it locks for a specific time. If there is an alternative to Redis or a way to make it run on my machine I would appreciate as removing it would result in security issues. The current python version is 3.8 and the Redis version is 4.0.2. The app was built with older versions of the same. -
django allow cors from any host in particular view
django-corsheaders provides a list of domains to specify to allow cors, however, it would apply to all the views. I have some views that do not have any authorised form and are intended for access from other domain, like serving a raw text string from db, and want to allow cors from any host only for this view @csrf_exempt def my_view(request): response = HttpResponse() response['Access-Control-Allow-Origin'] = '*' # some other code here return response However, it is managed by django.middleware.common.CommonMiddleware, and a 301 is responded in the middleware before reaching the view. Is there a way to do this? -
React Form not sending POST data to API
React code for Frontend function InputsSignUp(){ const [username, setUsername] = useState(''); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const handleSubmit = (e) => { e.preventDefault(); fetch('/api/user/', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ email }), }) .then((response) => response.json()) .then((data) => console.log(data)) .catch((error) => console.error(error)); }; return ( <> <Container fluid="sm" style={{backgroundColor: 'white'}}> <h1>{email}</h1> <h1>{password}</h1> <Form> <Form.Group className="mb-3" controlId="formBasicUsername"> <Form.Label>Email address</Form.Label> <Form.Control type="text" placeholder="Enter email" value={email} onChange={(e) => setEmail(e.target.value)} /> <Form.Text className="text-muted"> We'll never share your email with anyone else. </Form.Text> </Form.Group> <Button variant="primary" type="submit" onSubmit={handleSubmit}> Submit </Button> </Form> </Container> </> ) } Python code for Backend @csrf_exempt def signup(request): if request.method == 'POST': print("Hello") data = json.loads(request.body) user = User.objects.create( #username=data['username'], email=data['email'], password="hello", ) user.save() return JsonResponse({'message': 'User created successfully'}) I am trying to send data from frontend react to backend to create a user and store the data. But whenever I submit the data it does not reach the given api point. While using POSTMAN to send the data I am successfully able to create the user. Is there anything wrong with the react code? -
clean() getting None value for ModelChoice Field in django model form
Here in ModelForm the clean method is not fetching the values of production_process queryset it is giving the None value here is my views.py class ProductionCapacityCreateView(CreateView): template_name = 'manufacturing/production_capacity_form.django.html' form_class = ProductionCapacityForm context_object_name = "production_capacity" model = ProductionCapacity def get_form_kwargs(self): kwargs = super(ProductionCapacityCreateView, self).get_form_kwargs() kwargs["client"] = self.request.user.client kwargs["request"] = self.request return kwargs def form_valid(self, form): print("FORM VALID") self.client = self.request.user.client self.object = form.save(commit=False) self.object.client = self.request.user.client p_process = form.cleaned_data['production_process'] num_of_people = form.cleaned_data['number_of_people'] date = form.cleaned_data['date'] try: self.object.save() messages.success(self.request, 'Day created successfully.') except BaseException as e: logger.exception(e) messages.error(self.request, 'Failed to create a day.') return HttpResponseRedirect(reverse("capacity_list")) here is my forms.py class ProductionCapacityForm(forms.ModelForm): date = forms.DateField(required=True, widget=forms.DateInput(attrs= { 'class':'datepicker' })) def __init__(self, *args, **kwargs): self.client = kwargs.pop('client') self.request = kwargs.pop('request') try: self.work_time = kwargs.pop('work_time') except: pass super(ProductionCapacityForm, self).__init__(*args, **kwargs) self.fields['production_process'].queryset = ProductionProcess.objects.filter(is_deleted=False).values_list("name", flat=True).distinct() self.fields['date'].widget.attrs\ .update({ 'placeholder': 'Select Date', 'class': 'input-class_name' }) def clean(self): production_process = self.cleaned_data.get('production_process') number_of_people = self.cleaned_data.get('number_of_people') datee = self.cleaned_data.get('date') pk = self.instance.pk if production_process: try: if production_process not in ProductionCapacity.objects.get(client=self.client, date=datee,production_process=production_process.id): self.cleaned_data['production_process'] = get_object_or_404(ProductionProcess,client=self.client,id=production_process.id) except: if ProductionCapacity.objects.filter(client=self.client, date=datee, production_process=production_process.id).exists(): raise forms.ValidationError('Production Process is already exists') self.cleaned_data['number_of_people'] = number_of_people self.cleaned_data['date'] = datee return super(ProductionCapacityForm, self).clean() class Meta: model = ProductionCapacity widgets = { "date": McamDateInput1, } fields = ['date', 'production_process', 'number_of_people'] … -
False positive variable not defined how to resolve?
I have some code and in settings.py file, it is saying that variable INSTALLED_APPS is not defined. The code is written like this: INSTALLED_APPS += ABC_INSTALLED_APPS Now we know that variables in python don't need defining then why is this problem arising? it is with a lot of other variables too. I tried to define variables manually but it is throwing another error in another variable of index out of range. Kindly help. -
Using the URLconf defined in learning_log.url,error 404
The python project about Django error Using the URLconf defined in learning_log.urls, Django tried these URL patterns, in this order: A special answer for this question. -
How to distinct in Django with a field beyond a foreign key
In the following model relationship, how can we make it distinct in the B field? class A(models.Model): b = models.ForeignKey("B") class B(models.Model): name = models.CharField(max_length=1024) The following will result in an error A.objects.distinct('b__name') django.db.utils.ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1: SELECT DISTINCT ON ("b"."name") "a"."id", ... -
How to implement server sent events in django app using http views?
I have a django asgi app that is served by daphne. I am trying to add Server Sent events to stream data from server to client. My asgi.py: """ ASGI config for app project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.1/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') application = get_asgi_application() My django view is below: import uuid from django.http import StreamingHttpResponse from rest_framework.views import APIView from .sse_helper import register_connection import logging log = logging.getLogger("sse_handler") class MySseView(APIView): # authentication_classes = [SessionAuthentication] # permission_classes = [IsAuthenticated] def get(self, request): log.info("Recived get request") response = StreamingHttpResponse(content_type="text/event-stream") # Set headers to enable SSE support response["Cache-Control"] = "no-cache" response["Connection"] = "keep-alive" # Generate a unique ID for this connection connection_id = str(uuid.uuid4()) business_id = "foo" # Register the connection in the dictionary register_connection(connection_id, str(business_id), response) return response The registered connections are processed by a background thread like this: sse_connections = {} def register_connection(connection_id, business_id, response): log.info("Registering sse connection %s for business %s" % (connection_id, business_id)) sse_connections[connection_id + '#' + business_id] = response def handle_events(): while True: # Iterate over the dictionary of connections log.info("Running handle_events on %d items" % len(sse_connections)) … -
Forbidden (CSRF token missing)
I just learned how to create a web server on raspberry using django, i am trying to improve it by using JS that generates form every time i send data but am getting this error and haven’t found a solution yet. Need some help. here the error when i run web server enter image description here My html <!DOCTYPE html> <html> <head> <title>blablablai</title> <script> function sendDirection(direction) { const data = new FormData(); data.append('direction', direction); const request = new XMLHttpRequest(); request.open('POST', '{% url "home" %}'); request.send(data); } function onMouseDown(direction) { sendDirection(direction); } function onMouseUp() { sendDirection('stop'); } </script> </head> <body> <h1>bzzzz....</h1> <button type="button" onmousedown="onMouseDown('forward')" onmouseup="onMouseUp()">Forward</button> <button type="button" onmousedown="onMouseDown('backward')" onmouseup="onMouseUp()">Backward</button> <button type="button" onmousedown="onMouseDown('left')" onmouseup="onMouseUp()">Left</button> <button type="button" onmousedown="onMouseDown('right')" onmouseup="onMouseUp()">Right</button> <form method="post" action="{% url 'change_speed' %}"> {% csrf_token %} <button type="submit" name="speed" value="25">Speed 25%</button> <button type="submit" name="speed" value="50">Speed 50%</button> <button type="submit" name="speed" value="75">Speed 75%</button> <button type="submit" name="speed" value="100">Speed 100%</button> </form> </body> </html> My views.py from django.shortcuts import render, redirect import smbus # Define I2C address SLAVE_ADDRESS = 0x27 # Initialize I2C bus bus = smbus.SMBus(1) # Define motor control functions def forward(): bus.write_byte(SLAVE_ADDRESS, ord('f')) def backward(): bus.write_byte(SLAVE_ADDRESS, ord('b')) def turn_left(): bus.write_byte(SLAVE_ADDRESS, ord('l')) def turn_right(): bus.write_byte(SLAVE_ADDRESS, ord('r')) def stop(): bus.write_byte(SLAVE_ADDRESS, ord('s')) def speed25(): bus.write_byte(SLAVE_ADDRESS, ord('1')) … -
Index attribute of nested object in django elasticsearch DSL
I have those models (oversimplified of course): class User(AbstractUser): username = TextField(null=True, blank=True) profile_picture = ResizedImageField(size=[640, 640],null=True, blank=True) class Connection(models.Model): connected_user = models.ForeignKey(User, on_delete=models.CASCADE, null=False, db_index=True, related_name='connected_users' ) And I would like to index a "Connection" document that holds the connected_user data as well, and the profile_picture. However, I would like to save connected_user.profile_picture.url, as ResizedImageField does not serialize properly. I tried this: @registry.register_document class ConnectionDocument(Document): [...] connected_user = fields.ObjectField(properties={ 'pk': fields.IntegerField(), 'username': fields.TextField(), 'profile_picture': fields.ObjectField(properties={ 'url': fields.TextField() }) }) And everything I tried is failing so far... connected_user = fields.ObjectField(properties={ 'pk': fields.IntegerField(), 'username': fields.TextField(), 'profile_picture': fields.TextField(), }) with raise SerializationError(data, e) elasticsearch.exceptions.SerializationError: ({'connected_user': {'pk': 2, 'username': '@testuser2', 'profile_picture': <ResizedImageFieldFile: users/profile_photo/test_AnIwYDI.png>}}, TypeError("Unable to serialize <ResizedImageFieldFile: users/profile_photo/test_AnIwYDI.png> (type: <class 'django_resized.forms.ResizedImageFieldFile'>)")) ` connected_user = fields.ObjectField(properties={ 'pk': fields.IntegerField(), 'username': fields.TextField(), 'profile_photo': fields.ObjectField(properties={ 'url': fields.TextField() }), }) ValueError: The 'profile_photo' attribute has no file associated with it. (as it can be empty I guess?) The ES DSL documentation is really hard to navigate for those kind of issues... -
AJAX not interacting with my Django views functions
This is a simple todo-list developed with the Django framework. I have a categories dropdown on my main page that is to display the tasks based on that particular category chosen. Javasript (AJAX) Section function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== "") { const cookies = document.cookie.split(";"); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + "=")) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const theselect = document.getElementById('catSelect'); theselect.addEventListener('change', (event) => { event.preventDefault(); const catname = theselect.value; fetch(`/?cat=${catname}`, { method: "GET", headers: { "X-Requested-With" : "XMLHttpRequest", "X-CSRFToken": getCookie("csrftoken"), } }) .then(response => response.json()) .then (data => { const display = document.getElementById("results"); display.innerHTML = ""; (data.context).forEach(x =>{ const items = ` <div class="row"> <div class="col-lg-7"> <a href="{% url 'detail_task' 17 %}" style="text-decoration: none;"> ${x.title} </a> </div> <div class="col-lg-1"> <a href="{% url 'update_task' 17 %}"> <i class="fa-regular fa-pen-to-square"></i></a> </div> <div class="col-lg-1"> <a href="{% url 'delete_task' 17 %}" style="color:rgb(219, 43, 37);"> <i class="fa-regular fa-trash-can"></i> </a> </div> </div> ` display.innerHTML += items; console.log(data) }); }); }); index.html <h3> To-Do … -
Problem sending an account confirmation email from Django
I'm trying to send an account activation email from a Django REST-based application and through two email services, gmail and Mailgun, using Heroku to deploy the application. I have no issues doing a user registration function using "django.core.mail.backends.console.EmailBackend", I run into issues while using the email backend "django.core.mail.backends.smtp.EmailBackend" with the following settings: from environs import Env env = Env() env.read_env() EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_PORT = env('MAILGUN_SMTP_PORT') EMAIL_HOST_USER = env('MAILGUN_SMTP_LOGIN') EMAIL_HOST_PASSWORD = env('MAILGUN_SMTP_PASSWORD') I get the following on my test system: web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner web_1 | response = get_response(request) web_1 | File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response web_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs) web_1 | File "/usr/local/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view web_1 | return view_func(*args, **kwargs) web_1 | File "/usr/local/lib/python3.8/site-packages/django/views/generic/base.py", line 69, in view web_1 | return self.dispatch(request, *args, **kwargs) web_1 | File "/usr/local/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper web_1 | return bound_method(*args, **kwargs) web_1 | File "/usr/local/lib/python3.8/site-packages/django/views/decorators/debug.py", line 90, in sensitive_post_parameters_wrapper web_1 | return view(request, *args, **kwargs) web_1 | File "/usr/local/lib/python3.8/site-packages/dj_rest_auth/registration/views.py", line 47, in dispatch web_1 | return super().dispatch(*args, **kwargs) web_1 | File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch web_1 | response = self.handle_exception(exc) web_1 | … -
Django html not able to get the Add_More function working
I am working on a project, where I need to create target for employees. When creating the object, my intention is to get 'Target_Name' only once, and 'Category', 'target_percentage' to repeat upon clicking 'Add More'. From various sources, I ended up with below code. But my html keeps giving different errors. Can someone help to get this solved? models.py from django.db import models class Create_Target(models.Model): Target_Name=models.CharField(max_length=100) Category=models.CharField(max_length=100) target_percentage=models.FloatField() forms.py from django import forms from .models import Create_Target from django.forms.models import BaseModelFormSet class Create_Target_Form(forms.ModelForm): class Meta: model=Create_Target fields=('Target_Name', 'Category', 'target_percentage') class Create_Target_FormSet(BaseModelFormSet): model = Create_Target fields = ['Category', 'target_percentage'] extra = 1 formset_template = 'django.forms.formsets.DEFAULT_TABLE_TEMPLATE' views.py from django.shortcuts import render, redirect from django.views.generic.edit import CreateView from .forms import Create_Target_Form, Create_Target_FormSet from .models import Create_Target class Target_Create(CreateView): model = Create_Target form_class = Create_Target_Form template_name = 'create_target.html' success_url = '/home' def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) if self.request.POST: data['formset'] = Create_Target_FormSet(self.request.POST, prefix='formset') else: data['formset'] = Create_Target_FormSet(prefix='formset', queryset=Create_Target.objects.none()) data['formset'].min_num = 1 data['formset'].max_num = 10 return data def form_valid(self, form): formset = Create_Target_FormSet(self.request.POST, prefix='formset') if formset.is_valid(): form.instance.Target_Name = form.cleaned_data['Target_Name'] self.object = form.save() formset.instance = self.object formset.save() return redirect('/home') else: return self.form_invalid(form) def get_initial(self): initial = super().get_initial() initial['Target_Name'] = self.request.POST.get('Target_Name', '') return initial html <!DOCTYPE html> … -
Select Related django
Como fazer para pegar os produtos da tabela ItensCompra e juntar com a de pedido e de compra? Segue models class ItensCompra(models.Model): produto = models.ForeignKey('cadastro.Produto', related_name="compra_produto", on_delete=models.CASCADE, null=True, blank=True) compra_id = models.ForeignKey('compras.Compra', related_name="itens_compra", on_delete=models.CASCADE) quantidade = models.DecimalField(max_digits=13, decimal_places=2, validators=[MinValueValidator(Decimal('0.00'))], null=True, blank=True) valor_unit = models.DecimalField(max_digits=13, decimal_places=2, validators=[MinValueValidator(Decimal('0.00'))], null=True, blank=True) saldo_atual = models.DecimalField(max_digits=13, decimal_places=2, validators=[MinValueValidator(Decimal('0.00'))], null=True, blank=True) saldo_final = models.DecimalField(max_digits=13, decimal_places=2, validators=[MinValueValidator(Decimal('0.00'))], null=True, blank=True) tipo_desconto = models.CharField(max_length=1, choices=TIPOS_DESCONTO_ESCOLHAS, null=True, blank=True) desconto = models.DecimalField(max_digits=13, decimal_places=2, validators=[MinValueValidator(Decimal('0.00'))], null=True, blank=True) subtotal = models.DecimalField(max_digits=13, decimal_places=2, validators=[MinValueValidator(Decimal('0.00'))], null=True, blank=True) inf_ad_prod = models.CharField(max_length=500, null=True, blank=True) vicms = models.DecimalField(max_digits=13, decimal_places=2, validators=[MinValueValidator(Decimal('0.00'))], null=True, blank=True) vipi = models.DecimalField(max_digits=13, decimal_places=2, validators=[MinValueValidator(Decimal('0.00'))], null=True, blank=True) p_icms = models.DecimalField(max_digits=5, decimal_places=2, validators=[MinValueValidator(Decimal('0.00'))], null=True, blank=True) p_ipi = models.DecimalField(max_digits=5, decimal_places=2, validators=[MinValueValidator(Decimal('0.00'))], null=True, blank=True) `class Compra(models.Model): # Fornecedor fornecedor = models.ForeignKey( 'cadastro.Fornecedor', related_name="compra_fornecedor", on_delete=models.CASCADE) # Transporte mod_frete = models.CharField( max_length=1, choices=MOD_FRETE_ESCOLHAS, default='9') # Estoque local_dest = models.ForeignKey( 'estoque.LocalEstoque', related_name="compra_local_estoque", default=DEFAULT_LOCAL_ID, on_delete=models.PROTECT) movimentar_estoque = models.BooleanField(default=True) # Info data_emissao = models.DateField(null=True, blank=True) valor_total = models.DecimalField(max_digits=13, decimal_places=2, validators=[ MinValueValidator(Decimal('0.00'))], default=Decimal('0.00'))```` class PedidoCompra(Compra): orcamento = models.ForeignKey( 'compras.OrcamentoCompra', related_name="orcamento_pedido", on_delete=models.SET_NULL, null=True, blank=True) data_entrega = models.DateField(null=False, blank=False) status = models.CharField( max_length=1, choices=STATUS_PEDIDO_COMPRA_ESCOLHAS, default='0') PedidoCompra e Compra eu consegui juntar, ja a pedido_itens -
How can I set the QuerySet on a Wagtail InlinePanel - or hide/archive items without deleting them?
I need to set items in an InlinePanel on a page as 'archived' so they don't display in the InlinePanel. There should only be a few items visible at once but deleting them is not an option as they are required for historical information and reporting etc. Is there a way to do this without just hiding them with Javascript (which will slow down page loads over time)? If they are archived and removed from the QuerySet via filtering, they are then deleted when the page is published because they are not longer needed by the InlinePanel. I have tried SET_NULL but they are still deleted. Using PROTECT stops the page from being published but this wont work because it's just blocking the inline object from being deleted. So how could this be done, or is this just asking too much from an InlinePanel? Basic code example. SET_NULL is ignored and related object is deleted when the page is published. class Variant(models.Model): product = ParentalKey( 'wagtailcore.Page', related_name='variants', on_delete=models.SET_NULL, null=True, ) class Product(Page): panels = [ MultiFieldPanel([ InlinePanel('variants', label='Item Variants'), ]), ]