Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create product with tag from django-taggit?
I'm trying to create a product with tags. I use tags from django-taggit. How to add them from the user side without using forms.py models.py class Posts(models.Model): title = models.CharField('Название', max_length=100) tags = TaggableManager() def __str__(self): return self.title views.py def create(request): if (request.method == 'POST'): obj, created = Posts.objects.get_or_create(title=request.POST.get("title")) obj.image=request.POST.get("image") obj.save() return render(request, 'create.html') -
How to get a subset of %s_%s_changelist
The following code works correctly: I have the models(.../models.py): Water point class Pagua(models.Model): idpg = models.CharField(primary_key=True, max_length=255,) observaciones = models.CharField(verbose_name='Observaciones',max_length=200,blank=True,null=True) class Meta: managed = False db_table = 'pagua' verbose_name = "Punto de agua" verbose_name_plural = "Puntos de agua" def __str__(self): return str(self.idpg) Surface water point (inherits from class Pagua) class Pasup(Pagua): num_p = models.CharField(verbose_name='Número punto',max_length=50) tipo_pg = models.CharField(verbose_name='Tipo',max_length=200, default='Superficial') denominacion = models.CharField(verbose_name='Denominación',max_length=200, blank=True, null=True) cota = models.FloatField(verbose_name='Cota [m.s.n.m]',blank=True, null=True) latitud = models.FloatField(verbose_name='Latitud [decimal]',blank=True, null=True) longitud = models.FloatField(verbose_name='Longitud [decimal]',blank=True, null=True) geom = models.PointField(blank=True, null=True,srid=4326) class Meta: managed = False db_table = 'pasup' verbose_name = "Punto de agua superficial" verbose_name_plural = "Puntos de agua superficiales" def __str__(self): return str(self.pagua_ptr_id) Chemical data: class Dquimicos(models.Model): analisisnum = models.IntegerField(primary_key=True) idpg = models.ForeignKey('registrar_p.Pagua', models.CASCADE, db_column='idpg') tipoanalisis = models.CharField(verbose_name='Tipo análisis',max_length=200, blank=True, null=True) fecha = models.DateField(verbose_name='Fecha',blank=True, null=True) class Meta: managed = False db_table = 'dquimicos_0' verbose_name = "Datos químicos (encabezado)" verbose_name_plural = "Datos químicos (encabezados)" def __str__(self): return str(self.analisisnum) The views (.../views.py): This view shows the list of changes with ALL Chemical records: def verdquimicos(request): myapplabel = Dquimicos._meta.app_label mymodelname = Dquimicos._meta.model_name infodata = myapplabel+'_'+mymodelname return HttpResponseRedirect(reverse("admin:%s_changelist" % infodata)) This view receives the pk parameter and displays the CHANGE page for the water point whose idpg = pk def … -
An event for when the last object is saved via Django formset
I have a signal that listens to a model whose relation to another model is like this class Model1(models.Model): field1 = models.CharField(max_length=4) class ChildToModel1(models.Model): model_1 = models.ForeinKey(Model1, related_name='model_1', on_delete=models.CASCADE) Now I have an inlineformset_factory for ChildToModel1 according to django calling save for ChildToModel1 inlineformset_factory will save multiple instance of ChildToModel1 like it's a forloop. If I have, for example; 3 formset is there a way to check the total of the objects after total save and not on each save, I am accessing these on the model post_save signal. printing ChildToModel1 on post_save signal returns something like this <QuerySet [obj]> <QuerySet [obj][obj]> <QuerySet [obj][obj][obj]> What I really want is: <QuerySet [obj][obj][obj]> -
Django: IntegrityError (duplicate key) when saving an existing record
I hope everyone is well! I have a problem when I save an existing record in my application. As in my data modeling, I need all the tables in the model to have the same basic identification and auditing fields, I have an abstract class where all the classes extend from it: #models.py import uuid from django.db import models from django_currentuser.db.models import CurrentUserField class BasicMonitoringTable(models.Model): ium_uuid = models.UUIDField( verbose_name='UUID', help_text=''' Unique register ID in the iuSolutions Monitoring system ''', db_column='ium_uuid', db_index=True, primary_key=True, max_length=40, unique=True, null=False, blank=False, default=uuid.uuid4, editable=False, ) ium_active = models.BooleanField( verbose_name='Active', help_text=''' Determines whether record is active. Inactive records are not used by the system (logical deletion) ''', db_column='ium_active', db_index=True, unique=False, null=False, blank=False, editable=True, ) ium_mod_count = models.BigIntegerField( verbose_name='Updates Count', help_text=''' Number of times the record was updated ''', db_column='ium_mod_count', db_index=True, unique=False, null=False, blank=False, editable=False, ) ium_created = models.DateTimeField( verbose_name='Created Date Time', help_text=''' Record creation date and time ''', db_column='ium_created', db_index=True, unique=False, null=False, blank=False, editable=False, auto_now_add=True, ) ium_created_by = CurrentUserField( verbose_name='Created By User', help_text=''' Record creator user ''', db_column='ium_created_by', db_index=True, unique=False, null=False, blank=False, editable=False, on_delete=models.DO_NOTHING, related_name='+', ) ium_updated = models.DateTimeField( verbose_name='Updated Date Time', help_text=''' Record last update date and time ''', db_column='ium_updated', db_index=True, unique=False, null=False, blank=False, editable=False, auto_now=True, … -
Django Filter all fields of Model
i have a short Question. I've been working on a Inventory-System to use in my company. So i'm pretty new here and i'm not experienced with Django. To filter the items, i made a simple search bar, where you can search for items. The filter looks like this: return Item.objects.filter(name__contains=self.request.GET.get('search_item')) As you see, i only filter by name, but i would like to filter all attributes of Profile with the search-field. Is it possible to check all fields of a Model in a single query? Thank you -
How to add a label to the combination of the url pattern and http method?
In our project, we must register all our endpoints with their related HTTP method to the third-party service. To organize the list of endpoints, we want to add labels to the combination of the URL and HTTP method. But I can't find a way to make this happen:/ Can anyone help me? for more detail: I have this path: path("brands/", views.GetBrand.as_view({"get": "list", "post": "create"})) I want to extract this information from the above line: [ { "label": ["get-brand", "brand-management"], "method": "GET", "url": "api/brands/" }, { "label": ["create-brand", "brand-management"], "method": "post", "url": "api/brands/" } I assumed that we can read the labels from the attribute that we set on the class view, can't I?! -
Plotly Dash. How to relayout the x axis of the graph so that it's not looks crowded?
I have this existing code that can update and extend the data in a scatter graph, looks like this. image1 I want to relayout the xaxis of the graph with maximum range of 9 data so that the lines will not be crowded, like this. image2 app.layout = html.Div([ html.Div(style={'display': 'flex'}, children=[ dcc.Graph( id='graph-ph', figure={ 'data': [ {'x': [], 'y': [0, random.random()], 'mode':'lines+markers', }], 'layout': { 'title': 'pH (pH)' }}, ), ]), dcc.Interval( id='interval-graph-update', interval=1000, n_intervals=0), ]) @app.callback(Output('graph-ph', 'extendData'), [Input('interval-graph-update', 'n_intervals')], [State('graph-ph', 'figure'), ]) def update_extend_traces_traceselect(n_intervals, existing): x_new = datetime.datetime.now() y_new = random.random() return dict(x=[[x_new]], y=[[y_new]]) -
Using django channels with websockets (React + django), I am getting an error when sending message from inside useEffect in react
The error is that websocket is still in connection phase. This is the error message in console Uncaught DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state. at websocket__WEBPACK_IMPORTED_MODULE_1__.client.onmessage This is the code inside use effect: useEffect(() => { websocket.onmessage = (e) => { const dataReceived = JSON.parse(e.data) } if(dataReceived['Message'] == 'Hello'){ websocket.send(JSON.stringify({ State: 'Message Hello Received', toSendBack: 'Hi', })) } },[]} As you can see i am using if condition to check that if the message sent from the backend is 'Hello' I am sending a message from inside use effect in react which says 'hi'. -
How to run django view every 24 hours
I want to run django view on server every 24 hours, please help me if you can -
How to delete upto n type of data in self forienkey using django rest framework?
class Directory(models.Model): name = models.CharField(max_length=100) parent_directory= models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True) I want to delete root folder and all the folders which is inside the root folder (root folder means parent_directory is null in Directory model), https://i.stack.imgur.com/oszCR.png, In this picture root is base directory and rest of the all folders are inside the root folder and if i delete the root folder then all the folders which is inside the root folder needs to be deleted ] for exam: root is parent_directory test sub3 and sub4 is inside root directory base on table photo Bhavya is inside sub4 based on photo top is inside in Bhavya Now if I want to delete object number 22 means root directory then 26, 29, 33 and 34 should also be deleted. Would you please let me know how can delete this n type of object without on_delete=models.CASCADE ? -
Hyperlink redirect is not working in Django
I have the below code as part of my project. But instead of redirecting to the HTML page (contact.html), it is redirecting back to the home page or index.html. main_app/urls.py: path("", home_views.index, name='home_page'), path("contact", home_views.contact, name='contact'), main_app/home_views.py: def index(request): return render(request, 'Varsity/index.html') def contact(request): return render(request, 'Varsity/contact.html') Varsity/index.html: <li><a href="{% url 'contact' %}">Contact</a></li> Terminal [05/Sep/2022 14:34:43] "GET /contact HTTP/1.1" 302 0 -
are using django q objects (complex queries) with user input secure? [duplicate]
Is it possible to inject a SQL attack in these queries? is it okay to insert user input in the query directly like below or it need a validation etap in advance : query = self.request.GET.get('q') query_result= Consultant.objects.filter( Q(first_name__icontains=query) | Q(last_name__icontains=query) | Q(group__title_techGroup__contains=query) | Q(practices__title_practice__contains=query) ) -
Is there a way to get custom user model password before it gets hashed on Django
A custom user model was created in Django. After we create a user, we then send that user details to firebase: # Sync User to FireBase Authentication: @receiver(post_save, sender=Account) def add_user_to_firebase(sender, created, instance, *args, **kwargs): if created: auth.create_user(**{ "uid":instance.firebase_uid, "display_name": instance.username, "email": instance.email, "password": instance.password }) but this is where the issue comes in: when we send the password instance.password the password is then hashed before it gets sent to firebase. We want the unhashed password to get sent to firebase instead. Is that possible? -
AttributeError: type object 'ConsignacionDetalle' has no attribute 'objects'
Aqui se guardan diferentes precios para los diferentes productos class ProductoPrecioVenta(models.Model): precio = models.FloatField(default=0) val_seleccion = models.BooleanField(default=True, verbose_name="Act.") val_activo = models.BooleanField(default=True, verbose_name="Act.") producto = models.ForeignKey( Producto, on_delete=models.PROTECT, verbose_name="Productos") producto_precio_descripcion = models.ForeignKey( ProductoPrecioDescripcion, on_delete=models.PROTECT, verbose_name="Precio Descripción") moneda = models.ForeignKey( Moneda, on_delete=models.PROTECT, verbose_name="Monedas") created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) class Meta: verbose_name = "producto precio de venta" verbose_name_plural = "productos precios de ventas" def __str__(self): return "{} | {} | LMT. {} | {} {}".format(self.producto.nombre, self.producto_precio_descripcion.descripcion, self.producto.limite, self.moneda.simbolo, self.precio) ProductoPrecioVenta.form class ProductoPrecioVentaForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProductoPrecioVentaForm, self).__init__(*args, **kwargs) self.fields['producto'].queryset = Producto.objects.filter( val_activo=True) self.fields['producto_precio_descripcion'].queryset = ProductoPrecioDescripcion.objects.filter( val_activo=True) self.fields['moneda'].queryset = Moneda.objects.filter(val_activo=True) class Meta: model = ProductoPrecioVenta fields = ['producto', 'producto_precio_descripcion', 'moneda', 'precio'] labels = { 'producto': 'Producto', 'producto_precio_descripcion': 'Descripción para el Precio', 'moneda': 'Moneda', 'precio': 'Precio de Venta', } widgets = { 'producto': forms.Select( attrs={ 'class': 'form-select h-50 w-100', } ), 'producto_precio_descripcion': forms.Select( attrs={ 'class': 'form-control h-50 w-100', } ), 'moneda': forms.Select( attrs={ 'class': 'form-control', 'style': 'text-align:right;', } ), 'precio': forms.NumberInput( attrs={ 'class': 'form-control', 'style': 'text-align:right;', } ), } Se hace declara producto_precio_venta, que hace referencia a ProductoPrecioVenta class ConsignacionDetalle(models.Model): cantidad = models.IntegerField(verbose_name="Cantidad") val_activo = models.BooleanField(default=True, verbose_name="Act.") consignacion = models.ForeignKey(Consignacion, on_delete=models.PROTECT, verbose_name="Consignación") producto_precio_venta = models.ForeignKey(ProductoPrecioVenta, on_delete=models.PROTECT, verbose_name="Precio de venta") created_at = … -
Django employee working hours plan app based on date
I need to make an app that runs based on date. The idea is, have a total count on work hours that a divided by some number to get the right number of open positions to be filled with employees. When employees filling positions they should have their status and working hours bound to a from date, to date field, multiple from date, status, working hours, to date fields are necessary. And now visitors should have the option to input some date to view the future of open positions and needed working hours while also shown the employees with the status and working hours within that date range. I want to use django for that but have no clue how to accomplish such task. My idea was bound this whole thing into a calendar and let visitors just click on some date to show them the data but also dont know how to implement that. Do you have any ideas or direction you could guide me to ? -
Django - Bootstrap table inline editing
I have a data table with all functionalities like sort and search. I want to add a col in the table that could be editable. I want to save the comments of the viewer. I have the column in my model.py. but I do not know how to save it and keep it editable. <tbody> <tr> {% for a in data %} <td><a id="idclicked" href="datadescription/{{a.id}}/" title="click to see Metadata" style="color: rgb(30, 61, 199); font-weight:bold;"><u>{{ a.id }}</u></td></a> <td>{{ a.Date }}</td> <td>{{ a.Name }}</td> <td>{{ a.Affliations}} </td> <td>{{ a.Methods}}</td> <td>{{ a.Instruments}}</td> <td>{{ a.device}}</td> <td>{{ a.comments }}</td> <td contenteditable="true">{{ a.editablecomments }}</td> -
How to fetch rows from a table based on a field which is present in a different table having a foreign key relationship with it?
Context I have two tables as follows in Django Table1: - id - name - address - state - short_code Table2: - id - table1_id - property (searchable field) Relationship between Table1 and Table2: Table1(1) -> Table2(n) [ 1->n ] Question Let's say I have a searchable property p1 in Table2. How to fetch all the rows from Table1 which is satisfying the following query parameters? short_code, state, and property as p1 from Table2 Remember, Table1 1:n relationship with Table2, so Table2 can have multiple rows satisfying foreign key relationship of field id from Table1. Any help will be greatly appreciated. Have been working on the problem for a long time now. Thanks in advance. -
Multi-Language website using Django JS, facing error on Search filter error
I'm building a multi-language Django site and using 'Django-parler' for my model data translations. Now I'm wondering if there is a Django search app that works with multi-language models and I used to create the search functionality here, it works fine for single-language sites. But, I can't get it to work with multiple language filter functions. Here is my models.py from django.db import models from parler.models import TranslatableModel, TranslatedFields class Category (TranslatableModel): translations = TranslatedFields( category_Title=models.CharField(max_length=500) ) def __str__(self): return self.category_Title class Faq_QA(TranslatableModel): translations = TranslatedFields( question_Title=models.CharField(max_length=500), question_Description=models.TextField(), category_Option=models.ForeignKey(Category, on_delete=models.CASCADE), SEO_Keywords=models.TextField(), ) def __str__(self): return self.question_Title Here is my search View.py from django.shortcuts import render from .models import Category, Faq_QA from django.db.models import Q # Create your views here. def base(request): if 'q' in request.GET: q = request.GET['q'] multiple_keywords_faq = Q(Q(question_Title__icontains=q) | Q(question_Description__icontains=q)) search_key_faq = Faq_QA.objects.filter(multiple_keywords_faq) else: search_key_faq = Faq_QA.objects.all() context = { 'search_data': search_key_faq, 'category_data': Category.objects.all(), } return render(request, 'Base.html', context) For references my error-throwing image is here; Multi-Language website Error on Search filter image is here - please refer to it Can anyone please help me with this error, -
Django Tag Info
There are some wrong book links for the Django tag info. Since I do not have editing priviliges (It keeps saying edit queue is full.), I figured this would be the next best way. The books that need correction are: Pro Django Test Driven Development with Python -
VueJS + django_microsoft_auth + django REST framework authentication
I am having troubles logging in with Microsoft Authentication with my current stack. The Django application successfully logs in via MS auth using django_microsoft_auth (a legacy website section uses Django templates), but I can't figure out how to integrate it with the newer SPA section (as of now I managed to create a separate login with Django REST framework). Could you please give me any hint? Thank you! -
Dynamic Sitemap Django for not use model and only use api
Please help me. I am developing odoo ecommerce project. I use frontend with Django framework and backend with python. I give api from backend to Django frontend. Please let me know how to write dynamic sitemap. I am not have model to import and only use api. -
How can I use date as x axis Plotly Dash
I just started using Plotly Dash. I have this existing app that can generate random data. How can I change the X Axis to today's date. I tried using "datetime.datetime.now()" but the date looks like this image import dash from dash.dependencies import Output, Input import dash_core_components as dcc import dash_html_components as html import plotly import random import plotly.graph_objs as go from collections import deque import datetime from django_plotly_dash import DjangoDash X = deque(maxlen=10) X.append(1) Y = deque(maxlen=10) Y.append(1) x_new = datetime.datetime.now() app = DjangoDash("SimpleExample") app.layout = html.Div( [ dcc.Graph(id='live-graph', animate=True), dcc.Interval( id='graph-update', interval=1*2000 ), ] ) @app.callback(Output('live-graph', 'figure'), [Input('graph-update', 'n_intervals')]) def update_graph_scatter(input_data): X.append(X[-1]+1) Y.append(Y[-1]+Y[-1]*random.uniform(-0.1, 0.1)) data = plotly.graph_objs.Scatter( x=[x_new], y=list(Y), name='Scatter', mode='lines+markers' ) return {'data': [data], 'layout': go.Layout(xaxis=dict(range=[min(X), max(X)]), yaxis=dict(range=[min(Y), max(Y)]),)} if "SimpleExample" == '__main__': app.run_server(host='0.0.0.0', port=8080, debug=True) -
From within a Django Rest API, how can I return an image from an external image API that requires a key in the address
I am writing an API with the Django Rest Framework that returns a random image from an external image API that I have access to, which requires a private key in the url: imgapi.com/193811&key=2s3kp72a82 Without exposing the key, I want an endpoint in my API to return the image from this url: mysite.com/randomimage I will ise this endpoint as part of a web app that has a button that when clicked, displays a random image loaded via JS with an AJAX call to the endpoint. One of the approaches I tried was: @api_view(['GET']) def random_image(request): response = requests.get('api url with secret key') if request.method == 'GET': return HttpResponse(response.content, content_type="image/jpeg") however when I go to this endpoint in my browser, I get a server 500 error. When I make this a POST endpoint instead, I can get the image to return in Postman, but not in the browser. I have also tried to display the GET request using a Django template, but I cant get that to work either. -
why static files are not included?
Static files don't work. I seem to have registered everywhere where necessary. But the problem remains. What could be the catch. settings STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') urls from django.urls import * from . import * from django.conf.urls.static import * from django.contrib.auth import views as auth_views from django.conf import settings from blog import views app_name = "blog" urlpatterns = [ path('', views.index), path('create', views.create, name='create') ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) dir structure -
Django REST API 504 Gateway Time-out Error
so I have this API that takes a post request and needs almost 3 minutes to process and return some results in response. I've tried all the ways mentioned in this link