Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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'), ]), ] -
How to return value instead of related object id in DynamicFieldsModelSerializer?
In django rest framework there is possibility to create serializer able to Dynamically modifying fields. Is there any chance to get value instead of related object ID? -
DigitalOcean: Django, Channels, Redis & Daphne
I am having issues with running websockets on DigitalOcean's App platform. I think I am fundamentally missing a configuration as it relates to Daphne. Here is my setup: Daphne 4.0.0 Channels-Redis 3.4.1 Settings.py INSTALLED_APPS = [ ... # Third-party 'channels', ... CSRF_TRUSTED_ORIGINS = [ 'https://blah.com', 'https://*.blah.com', ] SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') ASGI.py import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.dev') import django django.setup() from django.core.asgi import get_asgi_application asgi_app = get_asgi_application() import api_waitlist.routing from channels.routing import ProtocolTypeRouter, URLRouter, get_default_application from channels.security.websocket import AllowedHostsOriginValidator from channels.auth import AuthMiddlewareStack application = ProtocolTypeRouter({ 'http': asgi_app, 'websocket': AllowedHostsOriginValidator(AuthMiddlewareStack( URLRouter( api_waitlist.routing.websocket_urlpatterns )) ), # new }) DigitalOcean Configurations DigitalOcean App: "run command" located under App>Settings>Run Command: daphne -b 0.0.0.0 -p 8080 config.asgi:application Redis Configuration: Redis is set up using DigitalOcean's managed Redis database. The connection string is provided by DigitalOcean. The app level variable "REDIS_URL" that contains the connection string is: rediss://default:password_here@fs-dev-redis-do-user-xxxx-0.b.db.ondigitalocean.com:25061 React Frontend (React is within the Django project scaffolding): The React frontend code to establish the websocket connection is: wb = new WebSocket("ws://127.0.0.1:8000/ws/waitlist/"); The frontend browser console error: -
AttributeError in ASGI/Daphne Django problem
I had done this tutorial for WebSocket with Django but I have this problem when I execute "python manage.py runserver": HTTP GET /chat/hello/ 200 [0.01, 127.0.0.1:65009] WebSocket HANDSHAKING /ws/chat/hello/ [127.0.0.1:65014] Exception inside application: 'int' object has no attribute 'decode' Traceback (most recent call last): File "D:\Projects\New Backend\venv\lib\site-packages\django\contrib\staticfiles\handlers.py", line 101, in __call__ return await self.application(scope, receive, send) File "D:\Projects\New Backend\venv\lib\site-packages\channels\routing.py", line 62, in __call__ return await application(scope, receive, send) File "D:\Projects\New Backend\venv\lib\site-packages\channels\sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "D:\Projects\New Backend\venv\lib\site-packages\channels\sessions.py", line 263, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "D:\Projects\New Backend\venv\lib\site-packages\channels\auth.py", line 185, in __call__ return await super().__call__(scope, receive, send) File "D:\Projects\New Backend\venv\lib\site-packages\channels\middleware.py", line 24, in __call__ return await self.inner(scope, receive, send) File "D:\Projects\New Backend\venv\lib\site-packages\channels\routing.py", line 116, in __call__ return await application( File "D:\Projects\New Backend\venv\lib\site-packages\channels\consumer.py", line 94, in app return await consumer(scope, receive, send) File "D:\Projects\New Backend\venv\lib\site-packages\channels\consumer.py", line 58, in __call__ await await_many_dispatch( File "D:\Projects\New Backend\venv\lib\site-packages\channels\utils.py", line 57, in await_many_dispatch await task File "D:\Projects\New Backend\venv\lib\site-packages\channels\utils.py", line 49, in await_many_dispatch result = task.result() File "D:\Projects\New Backend\venv\lib\site-packages\channels_redis\core.py", line 367, in receive message_channel, message = await self.receive_single( File "D:\Projects\New Backend\venv\lib\site-packages\channels_redis\core.py", line 422, in receive_single content = await self._brpop_with_clean( File "D:\Projects\New Backend\venv\lib\site-packages\channels_redis\core.py", line 255, in _brpop_with_clean connection = self.connection(index) … -
Create child object in view as extra action
I have the following drf view: class HouseFullInfoViewSet(viewsets.ModelViewSet): queryset = House.objects.all() serializer_class = HouseSerializer permission_classes = (permissions.IsAuthenticated,) http_method_names = ['get', 'delete', 'post'] def retrieve(self, request, pk=None): house = self.get_object() serializer = self.get_serializer(house) return Response(serializer.data, HTTP_200_OK) @action(methods=['delete'], detail=True, url_name='remove_habitant') def remove_habitant(self, request,pk=None): house = self.get_object() habitant = CustomUser.objects.get(id = request.data['id']) house.habitants.remove(habitant) return Response({'msg':'Deletion success'}, status=HTTP_200_OK) @action(methods=['delete'], detail=True, url_name='remove_vehicle') def remove_vehicle(self, request,pk=None): house = self.get_object() vehicle = Vehicle.objects.get(id = request.data['id']) house.vehicles.remove(vehicle) return Response({'msg':'Deletion success'}, status=HTTP_200_OK) I am trying to make create_habitant and create_vehicle extra actions within this view, but I dont know how to do that exactly. I thought about something like this. @action(methods=['post'], detail=True, url_name='create_vehicle') def create_vehicle(self, request,pk=None): house = self.get_object() vehicle = Vehicle.objects.create(request.data) house.vehicles.add(vehicle) return Response({'msg':'Creation success'}, status=HTTP_200_OK) -
getting AttributeError: 'Settings' object has no attribute 'MODEL'
I have also installed pypi and tls using 'pip'. I am now trying to run 'python manage.py runserver' but after going to the local host and enter the url for checking whether the url is phishing or not, but getting this error after click on predict button. Any help on how to fix this and get my project running?