Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ManyToMany Serializer
I implemented nested serializer, but I have that error: NameError: name 'SamplesSerializer' is not defined. I have called the SampleSerializer without defining it yet, I am aware, but here I have also defined the patientid as a foreign key which is related to Epi_dataSerializer. What should I do to fix the problem? class Epi_dataSerializer(serializers.ModelSerializer): epi_data_hospitals = HospitalsSerializer(read_only=True) epi_data = SamplesSerializer(read_only=True, many=True) class Meta: model = Epi_data fields = ['epi_data', 'bday', 'age', 'gender', 'born_country', 'foreigner', 'year_arival', 'date_arival', 'residence', 'postcode', 'occupation'] class SamplesSerializer(serializers.ModelSerializer): projects = ProjectsSerializer(read_only=True) hospitals = HospitalsSerializer(read_only=True) source_samples = SourceSamplesSerializer(read_only=True) sequencing = SequencingSerializer(read_only=True) patientid = Epi_dataSerializer(read_only=True) class Meta: model = Samples fields = ['id', 'reception_date', 'hospital_date', 'culture', 'index_sample', 'is_index_sample', 'status', 'hospital_sample_number', 'patientid', 'sample_type', 'box', 'last_extraction_date', 'inactivation_date', 'transfer_date', 'comments', 'projects', 'hospitals', 'source_samples', 'sequencing'] -
Every 10 row of my table I want to show them seperatly
In my Django project I have a table which datas coming from database. There can be hundreds of rows. I can't display all in one page. I want to display my tables 10 rows for each. I got two buttons for next and previous rows. Can I do this with jquery or some python code? index.html <table class="table" border=1> <thead> <tr> <th>Full Name</th> <th>Company</th> <th>Email</th> <th>Phone Number</th> <th>Note</th> <th>ID</th> <th>Item Barcode</th> </tr> </thead> <tbody> {% for x in thelist %} <tr> <td>{{x.full_name}}</td> <td>{{x.company}}</td> <td>{{x.email}}</td> <td>{{x.phone_number}}</td> <td>{{x.note}}</td> <td>{{x.id}}</td> <td>{{x.item_barcode}}</td> </tr> {% endfor %} </tbody> </table> <button type="button" class="btn btn-primary" name="button">Next</button> <button type="button" class="btn btn-primary" name="button">Previous</button> -
wants to map data in pandas but its indexing is coming properly
in this for a recipe there is column of Ingredients which have multiple Ingredients and its quantity column have multiple values corresponding to its ingredients . i am concatenate them but not getting a proper result enter image description here how to show them in a proper way here is the image of dataframe how for a single column data is coming wants data like for a particular recipe data should look like -
how to save an input list in Django admin
I am trying to work with the Django admin. In particular, I am interested in having a CharField so that I receive the input text from the user, process it inside the model and save it as an array to the database. So, having a database column origins_asns in PostgreSQL defined as an array of integers origin_asns BIGINT[] DEFAULT '{}', The corresponding model should look something like this class DynCdn(models.Model): ... origin_asns = models.CharField( verbose_name="Origin ASNs", help_text="Hint: use a space ' ' character to enter multiple ASNs.", max_length=64, ) interfaces = ChoiceArrayField( base_field=models.CharField( max_length=64, choices=DYNCDN_INTERFACES, ), default=list, ) ... def save(self, *args, **kwargs): ... if self.origin_asns is not None: self.origin_asns = [ int(_) for _ in self.origin_asns.split() if _.isdigit() ] return super(DynCdn, self).save(*args, **kwargs) ... The above fails with the following error message: Jun 08 10:21:33 __ registry[61043]: django.db.utils.DataError: malformed array literal: "[101, 202, 303]" Jun 08 10:21:33 __ registry[61043]: LINE 1: ...2f5c910bfd4f'::uuid, 'JSHGSAVS', '101, 202, 303', '[101, 202... Jun 08 10:21:33 __ registry[61043]: ^ Jun 08 10:21:33 __ registry[61043]: DETAIL: Missing "]" after array dimensions. It seems that the list is being casted to a string. Would you be so kind how to solve it? Having ChoiceArrayField defined like … -
How can we connect a Django app from local laptop to a SQL Managed instance that has azure AD authentication in place?
I am trying to connect a Django application from local laptop to Azure SQL Managed Instance with AD authentication in place. I have the necessary permissions for the SQL as I have been configured to connect it from SSMS with same credentials. I am trying to use ActiveDirectoryPassword as mentioned here. django-pyodbc-azure 2.1.0.0 docs and microsoft/mssql-django docs. Microsoft docs to connect to Azure MI. My db settings in settings.py is as follows: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'XXXX/db name', 'USER': 'xxxx.xxxx@xxxx.com', 'PASSWORD': 'XXXXXX', 'HOST': 'tcp:XXX.public.XXXX.database.windows.net', 'PORT': '3342', 'OPTIONS': {'driver':'ODBC Driver 17 for SQL Server', 'extra_params': 'Authentication=ActiveDirectoryPassword', },},} getting below error: django.db.utils.Error: ('FA004', "[FA004] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Failed to authenticate the user 'XXXX.XXXX@XXXXXXXX.com' in Active Directory (Authentication option is 'ActiveDirectoryPassword').\r\nError code 0xCAA2000C; state 10\r\nAADSTS50076: Due to a configuration change made by your administrator, or because you moved to a new location, you must use multi-factor authentication to access Similar issue has been discussed here. -
Broken pipe Django and problem with rendering view
I have problem with rendering my view. When i want to enter view with parings i get rolling wheel on top of page and after few mins i get error Broken pipe What i want to get in output is sets of 8 pairs of players with predicted score I try to make permutations of 6v6 and it render but from 7 its stuck. Is it problem of to many data in array? how can i simplify code? View.py: class TParing8v8View(View): def get(self, request, id, par): tournament = TournamentETC.objects.get(pk=id) player = Team_of_8.objects.get(pk=par) result = [] data_list = [] points = [] mp = [] teamA = [tournament.p1, tournament.p2, tournament.p3, tournament.p4, tournament.p5, tournament.p6] teamB = [player.op1, player.op2, player.op3, player.op4, player.op5, player.op6] for perm in permutations(teamA): result.append(list(zip(perm, teamB))) for pairing in result: score = [] total = 0 for i in pairing: if i == (tournament.p1, player.op1): i = player.p11 elif i == (tournament.p1, player.op2): i = player.p12 elif i == (tournament.p1, player.op3): i = player.p13 elif i == (tournament.p1, player.op4): i = player.p14 elif i == (tournament.p1, player.op5): i = player.p15 elif i == (tournament.p1, player.op6): i = player.p16 elif i == (tournament.p1, player.op7): i = player.p17 elif i == (tournament.p1, … -
Set attributes of SplitDateTimeField
I have a form which I build dynamically based on data provided by the user. For certain types of data, I want to provide a SplitDateTimeField to the user. I wanted to add attributes to this field, like a placeholder and a label, but couldn't find any hint on how to do it. Maybe I'm searching in the wrong place, but I couldn't find even a little piece of advice anywhere even though I've been searching for quite a while. I used an AdminSplitDateTime widget in order to at least get labels : datetime = forms.SplitDateTimeField(widget=AdminSplitDateTime()) While it gets closer to what I want, that's not exactly it. I've searched in the documentation and tried with a SplitDateTimeWidget but didn't manage to make any of its attributes to work. I'm currently lost as to what I should do so I'm asking here. My form, simplified (I kept the helper in it in case it impacts its behaviour) : from crispy_forms.helper import FormHelper from django.urls import reverse_lazy class ScriptInputForm2(forms.Form): datetime = forms.SplitDateTimeField(widget=AdminSplitDateTime()) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.add_input(Submit('submit', 'Submit')) self.helper.add_input(Submit('cancel', 'Back To Selection Page', css_class='ms-2 btn btn-danger')) self.helper.attrs = { 'novalidate': '' } self.helper.form_class = 'form-horizontal' self.helper.label_class … -
Its impossible to add a non-nullable field 'profile' to post without specifying a default. This is bc the DB needs something to populate existing rows
i created a model named post where i didn't add a 'PROFILE' foreign key before. class Post(models.Model): profile = models.ForeignKey(profile, on_delete=models.CASCADE) id = models.UUIDField(primary_key=True, default=uuid.uuid4) user = models.ForeignKey(User, on_delete=models.CASCADE) caption = models.CharField(max_length=250, blank=True, null=True) image = models.ImageField(upload_to="post_images", blank=True, null=True) created = models.DateTimeField(default=datetime.now()) no_of_likes = models.IntegerField(default=0) later i added it & ran makemigrations, it returned me saying i need to provide a default. by mistake i added the id number of that profile model as default. then everytime i do migrate, it returns IntegrityError: The row in table 'App_post' with primary key '6b6b280dbce848acb9fbbbec677d01b1' has an invalid foreign key: App_post.profile_id contains a value '1' that does not have a corresponding value in App_profile.id. now even after i completely removed the profile row from the post model, it still returns me saying this when i migrate. how do i fix this?? i want to change the default yet it returns saying App_post.profile_id contains a value '1' that does not have a corresponding value in App_profile.id i removed 1 from defult, i removed the whole row yet it doesn't change. i had to startover a whole project for this reason once, please help!! -
validating post method data in serializer
I have a simple model: class News(models.Model): viewed = models.BooleanField(default=False) headline = models.CharField() Given headline, I want to set the viewed to True. My question revolves around structuring the app/code base. Where do I validate the headline exists and update it? serializer.py class NewsSerializer(serializers.Serializer): def validate(self,data): try: news = News.objects.get(headline=data.get('headline')) return data except: raise serializer.ValidationError('headlinenotfound') views.py def post(self, request): headline = request.data.headline serializer = NewsSerializer(data=request.data) if serializer.is_valid(): #get the news to update news = News.object.get(headline=headline) news.viewed = True news.save() -
Nginx location doesn't work with Django app
I would like to ask a question related to hosting django project in production using Nginx. I created the following nginx configuration file: upstream django_app { server django_app:8000; } server { listen 80; listen [::]:80; server_name demo.company.com; location /custom { rewrite ^/custom/?(.*) /$1 break; proxy_pass http://django_app; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location /static/ { alias /var/www/static/; } } Here I am planning to put everything from Django behind custom , for example : http//demo.company.com/custom/..... I have three URLs with one dashboard '' and two Django apps, app1/ and app2/ . Using the above nginx configuration, I can get the dashboard at http://demo.project.com/custom/ but when i try to select any apps from dashboard the URL is redirected to http://demo.company.com/app1. May I ask how to ensure that any app upon selection goes to something like this http://demo.company.com/custom/app1 with static files loaded correctly. Thanks in advance, would appreciate any advice and help on this matter -
What causes this hanging command prompt in a Django project
This hanging prompt on any commands that involve migrate, makemigrations etc. I have other Django projects that work fine and I have no idea what is making it do this on this one. Since I had no data in any of the models/tables I've completely removed the db.sqlite3 file and all migrations files from all the apps involved in the project, and it still hung (as in the image) on the initial migrate command even though it recreated db.sqlite3. If I run makemigrations on any project app it creates 0001_initial.py and says things are ok but when I run migrate after it says there's nothing new to migrate. I've been messing with this for hours and I still have to ctrl-c out of these types of commands before they have completely terminated. I've even let them sit while I did other stuff and many minutes later I return to a still hanging command prompt. Pleeeeease tell me this has happened to someone else and/or someone knows how to fix this. Thanks -
How to return list of id's from create nested serialization using django rest framework
I created nested serialization but it is return only project name from project model but I want to return list of ids for one project. Here you can find create nested serialization Created nested serialization class Project(models.Model): project_id = models.AutoField(primary_key=True, unique=True) project_name = models.CharField(max_length=100) class ProjectSite(models.Model): site_id = models.AutoField(primary_key=True, unique=True) site_name = models.CharField(max_length=200,name='project_site_name') project_id = models.ForeignKey(Project, on_delete=models.CASCADE, blank=True, null=True, related_name="projectid") class Assignment(models.Model): assignment_id = models.AutoField(primary_key=True) assignment_name = models.CharField(max_length=150) site_id = models.ForeignKey(ProjectSite,related_name="projectsiteidkey", on_delete=models.CASCADE) assigned_to_id = models.ForeignKey('auth.User',related_name="assignedtoidfkey",on_delete=models.CASCADE) -
How to get data from an attribute of foreign key table to primary key table in Django
I want to get all the issues.reference with status "Exemption" in Project model's exemption field, in order to send the it as a response. As issue model has project as a foreign key field so I can't import Issue in Project model, that leads to circular import. Project Model ''' class Project(models.Model): creation_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) expiry_date = models.DateTimeField(null=True, blank=True) exemption = ListField(models.CharField(max_length=128), blank=True, null=True) ''' Issue Model ''' class Issue(models.Model): requestor = models.ForeignKey(User, related_name='issues', on_delete=models.CASCADE) projects = models.ManyToManyField(Project, related_name='issues_projects') reference = models.CharField(max_length=16, unique=True, editable=False, null=True) status = models.CharField(max_length=12, choices=IssueStatus.choices, null=True) ''' -
loop.last in jinja2 not working properly in django
guys I am trying to avoid printing two divs in my table in the last iteration of the loop of my Django template. I have used loop.last variable to check if the loop is in its last iteration, but it is not working for some reason. Here program session is simply a range(number_of_iterations_required). Here is my code: {% for n in program_sessions %} <!-- 1st session start --> <tr class="mb-2"> <td class="border border-0"> <div class="row"> <div class="col-6 mx-0 px-0"> <span class="float-end">Row: &nbsp;</span> </div> <div class="col-6 mx-0 px-0"> <span class="text-white">{{program.workout_time}}m</span> </div> {% if not loop.last %} <div class="col-6 mx-0 px-0"> <span class="float-end">Rest: &nbsp;</span> </div> <div class="col-6 mx-0 px-0"> <span class="text-white">{{program.rest_time}}min</span> </div> {% else %} <div class="col-6 mx-0 px-0"> <span class="float-end">Last Iteration boii! &nbsp;</span> </div> {% endif %} </div> </td> </tr> <!-- 1st session ends --> {% endfor %} </tbody> </table> </div> Thank you in advance for your help. Have a good day. -
Annotate getting wrong calculations
class Order(): pass class OrderItems(): parent = models.ForiegnKey(Parent, related_name="items") class OrderItemSalesTax(): child = models.ForiegnKey(OrderItems, related_name="sales_tax") I am using this query to calculate the total amount, but also deducting discount and adding Sales tax. But in second annotate I am not getting correct results, as you can see the query is straight forward to calculate sales tax (price + price * tax_percentage / 100). After struggling for hours, I couldn't figure it out, Am I doing something wrong ? Order.objects.annotate(trade_price= \ ExpressionWrapper( Sum(F('items__trade_price') * ExpressionWrapper(0.01 * (100 - F('items__discount__discount')), output_field=DecimalField()) * F('items__quantity') ) , output_field=DecimalField() ) ).annotate(total_price=F('trade_price') + F('trade_price') * Sum(F('items__sales_tax__percentage') / 100)) -
Unable to use reactjs ldap-authentication module, Error: 80090308: LdapErr: DSID-0C090447, comment: AcceptSecurityContext error, data 52e, v3839
I am developing one web application. I am using Django in the backend and reactjs in the frontend. I want to implement LDAP authentication with GroupWise permission. I am unable to find out good example or way to do this. Where should I implement LDAP - Djnago or reactjs?? If I use node module that is ldap-authentication. Source code is https://www.npmjs.com/package/ldap-authentication I am getting below error: Error: 80090308: LdapErr: DSID-0C090447, comment: AcceptSecurityContext error, data 52e, v3839 below are the param I am providing in code: let options = { ldapOpts: { url: CONFIG.ldap.url, }, // note in this example it only use the user to directly // bind to the LDAP server. You can also use an admin // here. See the document of ldap-authentication. userDn: `uid=${req.body.username},${ldapBaseDn}`, userPassword: req.body.password, userSearchBase: ldapBaseDn, usernameAttribute: 'UID', username: req.body.username, adminPassword: CONFIG.ldap.password, adminDn: 'cn=CONFIG.ldap.name,dc=xxx,dc=xxx,ou=Service Accounts,ou=xxx,ou=Common', verifyUserExists : true } Note: My LDAP server is not public and in reactjs ldap-authentication example they have used public ldap server. I am using https://github.com/shaozi/passport-ldap-example example for reactjs ldap implementation. Thank you. -
Django rest framework how to pass authorizing token in nextjs post request?
How to pass django authorization token in nextjs axois. I tried this for pass authorization token but getting 404 error. token = "Token 8736be9dba6ccb11208a536f3531bccc686cf88d" await axios.post(url,{ headers: { Authorization: `Bearer ${token}` }, contact_name:contact_name,contact_email:contact_email,contact_body:contact_body, }) -
I want to save the selected radio button into the database? How can I accomplish that in django?
models.py from django.db import models from django.utils.translation import gettext_lazy as _ # Create your models here. # from django.utils.encoding import smart_unicode from enum import Enum from django.contrib.auth.models import AbstractUser from django import forms class CommentForm(forms.Form): name = forms.CharField() comment = forms.CharField(widget=forms.Textarea) class Username(AbstractUser): firstName = models.CharField(max_length=200, null=True) lastName = models.CharField(max_length=200, null=True) email = models.EmailField(unique=True, default=None, null=True) password = models.CharField(max_length=32) REQUIRED_FEILDS = [] def __str__(self): return self.username class Option(models.TextChoices): OPTION1 = 'OPTION1', _('OPTION1') OPTION2 = 'OPTION2', _('OPTION2') OPTION3 = 'OPTION3', _('OPTION3') OPTION4 = 'OPTION4', _('OPTION4') class Question(models.Model): # id = models.AutoField(primary_key=True) question=models.CharField(max_length=600) option1=models.CharField(max_length=200, default=None) option2=models.CharField(max_length=200, default=None) option3=models.CharField(max_length=200, default=None) option4=models.CharField(max_length=200, default=None) difficulty=models.PositiveIntegerField() exam=models.BooleanField() key=models.CharField(max_length=100) correct_answer = models.CharField(max_length=7,choices=Option.choices,default=None,) def __str__(self): return str(self.id) class Answer(models.Model): username=models.ForeignKey(Username,max_length=200, null=True,on_delete=models.CASCADE) question_id = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.CharField( max_length=7, choices=Option.choices, default=None, ) surety=models.PositiveIntegerField( null=True) difficulty=models.PositiveIntegerField( null=True) def __str__(self): return self.answer views.py from django.shortcuts import render, redirect from .models import * from django.http import JsonResponse from django.contrib.auth import authenticate, login, logout # from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.contrib.auth import get_user_model from django.template import loader from django.views.generic import ListView from django.core.paginator import Paginator from ada.models import Question from django.db.models.functions import Lower from django import forms # class TestScreen(ListView): # paginate_by = 6 … -
How to display Selected option value Selected in option tag in Django Template File?
I want to keep user selected option active from the long SELECT OPTION dropdown list what they choose from SELECT OPTION. This is my HTML form in template file. <form action="" method="post"> {% csrf_token %} <div class="d-flex form-inputs"> <select class="form-select" aria-label=".form-select-lg" name="lang_txt"> <option value="span_to_eng">Spanish To English</option> <option value="eng_to_span">English To Spanish</option> <option value="french_to_eng">French To English</option> </select> <input name="txt" class="form-control p-3" type="text" placeholder="Search..."> <a href="#"><img src="/static/assets/image/search.png" alt=""></a> </div> </form> This is views function def lang_convert_view(request): if request.method == "POST" and 'txt' in request.POST: txt = request.POST.get('txt') selected_lang = request.POST.get('lang_txt') data = custom_function_name(txt) context = {'data': data} else: context = {} return render(request, 'index.html', context) Please help me -
Xlxs file response not correct. It returning garbage symbols on response
def daily_report_summery(request): body = request.body data = json.loads(body) date = data['date'] generate_summary_report_xl(date) with open('./Daily_Report.xlsx', "rb") as file: response = HttpResponse(file.read(),content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=Daily_Report.xlsx' return response I am getting this responce: response I want to send Daily_Report.xlsx file from backend. -
Delete object in django by two parameters by ajax.The object is deleting during declaration .How to retain object for using in templates?
When I try to delete an object by ajax call both ID's are not passing to url Am getting url like 127.0.0:8000/delete// The object is deleting during declaration .How to retain object for using in templates?? urls.py path('delete/<int:a_id>/<int:b_id>',views.delete,name="delete") views.py def delete(request,a_id,b_id): obj=Table.objects.get(a_id=a_id,b_id=b_id) obj.delete() return render(request,"delete.html",{'obj':obj}) delete.html <input type="hidden" id="a_id" data-value="{{obj.a_id}}"> <input type="hidden" id="b_id" data-value="{{obj.b_id}}"> script.js var a_id=$("#a_id").data("value"); var b_id=$("#b_id").data("value"); #some code $.ajax({ url:'delete/'+ a_id +'/' + b_id, #some code }); -
How to store images using Django forms?
I'm new to django. I've been stuck for a while. I believe everything is configured correctly. However, when my objects are created it is not creating the media directory or storing the files/images. I have done the settings file, urls, views, models, forms everything. Here are relevant files: // setting.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') // models.py class Trip(models.Model): city = models.CharField(max_length= 255) country = models.CharField(max_length= 255) description = models.CharField(max_length= 255) creator = models.ForeignKey(User, related_name = 'trips_uploaded',on_delete= CASCADE, null=True) favoriter = models.ManyToManyField(User, related_name= 'fav_trips') photo = models.ImageField(null=True, blank =True, upload_to='trips/') // urls.py ( there were 2 ways to write media according to tutorial) from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('travelsiteapp.urls')) ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) // views.py (lastly) def tripAdd(request): form = TripForm() if request.method == 'POST': form = TripForm(request.POST, request.FILES) if form.is_valid(): form.photo = form.cleaned_data["photo"] form.save() context = { 'form': form} return render(request, 'tripAdd.html', context) // html/ form <form action="/createTrip"method="post" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <input type="submit" value="submit"> </form> // forms.py from django import forms from django.forms import ModelForm from .models import Trip from django import forms … -
How to use the foreign key in condition html Django
everybody. Im beginner in Python and I have this question. Anyone knows why this condition dont works? In the h4 the lancamento.tipo show the information "Receita", but in the condition not works. list.html <div class="list-group"> {% for lancamento in object_list %} {% if lancamento.tipo == 'Receita' %} <a href="#" class="list-group-item list-group-item-success"> <h4 class="list-group-item-heading">{{lancamento.tipo}}</h4> <p class="list-group-item-text">Descrição: {{lancamento.descricao}}</p> <p class="list-group-item-text">Valor: R$ {{lancamento.valor}}</p> </a> {% else %} <a href="#" class="list-group-item list-group-item-danger"> <h4 class="list-group-item-heading">{{lancamento.tipo}}</h4> <p class="list-group-item-text">Descrição: {{lancamento.descricao}}</p> <p class="list-group-item-text">Valor: R$ {{lancamento.valor}}</p> </a> {% endif %} {% endfor %} And the models.py class Usuario(models.Model): nome = models.CharField(max_length=255) cpf = models.CharField(max_length=11, unique=True) saldo = models.FloatField(default=0) def __str__(self): return self.nome class Lancamento(models.Model): tipo = models.ForeignKey('Tipo', on_delete=models.CASCADE) nome_usuario = models.ForeignKey('Usuario', on_delete=models.CASCADE, default='') valor = models.FloatField() descricao = models.TextField() data_lancamento = models.DateTimeField(null=True, blank=True) class Meta: ordering = ['-data_lancamento'] class Tipo(models.Model): nome = models.CharField(max_length=255) def __str__(self): return self.nome And the views.py, using the Class Based Views from django.shortcuts import render from django.views.generic import ListView from core.models import Lancamento # Create your views here. def index(request): return render(request, 'core/index.html') class LancamentoList(ListView): model = Lancamento queryset = Lancamento.objects.all() -
DJango channels subscribe to multiple events
I have django application with channels. It opens websocket connection to Crypto-market data provider. I received tick data, I insert those ticks in the database. I also want to send that tick data to other application (say frontend). But I am not able to it efficiently. Currently only single frontend application is present. So when it connects to django channels, I add that connection to group named('root') and send all the market-tick data to that group. So the problem here is, If I decide to connect second frontend application, I get all the data that first user was requesting (as both clients are present in group 'root' on django). I tried a method were when a users requests data for particular crypto, then I added him to that crypt-named group (if user want bitcoin data only, I added him to bitcoin group) But I get lots crpto-data on django server and very big number of ticks per second. It feels kind of slow to send each tick data to that particular crypto group channel ( on tick check symbol and forward that tick to that symbol-named django channel). Any suggestion on how to approach to this problem.? -
Django Import-Export: Issues importing to model with UUID for id field
I am trying to import a csv file (utf-8 encoded) via Django Admin into a Django model using the Django-import-export package(v3.0.0b4). I was initially working with the last stable version but was encouraged to try the pre-release. The import preview looks correct but the interface shows the following error for all rows of the csv: Non Field Specific “” is not a valid UUID. I have tried several permutations of including 'id' in import_id_fields or excluding the 'id' field and using a renamed 'unique_id' field as a hook. I've also attempted the import with blank entries in both an 'id' column and 'unique_id' column of the csv. Also with the id field omitted from the csv entirely. For some reason a blank field is being returned regardless of whether I populate the id fields or not. I suspect I'm doing something small wrong, but I'm not clear on what. resources.py, models.py, and admin.py included below. Happy to share other snippets if needed. models.py from django.db import models from django.db.models import Sum import uuid from datetime import datetime class Purchase(models.Model): id = models.UUIDField(primary_key=True,default=uuid.uuid4, editable=False) date = models.DateField(blank=True,null=True) seller = models.CharField(max_length=200,default='') number = models.CharField(max_length=200,blank=True,default='') customer = models.CharField(max_length=200,default='') salesperson = models.CharField(max_length=200,blank=True,default='') discount = …