Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best django fieldtype(postgres datatype) to save python hashlib hexdigest (40 characters)
What is the best field type in django to save a fixed length (40 characters) hexdigest? This field is indexed and needs to be optimized for storage and querying. Currently we use CharField but doesn't seem to be optimal as this is varchar class MyModel(models.Model): ... my_field = models.CharField(max_length=40, null=True) class Meta: indexes = [models.Index(fields=["my_field"])] -
Any reason that .distinct() is outputting multiple rows? - Django/PostgreSQL
Is there any reason that this query Finances.objects.order_by('payout').distinct('payout') is still returning multiple rows? It returns 3 rows. I have an aggregate function getting the sum of the rows in the database. That looks like this: @property def Calculate_bank(self): totalpayout = Finances.objects.all().aggregate(Sum('payout'))['payout__sum'] or 0.00 totalwithdraw = Finances.objects.all().aggregate(Sum('withdraw'))['withdraw__sum'] or 0.00 totalbank = totalpayout - totalwithdraw return totalbank @property def Calculate_cash(self): totalwithdraw = Finances.objects.all().aggregate(Sum('withdraw'))['withdraw__sum'] or 0.00 totalcash = Finances.objects.all().aggregate(Sum('cash'))['cash__sum'] or 0.00 totalbank = totalwithdraw - totalcash return totalbank I then use the Finances.objects.order_by('payout').distinct('payout') query in view.py and it displays three rows of the same output? If I add more order_by or distinct filters, it duplicated the three rows already showing. I have tried filtering by id as well. If I do not use the distinct, it shows a new row for everytime there is an entry in the database. -
Django Add Custom Attributes to Model Fields
I have a model with a large number of fields that store float values: class Report(models.Model): field1 = models.Floatfield(...) field2 = models.Floatfield(...) ... The fields need to be able to have public-facing names that differ based on who is using it. For example, field1 might be named "Apples" for one user, but should display "Bananas" for another. I know that FloatField has a verbose_name option, but it seems like it has to be hardcoded and is not able to be dynamic. It is ideal for our setup that this is stored as data is written to the database. What is the best practice for setting something like this up? Is it best to use a custom field and add attributes? Do these attributes save when the model object is created? -
Not being redirected to the redirect_uri in live server | Spotipy
I am using Django and when I run a local server at localhost:8000, this piece of code works as intended: spotipy.Spotify( auth_manager=SpotifyOAuth( redirect_uri=config["REDIRECT_URI"], client_id=config["SPOTIPY_CLIENT_ID"], client_secret=config["SPOTIPY_CLIENT_SECRET"], scope="user-library-read user-library-modify playlist-modify-private playlist-modify-public", cache_handler=spotipy.DjangoSessionCacheHandler(request), ) ).current_user() It redirects me to http://localhost:8080/callback and fetches all the data by itself and caches the received token. But when I do the same on a live server, it doesn't redirect me and the bash asks me to input the URL I have been redirected to. I even tried including a false redirect_uri but it still asks me for the URL I have been redirected to. I have no idea what I am doing wrong, any help is appreciated. -
Making Javascript files private in Django Project
I am following a tutorial to integrate Apple Pay payments (w/ Stripe) into my website using Javascript to process the payments. The Javascript file renders the Apple Pay Button as well as actually processing the payment. I need to pass a secret key into one of the functions, but the file is public b/c its in my static folder. What can I do to either make the Javascript file private or at least make some of the functions private so I don't need to worry about hackers stealing my key from the static files? -
Django and Javascript. Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
Tengo un formulario el cual al momento de enviarlo, recibo la información por javascript para realizar una serie de validaciones y enseguida por fetch envió la información al servidor (una api sencilla creada con django). El código cuando lo trabajaba en un etorno de desarrollo funcionaba correctamente pero ahora que lo trabajo en un entorno de producción y lo desplegué en heroku me da el error. El código es el siguiente: formulario.addEventListener('submit', (e) => { e.preventDefault(); fetch('https://portafolioadrian.herokuapp.com/contacto', { method: 'POST', body: JSON.stringify({ nombre: document.querySelector('#nombre').value, correo: document.querySelector('#correo').value, telefono: document.querySelector('#telefono').value, mensaje: document.querySelector('#form__message').value, terminos : document.getElementById('terminos').checked, }), headers: { 'X-CSRFToken': getCookie('csrftoken'), "Accept": "application/json", 'Content-Type': 'application/json'} }) .then(res => res.json()) .then(res => { if (res.success) { formulario.reset(); document.getElementById('form__message-success').classList.add('form__message-success-active'); setTimeout(() => { document.getElementById('form__message-success').classList.remove('form__message-success-active'); }, 5000); document.querySelectorAll('.form__group-correct').forEach((icono) => { icono.classList.remove('form__group-correct'); }); }else{ document.getElementById('form__message').classList.add('form__message-active'); } }) }); Al momento de enviarlo, por consola me da el siguiente error Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 El urls.py de la app es esta: urlpatterns = [ path('', views.contacto, name='contacto'), path('mensajes/', views.mensajes, name='mensajes'), ] Y la view es la siguiente: def contacto(request): if request.method == "POST": data = json.loads(request.body) nombre = data['nombre'] correo = data['correo'] telefono = data['telefono'] mensaje = data['mensaje'] terminos = data['terminos'] … -
Searching by multiple categories in Django
Hi everyone! I want search by multiple categories, but my code is not working. When I type categories name, I got nothing. Can anyone help me? '''views.py''' class ExpenseListView(ListView): model = Expense paginate_by = 5 def get_context_data(self, *, object_list=None, **kwargs): queryset = object_list if object_list is not None else self.object_list form = ExpenseSearchForm(self.request.GET) if form.is_valid(): name = form.cleaned_data.get('name', '').strip() if name: queryset = queryset.filter(name__icontains=name) return super().get_context_data( form=form, object_list=queryset, summary_per_category=summary_per_category(queryset), get_per_year_month_summary=get_per_year_month_summary(queryset), **kwargs) def get_queryset(self): queryset = super(ExpenseListView, self).get_queryset() q = self.request.GET.get("q") if q: return queryset.filter(date__icontains=q) return queryset def get_gategory(request, pk_test): category = Category.objects.get(id=pk_test) orders = category.order_set.all() order_count = orders.count() myFilter = OrderFilter(request.GET, queryset=orders) orders = myFilter.qs context = {'category': category, 'orders': orders, 'order_count': order_count, 'myFilter': myFilter } return render(request, 'expense_list.html',context) '''May be my problem is in my vieews or in models. I m new in Django and dont nkow many things..''' ''' Here my models.py''' class Category(models.Model): class Meta: ordering = ('name',) name = models.CharField(max_length=50, unique=True) def __str__(self): return f'{self.name}' class Expense(models.Model): class Meta: ordering = ('-date', '-pk') category = models.ForeignKey(Category, models.PROTECT, null=True, blank=True) name = models.CharField(max_length=50) amount = models.DecimalField(max_digits=8, decimal_places=2) date = models.DateField(default=datetime.date.today, db_index=True) def __str__(self): return f'{self.date} {self.name} {self.amount}' '''html'' {% extends "base.html" %} {% block content %} <a … -
How do I configure my Django server to avoid Firefox "Response body is not available to scripts (Reason: CORS Missing Allow Header)" errors?
I'm running Django 3.2, Python 3.9 and trying to execute a fetch request in Firefox. Specifically, this OPTIONS request curl 'http://localhost:8000/login' -v -X OPTIONS -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:102.0) Gecko/20100101 Firefox/102.0' -H 'Accept: */*' -H 'Accept-Language: en-US,en;q=0.5' -H 'Accept-Encoding: gzip, deflate, br' -H 'Access-Control-Request-Method: POST' -H 'Access-Control-Request-Headers: content-type' -H 'Referer: http://localhost:3000/' -H 'Origin: http://localhost:3000' -H 'Connection: keep-alive' -H 'Sec-Fetch-Dest: empty' -H 'Sec-Fetch-Mode: cors' -H 'Sec-Fetch-Site: same-site' -H 'Pragma: no-cache' -H 'Cache-Control: no-cache' returns this error in Firefox Response body is not available to scripts (Reason: CORS Missing Allow Header) I'm not sure what Firefox is complaining about. When I run the above request in curl, I get these headers * Trying ::1... * TCP_NODELAY set * Connection failed * connect to ::1 port 8000 failed: Connection refused * Trying 127.0.0.1... * TCP_NODELAY set * Connected to localhost (127.0.0.1) port 8000 (#0) > OPTIONS /login HTTP/1.1 > Host: localhost:8000 > User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:102.0) Gecko/20100101 Firefox/102.0 > Accept: */* > Accept-Language: en-US,en;q=0.5 > Accept-Encoding: gzip, deflate, br > Access-Control-Request-Method: POST > Access-Control-Request-Headers: content-type > Referer: http://localhost:3000/ > Origin: http://localhost:3000 > Connection: keep-alive > Sec-Fetch-Dest: empty > Sec-Fetch-Mode: cors > Sec-Fetch-Site: same-site … -
Is there a way to keep Javascript files private in a Django project?
I have a Django project where I would like to accept Apple Pay payments. I followed a tutorial that uses Stripe with Javascript to process the payments. The Javascript is responsible for rendering the Apple Pay button, as well as using several functions to actually process the payment. Naturally, my javascript file ended up being public because it was in my static folder. However, I need to pass a secret key into one of these functions. Is there a way I can rearrange my project so that the Javascript file is private? Alternatively, is there a way to make some of my functions private so that I don't have to worry about hackers stealing my key from my static files? -
Django query returns multiple rows of Sum, I only want to display one row
currently the way I have the code written is that I have a model named Finances. I have an aggregate set up so it sums up all of the rows. I am trying to display the outcome of the rows, but when I do it displays a row for every database entry. I understand that I am grabbing all with .all() in the viewpayout = Finances.objects.all() in views.py, but I am unsure of how this should be written to only display one row. How would I display only one row that sums up all of the rows for a column? Any help is greatly appreciated! Below is my code: views.py def finances(request): viewpayout = Finances.objects.all() updatepayout = UpdatePayout() updatewithdraw = UpdateWithdraw() updatecash = UpdateCash() if request.method == "POST": if 'add_payout' in request.POST: updatepayout = UpdatePayout(request.POST) if updatepayout.is_valid(): post = updatepayout.save(commit=False) post.save() return redirect("/finances") else: updatepayout = None if 'bank_withdraw' in request.POST: updatewithdraw = UpdateWithdraw(request.POST) if updatewithdraw.is_valid(): post = updatewithdraw.save(commit=False) post.save() return redirect("/finances") else: updatewithdraw = None if 'add_cash' in request.POST: updatecash = UpdateCash(request.POST) if updatecash.is_valid(): post = updatecash.save(commit=False) post.save() return redirect("/finances") else: updatecash = None return render(request, 'portal/finances.html', {"updatepayout": updatepayout, "updatewithdraw": updatewithdraw, "updatecash": updatecash, "viewpayout": viewpayout}) model.py class Finances(models.Model): payout … -
Django join tables
How can I join the below tables in the view to get the addresses of all the Dials in DataUpload table from BO table. class BO(models.Model): id = models.AutoField(primary_key=True) Dial = models.IntegerField() Customer_Address = models.CharField(max_length=100, null=True, blank=True) Wallet_Limit_profile = models.CharField(max_length=100, null=True, blank=True) class DataUpload(models.Model): Dial = models.IntegerField() Serial = models.IntegerField(null=True) Bag = models.IntegerField(null=True) Today_Date = models.DateField(null=True) user = models.CharField(max_length=100) summary = models.ForeignKey(summary, on_delete=models.CASCADE) summary_text = models.CharField(max_length=100, null=True, blank=True) Name = models.CharField(max_length=100) C**ustomer_Address = models.ForeignKey(BO, on_delete=models.CASCADE, null=True, blank=True)** National_ID = models.IntegerField() Customer_ID = models.IntegerField() Status = models.CharField(max_length=100) Registration_Date = models.DateTimeField(max_length=100) Is_Documented = models.CharField(max_length=100, null=True) Needed_Action = models.ForeignKey(needed_action, on_delete=models.CASCADE, null=True, blank=True) Hard_Copy_Type = models.ForeignKey(Hard_Copy_Type, on_delete=models.CASCADE, null=True, blank=True) Request_Status = models.ForeignKey(Request_Status, on_delete=models.CASCADE, null=True, blank=True) -
When I start gounicorn.services, I get error 200/CHDIR. How can it be corrected?
gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root WorkingDirectory=/var/www/botproject/ ExecStart=gunicorn --workers 5 --bind unix:/run/gunicorn.sock botproject.wsgi:application [Install] WantedBy=multi-user.target /var/www/botproject/ - project folder systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: disabled) Active: failed (Result: exit-code) since Sat 2022-07-09 21:28:04 UTC; 3s ago Process: 83314 ExecStart=/usr/local/bin/gunicorn --workers 5 --bind unix:/run/gunicorn.sock botproject.wsgi:application > Main PID: 83314 (code=exited, status=200/CHDIR) Jul 09 21:28:04 server.domain.com systemd[1]: Started gunicorn daemon. Jul 09 21:28:04 server.domain.com systemd[1]: gunicorn.service: Main process exited, code=exited, status=200/CHDIR Jul 09 21:28:04 server.domain.com systemd[1]: gunicorn.service: Failed with result 'exit-code'. I can't figure out what is causing the 200/CHDIR error -
Reverse for 'category_site' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<category>[-a-zA-Z0-9_]+)\\Z']
Im trying to make url and content of currently displayed product category dynamic, with using one 'category.html' template, but I just keep getting this error urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', display_records, name="display_records"), path('about/', about_site, name="about_site"), path('product/<int:id>', product_site, name="product_site"), path('all_products/', all_products_site, name="all_products_site"), path('<slug:category>', category_site, name="category_site"),]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py def category_site(request, category): category_filter = (Q(category__icontains=category)) results = Farfocel.objects.filter(category_filter) return render(request, 'category.html', {'products': results}) product.html <ul class="breadcrumbs"> <li class="breadcrumbs__item"> <a href="{% url 'display_records' %}" class="breadcrumbs__link">Home</a> </li> <li class="breadcrumbs__item"> <a href="{% url 'all_products_site' %}" class="breadcrumbs__link">Products</a> </li> <li class="breadcrumbs__item"> <a href="{% url 'category_site' product.category %}" class="breadcrumbs__link">{{ product.category }}</a> </li> <li class="breadcrumbs__item"> <a href="" class="breadcrumbs__link breadcrumbs__link--active">{{ product }}</a> </li> Honestly I tried everything I could find and I still keep failing. -
Django widget for ManyToManyField
I'm new to Django. I have a model Course with a ManyToManyField to another model Person (representing the teachers of the course). In my views.py, I have the class CreateCourse(CreateView) for creating new instances of courses. The standard widget for the ManyToManyField does not work for me, because in principle there will be too many people. What is the best way to solve the problem, for example, how to create a text input from which I can insert the surname and getting the corresponding person? Thanks in advance! -
Django DRF How to force login on swagger
I'm using Django Rest Framework in a project with swagger for documentation. Swagger UI can be accessed by everyone who knows its URL. Is that possible to add an authentication method so only people with the right access can see and read swagger docs? on urls.py schema_view = get_schema_view( openapi.Info( title="API Docs", default_version='v1', description="beautiful and long text", license=openapi.License(name="BSD License"), ), public=True, permission_classes=[permissions.AllowAny], ) ... urlpatterns = [ url( r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui' ), url( r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc' ), ] on settings.py SWAGGER_SETTINGS = { 'SHOW_REQUEST_HEADERS': True, 'SECURITY_DEFINITIONS': { 'Bearer': { 'type': 'apiKey', 'name': 'Authorization', 'in': 'header', }, 'basic': { 'type': 'basic' } }, 'USE_SESSION_AUTH': True, 'JSON_EDITOR': True, 'SUPPORTED_SUBMIT_METHODS': [ 'get', 'post', 'put', 'delete', 'patch' ], } -
How do i do the summation of two dictionary with aggregate in django , and show it in HTML?
i am new to django , would u experts pls kindly help me.. so i have two modules, and in CBV's get_context_data they both return total sum, now I want to add both the totals and display it on my HTML page, I honestly tried many things but I am always getting an error. here is my views.py def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) today = datetime.datetime.now() # Order.objects.filter(created_at__year=today.year, created_at__month=today.month) context['expense1'] = Tracker.objects.filter(user=self.request.user) context['Total1'] =(Body.objects.filter(user=self.request.user, pub_date__year=today.year, pub_date__month=today.month).aggregate(total=Sum(F('price') * F('quantity'))) , Sport.objects.filter(user=self.request.user, pub_date__year=today.year, pub_date__month=today.month).aggregate(total=Sum(F('price') * F('quantity')))) return context so what I want is , total of body + total of sports , which is being asgn to the context "total1" ,and then I want to show it in HTML my HTML file this is how I am displaying the total, Total: {{Total1}} -
How to sort the records in the table for the month for each doctor (DJANGO)
There are two tables class Doctors(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL") content = models.TextField(blank=True) photo = models.ImageField(upload_to="photos/%Y/%m/%d") time_create = models.DateTimeField(auto_now_add=True) time_update = models.DateTimeField(auto_now=True) spec = models.ForeignKey('Speciality', on_delete=models.PROTECT, null=True) class Appointment(models.Model): class Meta: unique_together = ('title', 'date', 'timeslot') TIMESLOT_LIST = ( (0, '09:00 - 09:30'), (1, '10:00 - 10:30'), (2, '11:00 - 11:30'), (3, '12:00 - 12:30'), (4, '13:00 – 13:30'), (5, '14:00 – 14:30'), (6, '15:00 – 15:30'), (7, '16:00 – 16:30'), (8, '17:00 – 17:30'), ) title = models.ForeignKey('Doctors', on_delete=models.CASCADE) date = models.DateField() timeslot = models.IntegerField(choices=TIMESLOT_LIST) username = models.ForeignKey(User, max_length=60, on_delete=models.CASCADE) complaints = models.CharField(max_length=500) phone = models.CharField(max_length=30) When you make an appointment with a doctor, an entry is added to the Appointment table, I need to find out how many entries for each doctor for a month and for all time. -
Detail view is not displaying content of models
i'm new to Django, so please bear with me. My detail View in Django, isn't successfully displaying the content selected from the listviews. The following is my code. Model: from django.db import models from django.contrib.auth.models import User # Create your models here. class Post_Model(models.Model): Title = models.CharField(max_length=50) Author = models.ForeignKey(User, on_delete=models.CASCADE) Body = models.TextField() def __str__(Self): return Self.Title + ' | ' + str(Self.Author) urls: from django.urls import path from .views import Article_details, Home_page urlpatterns = [ path('', Home_page.as_view(), name="Home"), path('Article/<int:pk>/', Article_details.as_view(), name="Article"), Views: from django.shortcuts import render from django.views.generic import ListView, DetailView from . models import Post_Model class Home_page(ListView): model = Post_Model template_name = 'June11App/Home.html' class Article_details(DetailView): model = Post_Model template_name = 'June11App/Article.html' HTML LIST VIEW: <h1>Home Page</h1> <ul> {% for Post in object_list %} <li> <a href="{% url 'Article' Post.pk %}"> {{Post.Title}} </a> - {{Post.Author}}<br> {{Post.Body}} </li> <br> {% endfor %} </ul> HTML DETAIL VIEW: <h1>Article Page</h1><br> {{Post.Author}} {{Post.Body}} I hope my query made sense. I don't receive any error on myside, its just not working as it should. -
Django session variables not being created on post
I have a weird problem, I have been asked to modify a Django form to include an address (simple I thought), the original html form collects the data, name, contact, etc and then the views.py gets the session variables using sender_name = request.POST.get('sender_name', ''), etc. The sender_address which is a textarea on the HTML form is not included in the dictionary. I can see all the other session variables. The weird thing is if i change one of the original session variables in the HTML form, example sender_name to sender_name1, it too also stops working and disappears from the dictionary. I’m new to Django, slowly getting my head around it, is there a way in django to protect the session variables or am I completely missing something. The form data is not being stored in a dB its being fired off in a email. There isn’t any forms.py associated with the view either. I’ve checked all the MIDDLWWARE entries just in case too. Ive googled the problem but only find stuff on sessions which is not useful. Thank you. -
django - save list of base 64 images to database
i have a list of base64 images that i send from a react panel. images list look like below: [ "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkG", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAeAAAADkCAY" ] Note: i remove most of the charachters because each index charachters is more than 2000 and it's just a example of what i have. so i want to save them in django model. my field for saving this list of images is this: ArrayField(base_field=models.ImageField(upload_to='hotel_images/')) so how should i convert list of base64 images to real images and save them to this ArrayField? or do you have a better way for saving this base64 images list? Note: i convert images to base64 in react panel by code below: const FR = new FileReader(); FR.addEventListener("load", function () { image = FR.result; }) FR.readAsDataURL(img); and i do this because i have a json that contains other fields like name and description so when i want to send this json with request body i should use JSON.stringify() for that and when i use JSON.stringify(), images field is turn to empty array and i have to convert images to base64. so if you have a solution for this problem, that could help too! Final Note: my database is postgreSQL. -
How do I limit requests per user in Django rest framework using throttling?
I'm working on a Quiz app and one question gets uploaded every week in a month (4 ques/month). Now I want to make sure that a logged in user can only attempt the question twice per week and not more than that. How can I do this using throttling or any other way? Here's my Quiz model: Days = ( ("Mon", "Monday"), ("Tue", "Tuesday"), ("Wed", "Wednesday"), ("Thu", "Thursday"), ("Fri", "Friday"), ("Sat", "Saturday"), ("Sun", "Sunday") ) class QuizDetail(models.Model): name = models.CharField(max_lenght=255, blank=False, null=False) start_date = models.DateTimeField() end_date = models.DateTimeField() publisehd_week_day = models.CharField(max_length=255, choices=Days) The published_week_day can change every month, so basically one month it can be Tuesday and next month it can be Thursday. Note: If in a month published_week_day is Tuesday and a user attempts last week's quizz on Monday and exhausts his two attempts then on Tuesday he should be able to attempt as it will be a fresh quizz. Thanks in advance. -
is there a way to access a single element of many-to-many relation in django without using for loop?
I'm really new to using Django and I've been stuck on this for weeks. I've got a list of voters which is named thumbs under each candidate, and it is a many-to-many field which is populated once a user votes. How can I check if a user is already in thumbs (i.e. has already voted) so that I display components differently based on this? Here is what I've got: myTemplateFile.html {% if request.user == candidate.thumbs.all %} <small style="color:grey; font-size:10px;">you've already voted here</small> <a id="Thumbs" class="btn btn-success btn-sm thumbaction{{poll.id}}{{candidate.id}}" value="thumbsup" data-toggle="tooltip" title="upVote: I like this candidate" role="button"> <svg id="{{poll.id}}{{candidate.id}}thumbsup" width="1em" height="1em" viewBox="0 0 16 16" class="up bi bi-hand-thumbs-up d-none" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd"/> </svg><span id="i_like_this"><span class="" style="color:white; font-size:xx-small" id="{{poll.id}}{{candidate.id}}up">{{candidate.thumbsup}} </span></span><font class="" style="color:white; font-size:xx-small;" id="{{poll.id}}{{candidate.id}}approve">&nbsp;approved</font> </a> <a id="Thumbs" class="btn btn-danger btn-sm thumbaction{{poll.id}}{{candidate.id}}" value="thumbsdown" data-toggle="tooltip" title="downVote: I dont like this candidate" role="button"> <svg id="{{poll.id}}{{candidate.id}}thumbsdown" width="1em" height="1em" viewBox="0 0 16 16" class="down bi bi-hand-thumbs-down d-none" fill="currentColor" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd"/> </svg> <span class="" style="color:white; font-size:xx-small;" id="{{poll.id}}{{candidate.id}}down">{{candidate.thumbsdown}} </span><font style="color:white; font-size:xx-small;" id="{{poll.id}}{{candidate.id}}reject">&nbsp;rejected</font> </a> {% else %} <a id="Thumbs" class="btn btn-success btn-sm thumbaction{{poll.id}}{{candidate.id}}" value="thumbsup" data-toggle="tooltip" title="upVote: I like this candidate" role="button"> <svg id="{{poll.id}}{{candidate.id}}thumbsup" width="1em" height="1em" viewBox="0 0 16 16" class="up bi bi-hand-thumbs-up" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd"/> </svg><span style="color:white; font-size:xx-small;" id="i_like_this"><span … -
from.import views ImportError: attempted relative import with no known parent package
from django.urls import re_path as url from . import views urlpatterns=[ url('home/',views.home,name="home"), url('marketing_courses/',views.marketingCourses,name="Marketing courses"), url('privacy_policy/',views.privacyPolicy,name="Privacy policy"), url('blog/',views.blog,name="blog"), ] -
Uncaught TypeError: Cannot read properties of undefined (reading 'amount')
I converted the Django models into a JSON data object and accessed it in Javascript. However, I cannot access a field from the object and assign it to a text box. The JSON object that is being returned: [{"model": "inventory.inventory","pk": 1, "fields": {"product": "nice", "title": "Asus", "amount": 56000}}, {"model": "inventory.inventory", "pk": 2, "fields": {"product": "nice", "title": "Lenovo", "amount": 55000}}] The javascript code that I am using: <html>....{{ data|json_script:"hello-data" }}.... <script type="text/javascript"> const data = JSON.parse(document.getElementById('hello-data').textContent); document.getElementById('id_line_one').onchange = function(){ var line_one=document.getElementById('id_line_one').value; var id=line_one-1; document.getElementById('id_line_one_unit_price').value = data[id].fields.amount; }; </script>....</html> The dropdown value returns its primary key, i.e., product_number and basically I want to fetch the amount of the product associated with that product_number. As the objects are stored from 0(?) in JSON, I thought the logic of my code was correct but I am not an expert so I am pretty sure I am making some silly mistake here. How can I return the amount of the object in the unit price text box when the title is selected in the dropdown list? Thanks! views.py @login_required def add_invoice(request): form = InvoiceForm(request.POST or None) data = serializers.serialize("json", Inventory.objects.all()) total_invoices = Invoice.objects.count() queryset = Invoice.objects.order_by('-invoice_date')[:6] if form.is_valid(): form.save() messages.success(request, 'Successfully Saved') return redirect('/invoice/list_invoice') context … -
Creating a SET of strings in Redis but returning integers
Noticing that when I try to add a list of strings to my redis_instance as members of a SET when I try to retrieve the elements in this SET I only see integers. From how I read the documentation if I were to for example have a set containing: 'Fred', 'Emmanuel', 'Marcus Aurelius' If I were to return the entire SET, assuming the key for the set is 'newSet' by running this command: SMEMBERS newSet I should see a list of all members of said state, instead this is the response I get: 1) "32" 2) "39" 3) "44" 4) "65" 5) "69" 6) "70" 7) "77" 8) "91" 9) "93" 10) "97" 11) "99" 12) "100" 13) "101" 14) "105" 15) "108" 16) "109" 17) "110" 18) "114" 19) "115" 20) "117" This is the code I am using to create and append to said set: @api_view(['GET', 'POST']) def manage_items(request, *args, **kwargs): ... elif request.method == 'POST': new_users = request.body for i in range(0, len(new_users)): redis_instance.sadd('pairs', str(new_users[i])) response = { 'msg': f'set contains: {new_users}' } return Response(response, 201) Any ideas what's going on?