Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save a form which contains a container div with sub-divs that have been dynamically added in django
I am working on a job portal system. I provide users the change to edit their profiles by adding and removing job experience. The issue is I don't know how to send that data to the view so that it can retrieve all the fields and store them in the database accordingly. By retrieving, I mean for each job experience, retrieve their corresponding sub fields Here is my template file: <!--JOB EXPERIENCE--> <div class="job_experience"> <h5>Experience</h5> <hr> <!--FORM--> <form action="#" id="save_job_experience_form" method="POST"> {% csrf_token %} <div class="job_container"> {% for job in job_experience %} <div class="exp"> <label>Organisation</label> <input type="text" class="form-control" name="organisation placeholder="Organisation" value="{% if job.organisation %} {{job.organisation}}{% endif %}" required> <label>Job Title</label> <input type="text" name="job_title" class="form-control" value="{% if job.job_title %}{{ job.job_title }}{% endif %}" placeholder="Job Title e.g Backend Developer" required> <button style="margin-left:15px;" type="button" class="btn btn-danger remove_job_exp"><strong>Delete Job Experience</strong></button> </div> <hr> {% endfor %} </div> <!--BUTTONS--> <input type="submit"value="Save"> <input type="button" id="add_job_experience"value="Add one"> </form> </div> <script> $(document).on('click', '#add_job_experience',function(e){ e.preventDefault(); $(".job_container").append(`<div class="exp"> <!--IT GOES ON AS ABOVE --> $(document).on('click', 'button.remove_job_exp', function(e){ e.preventDefault(); $(this).closest('div.exp').remove(); }); models.py class StudentWorkExperience(models.Model): student = models.ForeignKey(StudentUser, on_delete=models.CASCADE) organisation = models.CharField(max_length=100) job_title = models.CharField(max_length=50) job_desc = models.TextField(null=True, blank=True) country = models.CharField(max_length=254) city = models.CharField(max_length=100) state = models.CharField(max_length=200) start_month = models.CharField(max_length=10, null=True, blank=True) … -
Django form errors are not showing in template
no form errors are showing up in my HTML template when the form is invalid. The form is placed within a carousel incase that's relevant. I'm calling out individual form elements instead of rendering as {{form.as_p}}, errors where showing when this was the case. The last item in the carousel is the password and if I leave this blank it will show a pop out that says "please fill in this field" but nothing more than that and only for that one field. Views.py def collapsecard(request): if request.method == 'POST': create_user_form = CreateUserForm(request.POST) safezone_form = SafezoneForm(request.POST) if create_user_form.is_valid() and safezone_form.is_valid(): user = create_user_form.save() safezone = safezone_form.save(commit=False) safezone.userid = user safezone.useremail = user.email safezone.save() user = authenticate(username=create_user_form.cleaned_data['username'], password=create_user_form.cleaned_data['password1'], ) login(request,user) api_key = 'XYZ' api_secret = 'XYZ' id = 'XYZ' mailjet = Client(auth=(api_key, api_secret)) data = { 'Email': safezone.useremail, 'Action': "addnoforce" } result = mailjet.contactslist_managecontact.create(id=id, data=data) print result.status_code print result.json() return redirect('safezoneaddedpage') return redirect('safezoneaddedpage') else: create_user_form = CreateUserForm() safezone_form = SafezoneForm() print(create_user_form.errors) print(safezone_form.errors) return render(request, 'V2maparonno_create_safe_zoneV2.html', {'create_user_form': create_user_form, 'safezone_form': safezone_form}) Extract from HTML <form action="" method="POST" class="form-control"> {% csrf_token %} <div id="carouselExampleIndicators" class="carousel slide" data-interval="false" style="width: 100%"> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li> <li data-target="#carouselExampleIndicators" data-slide-to="1"></li> <li data-target="#carouselExampleIndicators" data-slide-to="2"></li> <li data-target="#carouselExampleIndicators" data-slide-to="3"></li> … -
Django channels Add users to group
I'm using django channels I'm making a Facebook clone and trying to add real time notifications using channel, so I've this idea when a notification happens i create a group and add the users the one who sent it and the one who received it and after receiving it, then the group gets discarded, can this be accomplished? -
Django All-auth, disable automatic login with google
I've got a similar problem to this question but I don't have enough reputation to comment on the original post. Django all-auth: How to disable automatic login via Google I'd like the user to choose a specific google account (because I'm filtering by a company email), the automatic login doesn't allow the user to change accounts when signing up and instead brings them to the "sign up is closed" page. Very new to Allauth and Oath so any help would be appreciated. I'm overriding the defualtsocialaccountadapter to filter the emails getting through and that works fine on incognito. -
How 'set_password' method works?
I've been looking for this in DRF and Django doc but I can't find it. Someone could explain how the base method works? Thanks! -
session maintain with simple salesforce
I would like to do session maintenance with simple salesforce. I am using dJango web framework for a tool I developed which is to update data salesforce. Can somebody help with below tasks Would like to sign-in to salesforce without providing Salesforce credentials like Username, password & security token If User wont provides credentials in web page, then framework should consider existing/previous session logged-in successfully. Session should expire after 30 minutes of in-Active I tried to save session in file where i can retrieve for next time, but facing multiple errors file = open(sf_sess_fl, "w") file.write(sf.instance) error: File "", line 1, in TypeError: write() argument must be str, not SFType Thank you in advance Dharani 3. -
Django_filters - MultipleChoiceFilter with ForeignKey not shown
I'm trying to filter a digital product with multiple filters. On of them includes the functionality model. So the user select a category and then, related to the category, can filter the existing products by their functionality models.py class DigitalProduct(models.Model): name = models.CharField(max_length=200, verbose_name='Name') thumbnail = models.ImageField(upload_to='DigitalProduct/thumbnails') category = models.ForeignKey(Category, on_delete=models.CASCADE) class Category(models.Model): category = models.CharField(max_length=200) filter_functions = models.ManyToManyField(Functionality, verbose_name='Filter by') class Functionality(models.Model): functionality = models.CharField(max_length=200) I installed django-filter v2.4.0 and trying to add the filters. filters.py ... class PlatformFilter(django_filters.FilterSet): func = django_filters.MultipleChoiceFilter(field_name='category', conjoined=True) Inside of my views.py function I pass the queryset=Platform.objects.filter(category=category) to get the correct digital products, which is working fine but the category values aren't shown in the MultipleChoiceField. So far I can see the MultipleChoiceField but no values are shown. I tried to change the field name to field_name='category.category' but I get an [invalid name]. Do I miss something? -
Rendering geojson with folium / leaflet.js in django
In a django application I render some geojson using the folium library. This generates html that I can use to display my map, and that all works great. Except that it's pretty sure it owns the universe: it generates the entire page: <!DOCTYPE html> <head>...</head> <body>...</body> <script>...</script> (Note that it doesn't generate an html tag.) My issue is that my site is themed in a certain way, I expect other content on this page explaining the map, my standard headers and footers. And inserting the folium-generated code into my page messes with that. My get_context_data() function, after some database lookups to get the geojson and other parameters I need for my multi-layer map, is just this: geomap = folium.Map(...) root = geomap.get_root() html = root.render() context["html_map"] = html return context Any suggestions how to integrate folium with django? (Or suggestions that I should be doing something totally different?) -
Better many to many filtering logic
Let's say I have 2 models like this: class ModelA(AbstractUser): is_author = models.BooleanField(default=True) class ModelB(models.Model): user = models.ForignKey(ModelA, ondelete=models.CASCADE) liked = models.BooleanField(default=False) date = models.DateTimeField(auto_now_add=True) Right now, let's say I wanted only all ModelB objects liked by the logged-in user, I would do something like this in my view: def view_funct(request): user = request.user modelb_objects = ModelB.objects.filter(liked=user).order_by("-date") This works, however, I feel like there is better and faster filtering I don't know of yet. Is there? -
Login Method in Django works fine with POSTMAN but with front end everything works except Login Method
I am new to React Js and want to connect my React app with Django.I had created CustomUser for authentication purpose , login() for session and used rest_framework.auth.Token (Token) for login Purpose. Now when I am sending POST Request through POSTMAN it creates sessions properly and return email and auth-token but when I am sending POST Request with React Js (Front End) Everything works properly (returns email and token) but login method doesn't create sessions, due to which user.is_authenticated returns False. How to solve this problem. Thanks in Advance. My views.py @csrf_exempt def signin(request): if request.method == 'GET': if request.user.is_authenticated: token,created = Token.objects.get_or_create(user=request.user) return JsonResponse({"Email":request.user.email,"Auth-token":token.key},safe=False) return render(request,'application/signup.html') if request.method == 'POST': # if not request.user.is_authenticated: data = JSONParser().parse(request) email = data['email'] print(email) b1 = email.replace("@","") password = data['password'] print(password) user = authenticate(request,email=email,password=password) if user: location = str(pathlib.Path().absolute())+'\Camera\DatabaseImage\DatabaseImage\\' + b1 + '.jpg' print(location) answer = facedect(location) if answer=="Retry": messages.error(request,"Captured Image is not clear Please be in light") #React #return render(request,"application/signup.html") return JsonResponse("Captured Image is not clear Please be in light",safe=False) if answer == True: login(request,user) token,created = Token.objects.get_or_create(user=request.user) messages.success(request,"Account created") #React #return redirect('http://localhost:8000/homepage/') return JsonResponse({"Email":request.user.email,"Auth-token":token.key,"answer":"abhi login hua hai"},safe=False) else: print("Face Not Found") messages.error(request,"Face Not Found") #React #return render(request, 'Facebook.html') return JsonResponse("Face … -
Django: how to get multiple input?
I m working on cylinder management system in which i want to give functionality that user can issue multiple cylinder. What i m wanting that user get a list of available cylinder where he can choose the cylinders item and submit the form. I m able to handle this for single cylinder , here is what i m applying for single cylinder:- models:- class Cylinder(models.Model): stachoice=[ ('Fill','fill'), ('Empty','empty') ] substachoice=[ ('Available','available'), ('Unavailable','unavailable'), ('Issued','issued') ] cylinderId=models.CharField(max_length=50,primary_key=True,null=False) gasName=models.CharField(max_length=200) cylinderSize=models.CharField(max_length=30) Status=models.CharField(max_length=40,choices=stachoice,default='fill') Availability=models.CharField(max_length=40,choices=substachoice,default="Available") EntryDate=models.DateTimeField(default=timezone.now) issue_Date=models.DateTimeField(null=True) issue_user=models.CharField(max_length=70,null=True) return_Date=models.DateTimeField(null=True) def get_absolute_url(self): return reverse('cylinderDetail',args=[(self.cylinderId)]) def __str__(self): return str(self.cylinderId) class Issue(models.Model): cylinder=models.ForeignKey('Cylinder',on_delete=models.CASCADE) userName=models.CharField(max_length=60,null=False) issueDate=models.DateTimeField(default=timezone.now) def save(self,*args,**kwargs): if not self.pk: if self.cylinder.Availability=='Available': Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability=('Issued')) Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(issue_Date=self.issueDate) Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(issue_user=self.userName) super().save(*args,**kwargs) def __str__(self): return str(self.userName) class Return(models.Model): fill=[ ('Fill','fill'), ('Empty','empty'), ('refill','Refill') ] ava=[ ('yes','YES'), ('no','NO') ] cylinder=models.ForeignKey('Cylinder',on_delete=models.CASCADE) availability=models.CharField(max_length=20,choices=ava) status=models.CharField(max_length=10,choices=fill) returnDate=models.DateTimeField(default=timezone.now) def save(self,*args,**kwargs): if not self.pk: if self.cylinder.Availability=='Issued': Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(return_Date=self.returnDate) if self.availability=='YES' or self.availability=='yes': Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability='Available') if self.status=='empty' or self.status=='Empty': Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(Status='Empty') else: Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability='Unavailable') if self.status=='refill' or self.status=='Refill': Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(Status='Refill') if self.status=='empty' or self.status=='Empty': Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(Status='Empty') super().save(*args,**kwargs) def __str__(self): return str(self.cylinder) views:- @login_required def issue(request): if not request.user.is_superuser: return redirect('index') form=IssueForm() if request.method=='POST': form=IssueForm(data=request.POST,files=request.FILES) if form.is_valid(): form.save() return redirect(cylinderListView) return render(request,'entry/cylinder_form.html',{'form':form}) form template:- <div class='col-lg-12' id="divForm"> <br> <div class="form-group " id="form1"> <h3>New Entry</h3> <form method="post" > {% csrf_token %} {{ … -
Can i send POST request to view function from another view function in django?
I am creating a Django multi-wizard form. I need to send Data to an already created view through post request Here is the Wizard form: class UserQueryWizard(SessionWizardView): template_name = "wizards/index.html" form_list = [forms.ShippingForm, forms.ExporterdetailsForm, forms.ImporterdetailsForm, ] def done(self, form_list, **kwargs): post_data = [form.cleaned_data for form in form_list] ------need to send this post_data ------ return SEND('query/',method='POST') <--- Example I know its not correct its ruff idea what I want I set up the URL Like this: path('query/', views.UserQueryView.as_view(), name='user_query'),<--- Where i send POST Request And the view class UserQueryView(View): def post(self, request, *args, **kwargs): importer = request.POST.get('importer', '') .......etc...................... query = UserQuery.objects.create( make=make, model=model, version=version, launch_date=launch_date, body_type=body_type, importer_type=importer_type, vehicle_condition=condition, mileage=mileage, chasis_number=chasis_number, engine_number=engine_number, fuel_type=fuel_type, vehicle_color=vehicle_color, seating_position=seating_position, importer=importer, importer_country=importer_country, importer_city=importer_city, importer_name=importer_name, exporter_name=exporter_name, exporter=exporter, exporter_country=exporter_country, exporter_city=exporter_city, hs_code=hs_code ) result = render_to_string( 'partials/_alert.html', {"type": "success", "message": "Query Saved Successfully"}, request=request) query = render_to_string( 'partials/_table_row.html', {'vehicle': query}, request=request) return JsonResponse({"message": result, 'query': query}) -
How to include urls file from sub sub folder in django
i try to include urls from my Api folder i tried path('api/', include("main.Apps.Api.apps.urls")) but it doesn't work in my settings.py i add the app by INSTALLED_APPS += ["main.Apps.Api.apps.ApiConfig"] and i changed the app name in Api.apps.py to name = 'MikeWebsite.Apps.Api' Everything works But include the urls return me ModuleNotFoundError: No module named 'MikeWebsite.Apps.Api.apps.urls'; 'MikeWebsite.Apps.Api.apps' is not a package my project file tree look like this main └───_main ├── __init__.py ├── settings.py ├── urls.py ├── wsgi.py └──_Apps ├──_Api | └── urls.py └── ... What I'm doing is wrong? And if you have a good source of information on how to work with apps nested in Django -
Accessing the file path from object created via mutagen.File() python django
I'm using django and filefields to upload a file to s3. I need to get the local path of the file in the the pre_save signal. Currently I am doing the following: def pre_save(sender, instance, **kwargs): mutagen_file = mutagen.File(instance.audio) Where instance is the model and audio is the FileField property. I think I found a work around via: instance.audio._file.temporary_file_path() but that should fail with files under 2.5MB and the mutagen variant wouldn't (if I could get the path from the mutagen_file object. -
DRF and Knox showing logged in user as anonymous (Django)
as I created an API with DRF and Knox and I am using token based authentication. Everything is working except the system is showing the logged in user as anonymous. I tried all this: current_user = request.user print(current_user.is_anonymous) # True print(current_user.is_authenticated) # False print(current_user.is_staff) # False print(current_user.is_superuser) # false print(current_user.is_active) # false u = User() print(u.id) # None I need the user id of the logged in user because I am using that as a foreign key in the other table. I checked the auth_user table and it has all the columns. Is there any way to get the user id or convert the anonymous user to authenticated user ? Thanks AJ -
Filter users by roles during serialization
I have a User model with 3 roles Teacher, Student, Admin as the choices. I wanted to have only users whose role is Teacher in TeacherSerializer. So, like this for Students and Admins. When I creating a Batch wise course I have to assign a Tutor(Teacher) in the API URL under tutor I wanted to show the users who are teachers. Who aren't teachers should not be included in that list -
Daphne server halts after executing a very long process in a Django Channels-based architecture
I am building a system for processing data and then train ML models using sklearn's builtins. I used digital ocean for deployment with Ubuntu, Nginx, Gunicorn, Daphne, Django, and Channels. All features work fine until it is required to train larger datasets through channels (sockets) asgi connection. When the execution starts, it takes few moments until the server (asgi) stops responding and all other WebSockets stop working, HTTP ones are fine though. I have followed the following tutorial for deployment: CodingWithMitch Channels Deployment, when I restart the server again with these commands, everything starts working fine except the training part (the long process): sudo systemctl daemon-reload sudo systemctl restart gunicorn sudo systemctl restart nginx sudo systemctl restart redis.service service daphne restart Restarting Daphne was the critical one I noticed. The confusing part is, the server logs show no error whatsoever. It seems to be an issue with the websockets keepalive timeout as my initial guess, but even after I increase the timeout in my nginx.conf file it and restart, it doesn't change the behavior: /etc/nginx/sites-availabel server { server_name 159.203.13.90; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/django/EasyAI; } location / { include proxy_params; proxy_pass … -
TypeError: list indices must be integers or slices, not str . while working with json
I am making a simple weather app using API. I got the error: list indices must be integers or slices, not str. I know where the problem is but I don't know how to solve it. my code is: `from django.shortcuts import render import urllib.request import json Create your views here. def index(request): if request.method == 'POST': city = request.POST['city'] source = urllib.request.urlopen('http://api.openweathermap.org/data/2.5/weather?q='+city+'&appid=5ba7df1f751428007642bf4e5f6c4c9a').read() list_of_data = json.loads(source) data = { "country_code": str(list_of_data['sys']['country']), "coordinate" : str(list_of_data['coord']['lon']) + ' ' + str(list_of_data['coord']['lat']), "temp" : str(list_of_data['main']['temp']) + 'k', "pressure": str(list_of_data['main']['pressure']), "humidity": str(list_of_data['main']['humidity']), "weather" : str(list_of_data['weather']['description']), } print(data) else: data = {} return render(request, 'main/index.html', data)` The problem is in the last line of the data dictionary. I don't know how to write it. Please help me with this. -
Is there will be any issue on django if I try to add a user to a group in which he/she already in
I am adding a user who is done some donation in the app to a group. My code is below: donation_event_group.user_set.add(customer_obj) My question is will there be any issue behind the scenes, if I try to add the user again, Like when the user try to donate more than once my code for adding him to the group will still execute. I don't have any errors in console so far, so I think there is no problem at all. Will there will be any problem? Or do I need to a strict checking and add only if the user is not in the group? -
Django Error: Field 'id' expected a number but got 'list'
I have an app with 2 models and I'm trying to create a List View and a Detail View. The list view worked fine, but when I created the detail view the list view stopped working and it's prompting me with this error: "Field 'id' expected a number but got 'list'. Models.py from django.db import models # Create your models here. class schools(models.Model): name=models.CharField(max_length=256) principal=models.CharField(max_length=256) def __str__(self): return self.name class students(models.Model): name=models.CharField(max_length=256) age=models.PositiveIntegerField() school=models.ForeignKey(schools,related_name='students',on_delete=models.CASCADE) views.py from django.shortcuts import render from django.views.generic import DetailView,ListView,CreateView,FormView,UpdateView from basicapp import models,forms from django.http import HttpResponseRedirect, HttpResponse # Create your views here. class SchoolListView(ListView): model = models.schools class SchoolDetailView(DetailView): context_object_name='schools_detail' model=models.schools template_name='basicapp/schools_detail.html' urls.py from django.contrib import admin from django.urls import path,re_path from basicapp import views urlpatterns=[ re_path(r'^(?P<pk>[-\w]+)/$',views.SchoolDetailView.as_view(),name="detail"), path('list',views.SchoolListView.as_view(),name="list"), path('create',views.cview.as_view(),name="create"), path('index',views.index,name='index'), ] and my templates: {% extends 'basicapp/base.html' %} {% block body_block %} <h1>Welcome to the List of Schools Page!</h1> <ol> {% for school in schools_list %} <h2> <li><a href="{{school.id}}"></a>{{school.name}}</li> </h2> {% endfor %} </ol> {% endblock %} {% extends 'basicapp/base.html' %} {% block body_block %} <div class="jumbotron"> <h1>School Detail Page</h1> <h2>School Details:</h2> <p>{{ schools_detail.name }}</p> <p>{{ schools_detail.principal }}</p> <h3>Students:</h3> {% for student in school_detail.students.all %} <p>{{ student.name }} who is {{ student.age }} years old.</p> … -
Using html input type month to show the value of year and month in Django
I have an input type month where I ask a user to type the start_month and start_year for a job. However, the field month is optional. Like a user can only specify the start year. In my model, I store start_month as a CharField with values like 'January', 'February'. I store start_year as an IntegerField. I already have the values stored and I have even successfully retrieved them such that they show up in the template if i do {{ job.start_month }} The issue is how do I display that by the value attribute in the input type month provided that a user can have only year and month or year? Thank you for your help guys Note: I am not comfortable with Django forms :/ Here is my code snippet: <div class="form-group col-md-6"> <label for="start">From:</label> <input style="margin-left: 5px;" type="month" id="start" value="{% if job.start_month %}{{ }}{% endif %}" name="start"> <p style="color: red;">Month is optional</> </div> -
connect() to unix:/run/gunicorn.sock failed (111: Connection refused) while connecting to upstream - Trying to upload django app to digitalocean
I am trying to upload my django project to digitalocean droplet. Followed this article https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-20-04 to upload it. After completing all the steps I am getting 502 bad gateway. Also the server is not running on SSL rather it is running on http//. I followed every steps the article provided. Somehow there is an error called "connect() to unix:/run/gunicorn.sock failed (111: Connection refused) while connecting to upstream" /etc/systemd/system/gunicorn.socket ----- [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target /etc/systemd/system/gunicorn.service ---- [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=sammy Group=www-data WorkingDirectory=/home/sammy/myprojectdir ExecStart=/home/sammy/myprojectdir/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ myproject.wsgi:application [Install] WantedBy=multi-user.target /etc/nginx/sites-available/myproject ----- server { listen 80; server_name server_domain_or_IP; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/sammy/myprojectdir; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } I ran this commands but getting no error sudo nginx -t && sudo systemctl restart nginx So I need help on this. -
Separating User Settings on to different views in Django
I was wondering if anyone could provide me when any references or guidance on achieving the following outcome: On my User Settings view currently, I am displaying the Username, Email and Profile Avatar fields belonging to a specific user. However as I begin to add more settings, it would be quite a nice touch if I could somehow separate these settings in to categories of their own to make it more clearer for users to navigate amongst the settings they wish to update. For example, on the Facebook app when you tap on to Settings, they feature a list of clickable setting categories e.g. General Information, Privacy & Security, Language and so forth. I think categories is perhaps the wrong term to use, I'm guessing "Setting Groups" would be a better way to describe the outcome of which I'm hoping to achieve. If anyone knows of any guidance, tips or references to achieving this outcome, that would be super helpful! Thanks, Jay. -
How to select distinct column A, then aggregate values of of column B in DJANGO?
I try to create a crypto portfolio webpage. My problem is the following. Current Transactions table when i render the html: Crypto_Name Total Trade Value BTC 150 BTC 100 DOGE 200 DOGE 210 Desired Transaction table: Crypto_Name Total Trade Value BTC 250 DOGE 410 I would like to select distinct values of Crypto_Name and then summarize the values in Total Trade Value. models.py: class Transaction(models.Model): """Model representing a trade.""" portfolio = models.ForeignKey('Portfolio',on_delete=models.CASCADE) coin = models.ForeignKey(Coin,on_delete=models.CASCADE) number_of_coins = models.DecimalField(max_digits=10, decimal_places=0) trade_price = models.DecimalField(max_digits=10, decimal_places=2) date = models.DateField() def __str__(self): return str(self.portfolio) @property def total_trade_value(self): return self.trade_price * self.number_of_coins views.py query: def my_portfolio(request): filtered_transaction_query_by_user = Transaction.objects.filter(portfolio__user=request.user) ... What I have tried among many things: test = filtered_transaction_query_by_user.order_by().values('coin__name').distinct() It gives me just two crypto name in an ugly format {'coin__name': 'Bitcoin'} {'coin__name': 'Doge'} but the other columns are empty when I render them in the html. I appreciate your help!!! :) -
How can I use django-bootstrap-icon inside JQuery insert function?
I'd like to insert bootstrap buttons into a table data element. What I've been doing until now, is something like: $("<td>").insert("{% bs_icon 'pencil-square' %}"); // or $("<td>").insert("{% bs_icon 'pencil-square' %}".toString()); // or similar things All I could achieve is > Uncaught SyntaxError: Invalid or unexpected token Is there any way I could make it work by scaping the svg tag generated by django-boos