Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - before model create
I have a model: book(book_id, release_year, book_number_by_release_year) Field book_number_by_release_year must be automatically generated and incremented by 1 within the release_year field for new model instances. What is the best way to do this in Django? Thank you for your help -
Django How To annotate/Group by & Display it in Serializer
I have following Model class ModelAnswer(BaseModel): questions = models.ForeignKey( to=Question, on_delete=models.CASCADE ) answer = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) Basically usecase is answer can be added multiple time i.e at once 3 answer can be added and all answers needed to be added for particular question I just made another model to keep track of these things in next model for my easiness. class AnswerLog(BaseModel): answer = models.ForeignKey(to=ModelAnswer, on_delete=models.CASCADE, null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) order = models.PositiveIntegerField(null=True, blank=True) I am getting my response in this format [ { "answer":{ "id":42, "user":1, "questions":"what did you do today", "subcategory":"Circumstance", "is_intentional":"False", "answer":"I played well", "created_at":"2022-09-05T21:00:57.604051" }, "order":1, "category":"sports" }, { "answer":{ "id":43, "user":1, "questions":"what was your achievment?", "subcategory":"Result", "is_intentional":"False", "answer":"a broked my leg", "created_at":"2022-09-05T21:00:57.626193" }, "order":1, "category":"sports" } ] I just want my above response in a bit easier format in this way just combine by order and category because both will be ( category can still be same for another answer so order will only be different for next answer i.e 2) [{ "answer":[{ "id":42, "user":1, "questions":"what did you do today", "subcategory":"Circumstance", "is_intentional":"False", "answer":"I played well", "created_at":"2022-09-05T21:00:57.604051" },{ "id":43, "user":1, "questions":"what was your achievment?", "subcategory":"Result", "is_intentional":"False", "answer":"a broked my … -
Post allauth intinate post handshake
Since allauth 0.47.0. You are suppose to intinate the sign up with a post handshake, I just don't understand how to do it and if it is suppose to be in the frontend or the backend. -
I can't show images in django
Not finding my image to show in django I can't see why is that I think there is something with my setting.py , cause I couldn't find MEDIA_URL and MEDIA_ROOT in there but I should I don't know how to direct the program to static/images/defaul.jpg actually and I am going through a course that it did excatly what I did but it keep saying that it can't find the image so I need your help guys here are my codes models.py from django.db import models # Create your models here. from django.db import models import uuid # null is for database and blank is for django # auto_now_add automatically add the date and the time that a object of this model created # Use it to override the id cause django automatically create id for any object # Use uuid and unique to make 16 chars id and unique ids # Use primary key to use it as primary key in database class Project(models.Model): objects = None title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) image = models.ImageField(null=True, blank=True, default='default.jpg') demo_link = models.CharField(null=True, blank=True, max_length=2000) source_link = models.CharField(null=True, blank=True, max_length=2000) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) tag = … -
django makemigrations no changes detected when use foreignkey
I ran into this problem. practically with makemigrations it saves me all the changes except the foreignkey .. it is as if it does not consider that line at all from django.db import models class Ingrediente(models.Model): nome_ingre = models.CharField(max_length=20) def __str__(self): return self.nome_ingre class Panino(models.Model): nome_panino = models.CharField(max_length=20) composizione = models.ForeignKey(Ingrediente, on_delete=models.CASCADE) def __str__(self): return self.nome_panino -
Django Queryset not displaying all results related to a member
i am trying to show data related to order table VIEWS.py class HBTYReadView(DetailView): model = HbtyOrder context_object_name = 'hairbty' template_name = 'accounts/modals/hairbty/read_hbty.html' MODELS.PY class HbtyOrder(models.Model): STATUS = ( ('Pending', 'Pending'), ('Out for delivery', 'Out for delivery'), ('Delivered', 'Delivered'), ) hbtycustomer = models.ForeignKey(HbtyCustomers, on_delete=models.SET_NULL, blank=True, null=True) itm = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True, blank=True) status = models.CharField(max_length=200, null=True, choices=STATUS) URLS.PY path('read_hairbty/<int:pk>', views.HBTYReadView.as_view(), name='read_hairbty'), Currently showing a user with one order but not a user with many orders. THANK YOU -
django-elasticsearch-dsl-drf filter fields size
There are size options for the Suggester field in django-elasticsearch-dsl-drf . So how do we use the filter extra(size=20) function that we use while writing a query in django-elasticsearch-dsl in django-elasticsearch-dsl-drf view or is there a size option like in the suggestion? filter_fields = { 'stat': { 'field': 'Stat.raw', 'lookups': [ LOOKUP_QUERY_IN, LOOKUP_FILTER_RANGE, ], 'default_lookup': LOOKUP_FILTER_WILDCARD, 'options': { 'size': Pallets.objects.all().count(), }, }, } suggester_fields = { 'Pallet_Id': { 'field': 'Pallet_Id.suggest', 'suggesters': [ SUGGESTER_COMPLETION, ], 'options': { 'size': Pallets.objects.all().count(), }, }, -
Rendering form in React based of DRF response
I already defined all the constraints for the fields of my models in the models.py or the serializer, so can i use that data to render forms to react? Defining them again in React seems like an errorsource if someone ever changes the form and introduces redundancy. I already tried it like this: from .serializer import StammdatenSerializer from .models import Probanden class Stammdaten(ModelViewSet): """ API endpoint that handles data for StammdatenForm. """ queryset = Probanden.objects.all() serializer_class = StammdatenSerializer permission_classes = [permissions.IsAuthenticated] template_name = "stammdatenForm.html" @action( detail=True, methods=["GET"], renderer_classes=[TemplateHTMLRenderer] ) def get_form(self, request, pk): profile = get_object_or_404(Probanden, pk=pk) serializer = StammdatenSerializer(profile) return Response({"serializer": serializer, "profiles": profile}) which seems to work fine for returning the rendered form, but now i dont know how to use that response in a react component. All i can think of is: using dangerouslySetInnerHtml and loading it into a div component. But then i completly lose the option to use states for the form elements or handle the submit. Is there an option to nicely integrate drf and react? -
Transaction Management with Raw SQL and Models in a single transaction Django 1.11.49
I have an API which reads from two main tables Table A and Table B. Table A has an column which has a column which acts as foreign key to Table B entries. Now inside api flow, I have a method which runs below logic. Raw SQL -> Joining table A with some other tables and fetching entries which has an active status in Table A. From result of previous query we take the values from Table A column and fetch related rows from Table B using Django Models. It is like query = "Select * from A where status = 1" #Very simplified query just for example cursor = db.connection.cursor() cursor.execute(query) results = cursor.fetchAll() list_of_values = get_values_for_table_B(results) b_records = list(B.objects.filter(values__in=list_of_values)) Now there is a background process which will enter or update new data in Table A and Table B. That process is doing everything using models and utilizing with transaction.atomic(): do_update_entries() However, the update is not just updating old row. It is like deleting old row and deleting related rows in Table B and then new rows are added to both tables. Now the problem is if I run api and background job separately then everything is good, but … -
how to force Django to use specific version of database
I have upgraded to python 3.9 and it requires Postgressql 11 to work. I was using Postgressql 10 already and I found out that I have 11 installed.. but I don't know how to force Django to use this version $ dpkg -l | grep PostgreSQL ii pgdg-keyring 2018.2 all keyring for apt.postgresql.org ii postgresql 10+190ubuntu0.1 all object-relational SQL database (supported version) ii postgresql-10 10.22-0ubuntu0.18.04.1 amd64 object-relational SQL database, version 10 server ii postgresql-11 11.17-1.pgdg18.04+1 amd64 The World's Most Advanced Open Source Relational Database ii postgresql-client-10 10.22-0ubuntu0.18.04.1 amd64 front-end programs for PostgreSQL 10 ii postgresql-client-11 11.17-1.pgdg18.04+1 amd64 front-end programs for PostgreSQL 11 ii postgresql-client-common 242.pgdg18.04+1 all manager for multiple PostgreSQL client versions ii postgresql-common 242.pgdg18.04+1 all PostgreSQL database-cluster manager ii postgresql-contrib 10+190ubuntu0.1 -
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 ?