Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can I change the user and the value of product(Model) after wallet transaction
here is my model.py, Where Customer is the one to make orders and purchase Products. class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=25, null=True) phone = models.CharField(max_length=12, null=True) def __str__(self): return self.name class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) coinid = models.CharField(max_length=255, null=True) digit = models.CharField(max_length=18, null=True) ctp = models.FloatField(max_length=100, null=True) transection_id = models.IntegerField(null=True, default=0) slug = models.SlugField(max_length=250, null=True, blank=True) date_created = models.DateField(auto_now_add=True, null=True) def __str__(self): return self.coinid def get_absolute_url(self): return reverse("core:detail", kwargs={ 'slug': self.coinid }) class Balance(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) balance = models.IntegerField(default=0) def __str__(self): return self.user.username in views.py, Here I want to replace the user(Product.user) of the product by sender sending amount from wallet def buy_c(request, ok): ctp_val = Product.objects.get(id=ok) msg = "Enter Details" if request.method == "POST": try: username = request.POST["username"] amount = request.POST["amount"] senderUser = User.objects.get(username=request.user.username) receiverrUser = User.objects.get(username=username) sender = Balance.objects.get(user=senderUser) receiverr = Balance.objects.get(user=receiverrUser) sender.balance = sender.balance - float(amount) receiverr.balance = receiverr.balance + float(amount) if senderUser == receiverrUser: return Exception.with_traceback() else: sender.save() receiverr.save() msg = "Transaction Success" return redirect("/user") except Exception as e: print(e) msg = "Transaction Failure, Please check and try again" context = {"coin": ctp_val, "msg":msg} return render(request, 'coinwall.html', context) here is my template coinwall.html <tr> <th>username</th> <th>Coin Id</th> <th>current … -
2 different references from the same object to two different objects from the same class - DJANGO database
I want to have a match object with two team references. I.E(old json database example): I would like to easeliy be able to access each team and possibly swap side. That's why I want to use Django example 2, as then I can reference each team from the Match Object. But example gives an error about each reference duplicating each other... { "dateTime": "", "matchID":"0fb86bcf-c700-4429-b5a9-558ca9b95a03", "team1ID":"e372b7f4-008f-4503-beee-1d6756361fea", "team2ID":"802b4705-d812-4a88-9246-b14bd18938d8", "format":3, "division":"Relegation", "league":leagueRef, "game":leagueRef, } Django example 1: class Match(models.Model): ... team = models.ManyToManyField( Team, on_delete=models.CASCADE, ) Django example 2: class Match(models.Model): ... team1 = models.OneToOneField( Team, on_delete=models.CASCADE, ) team2 = models.OneToOneField( Team, on_delete=models.CASCADE, ) -
Django Exception Type: RelatedObjectDoesNotExist Exception Value: User has no shopper
I am getting the following error: Exception Type: RelatedObjectDoesNotExist ; Exception Value: User has no shopper. below is my models.py file: Below are the given models for this project from django.db import models from django.contrib.auth.models import User class Shopper(models.Model): email = models.CharField(max_length=100,null=True) user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=100,null=True) def __str__(self): return self.name class Item(models.Model): itemName = models.CharField(max_length=100,null=True) itemPrice = models.FloatField() img = models.ImageField(null=True,blank=True,upload_to='static\images') def __str__(self): return self.itemName class TotalOrder(models.Model): shopper = models.ForeignKey(Shopper, on_delete=models.SET_NULL,blank=True,null=True) dateOfOrder = models.DateTimeField(auto_now_add=True) isDone = models.BooleanField(default=False,null=True,blank=False) orderId = models.CharField(max_length=100,null=True) def __str__(self): return str(self.id) class ItemToOrder(models.Model): dateOfAdded = models.DateTimeField(auto_now_add=True) item = models.ForeignKey(Item,on_delete=models.SET_NULL,blank=True,null=True) order = models.ForeignKey(TotalOrder,on_delete=models.SET_NULL,blank=True,null=True) quantity = models.IntegerField(default=0,null=True,blank=True) And here is where I am trying to access this in the view.py file: def cart(request): if request.user.is_authenticated: shopper = request.user.shopper order, created = TotalOrder.objects.get_or_create(shopper = shopper,isDone=False) items = order.itemtoorder_set.all() else: items = [] context = {'items':items} return render(request, 'store/cart.html', context) Thank you so much for the help! -
Download videos using django didn't work with Iphone
Why download videos from django doesn't work with Iphone but it's work with android and windows my view def download_videos(request, pk): video = Video.objects.get(pk=pk) response = HttpResponse( video.video, content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="fromCubeLinda.mp4"' return response The html template <a id="adown" href="{% url 'video:video_download' video.pk %}" target="_blank">Download</a> -
I get an error when I try to deploy to Heroku with simpleJWT version 4.6.0
When I install djangorestframework-simplejwt 4.6.0 in Django and try to deploy it to Heroku, I get the following error. remote: Downloading djangorestframework-3.12.2-py3-none-any.whl (957 kB) remote: ERROR: Could not find a version that satisfies the requirement djangorestframework-simplejwt==4.6.0 (from -r /tmp/build_5927f5b0/requirements.txt (line 19)) (from versions: 1.0, 1.1, 1.2, 1.2.1, 1.3, 1.4, 1.5.1, 2.0.0, 2.0.1, 2.0.2, 2.0.3, 2.0.4, 2.0.5, 2.1, 3.0, 3.1, 3.2, 3.2.1, 3.2.2, 3.2.3, 3.3, 4.0.0, 4.1.0, 4.1.1, 4.1.2, 4.1.3, 4.1.4, 4.1.5, 4.2.0, 4.3.0, 4.4.0) remote: ERROR: No matching distribution found for djangorestframework-simplejwt==4.6.0 (from -r /tmp/build_5927f5b0/requirements.txt (line 19)) I tried installing and deploying 4.4.0 to see if I could find 4.6.0, and I was able to deploy it, but when I tried to start and access it with python manage.py runserver, the 'str' object has no attribute ' decode'. Why does this happen? I would appreciate it if you could tell me how to feed them. -
Django ModelForm is not Displaying Customizations in forms.py
I have created a form that allows users to create a request for a ride that saves to a table in my database. The form works and can save data. Here is my code: forms.py: from django import forms from .models import Post import datetime from django.utils.translation import gettext_lazy as _ DESTINATION_LOCATIONS = [ ('RedMed','Red Med'), ('OOSM','Oxford Bone Doctor'), ('BSMH','Baptist Street Memorial Hosptial') ] class RiderRequestForm(forms.ModelForm): riderLocation = forms.CharField(label='Pickup Location') destination = forms.ChoiceField(widget=forms.Select(choices=DESTINATION_LOCATIONS)) date = forms.DateTimeField(initial= datetime.date.today) addSupport = forms.CharField(max_length=200, required=False) class Meta: model = Post fields = ['riderLocation', 'destination','date','addSupport'] labels = { "riderLocation": _('Pickup Address'), "destination": _("Select Destination: "), "date": _("Enter Time to be Picked Up"), "addSupport": _("List any additional things we should know: "), } models.py: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class Post(models.Model): riderLocation = models.CharField(max_length=200) destination = models.CharField(max_length=200) date = models.DateTimeField() date_created = models.DateTimeField(default=timezone.now) rider = models.ForeignKey(User, on_delete=models.CASCADE) addSupport = models.CharField(max_length=200, null=True) def __str__(self): return self.destination def get_absolute_url(self): return reverse('request-viewDetail', kwargs={'pk': self.pk}) The HTML for the form post_form.html: {% extends 'homepage/homepageBase.html' %} {% load crispy_forms_tags %} {% block content %} <div> <form method="POST"> <div class="registerField"> {% csrf_token %} <fieldset class='form-group'> <legend … -
Paginating resulted filtered from Django form
I am trying to paginate resulted filtered from Django form GET request. However, when I click the second page it redirects me to the form page. I searched for similar questions and tried several approaches but somehow this still does not work. Below is the screenshots of my code. Any help will be appreciated. view.py def get_pictures_by_filters(request): if request.method == 'GET': form = GetPictureForm(request.GET) if form.is_valid(): name = form.get_name() problem = form.get_problem() language = form.get_language() pictures = Picture.objects.filter(relatedGame=name, language__iregex=r'.*' + language) if problem: for p in problem: pictures = pictures.filter(problem__contains=p) paginator = Paginator(pictures, 1) page = request.GET.get('page') try: pictures = paginator.page(page) except PageNotAnInteger: pictures = paginator.page(1) except EmptyPage: pictures = paginator.page(paginator.num_pages) context = {'list_pictures': pictures, 'page_obj': pictures} return render(request, 'picture/show_pictures_by_filter.html', context) form = GetPictureForm() context = { 'form': form } return render(request, 'picture/get_pictures_by_filter.html', context) urls.py path('pictures/filter', views.get_pictures_by_filters, name='get-pictures'), forms.py class GetPictureForm(forms.Form): def __init__(self, *args, **kwargs): super(GetPictureForm, self).__init__(*args, **kwargs) games = [(g.name, g.name) for g in Game.objects.all().order_by('-id')] problems = [(p.name, p.name) for p in Problem.objects.all()] self.fields['项目名称'] = forms.CharField(required=True, widget=forms.Select(choices=games)) self.fields['语种'] = forms.CharField(required=False) self.fields['问题'] = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple, choices=problems) def get_name(self): data = self.cleaned_data['项目名称'] return data def get_problem(self): data = self.cleaned_data['问题'] return data def get_language(self): data = self.cleaned_data['语种'] return data -
Best Django design with constant updating data
I’m making a website with Django framework with MySQL for database to display some data (e.g. daily stock prices for many stocks). Everyday, I would like to refresh all the data in the database to the latest data. There’s a lot data so I want to replace the entire database instead of inserting new entries. Is there an elegant way of achieving this? Is this kind of operation supported by relational databases like MySQL. Thanks! -
Setting cookies in django without a response
I want to be able to set a cookie on my django site when somebody creates an account. This is currently my view: from django import forms from django.shortcuts import render, redirect from django.http import HttpResponseRedirect from django.contrib.auth.models import User from django.core.mail import send_mail CARRIER_CHOICES =( ('@txt.freedommobile.ca', 'Freedom Mobile'), ('@txt.luckymobile.ca', 'Lucky Mobile'), ('none', 'None'), ) class RegisterForm (forms.Form): username = forms.CharField() password = forms.CharField() check_password = forms.CharField() email = forms.EmailField() phone = forms.IntegerField(required=False) carrier = forms.ChoiceField(choices=CARRIER_CHOICES, required=False) def register (request): form_error = 'none' if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] check_password = form.cleaned_data['check_password'] email = form.cleaned_data['email'] phone = form.cleaned_data['phone'] carrier = form.cleaned_data['carrier'] phone = str(phone) if password == check_password: phone_email = phone + carrier user = User.objects.create_user(username, email, password) user.is_staff = False user.is_active = True user.is_superuser = False send_mail( 'TachlisGeredt.com Account', 'Congrats! You have succesfully created an account with TachlisGeredt.com!', 'contact@tachlisgeredt.com', [email], fail_silently=False, ) return redirect ("/register/success") else: form = RegisterForm(request.POST) return render (request, 'register.html', {'form':form}) I'ver tried making cookies a million different ways but its really confusing. They all seem to need me to make a variable called 'response', do 'response.set_cookie' or whatever the command is, and then do 'return response'. … -
React-Django: How to send different functional components (React) to Django Views?
So I am new to React and I can currently create different functional components when I use npx create-react-app appname but if I want to "package" these files and send them to my Django's view page, what is the best way to do this? I am having some trouble with webpack configuring everything in the methods I've attempted. I am trying to create a web app. Thank you. -
DJANGO not returning context in my html template
why this context not rendering in my html template: return render(request, 'index.html',{'message_name':name}) This context will print user name after successful submit my contact form. here is my code: views.py @csrf_exempt def home_view(request,*args,**kwargs): name = None if request.method == "POST": contact_form = ContactForm(request.POST) if contact_form.is_valid(): name = request.POST['name'] email = request.POST['email'] subject = request.POST['subject'] message = request.POST['message'] save_details = Contact(name=name,email=email,subject=subject,message=message) save_details.save() return HttpResponseRedirect("http://127.0.0.1:8000/") return render(request, 'index.html',{'message_name':name}) else: print("not submitted") else: contact_form = ContactForm() return render(request, 'index.html',{'form':contact_form}) app urls.py from django.urls import path from pages import views urlpatterns = [ path('', views.home_view, name="home"), ] root urls.py from django.contrib import admin from django.urls import path,include from pages import urls urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.urls')), ] index.html <!--===== CONTACT =====--> <section class="contact section" id="contact"> <h2 class="section-title">Contact</h2> {% if message_name %} <div class="centerTest"> <h1> Thanks {{ message_name }} for your message. We will get back to you very soon</h1> </div> {% else %} <div class="contact__container bd-grid"> <form action="#contact" method = "POST" class="contact__form"> {% for error in form.non_field_errors %} <div class="alert alert-danger" role="alert"> {{ error }} </div> {% endfor %} <label>Name:</label> {{ form.errors.name }} <input type="text" placeholder="Name" name="name" class="contact__input" {% if form.is_bound %}value="{{ form.name.value }} {% endif %}"> <label>Email:</label> {{ form.errors.email }} <input type="mail" … -
ModelForm in Django not showing
I'm trying to display a basic form in django but does not render the form once I run the server, I would appreciate if you could help me with these, here my code. models.py STATUS_OPTIONS =( ('OP', 'OPEN'), ('CL', 'CLOSED') ) class Employee(models.Model): id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField(max_length=200) status = models.CharField(max_length=50, choices=STATUS_OPTIONS) password = models.CharField(max_length=100) def __str__(self): return self.first_name forms.py from django import forms from .models import Employee class EmployeeForm(forms.Form): class Meta: model = Employee fields = "__all__" urls.py from django.urls import include, path from . import views urlpatterns = [ path('', views.create_employee), ] view.py from .forms import EmployeeForm # Create your views here. def create_employee(request): form = EmployeeForm() return render(request, 'employee/create_employee.html', {'form':form}) create_employee.html <h1>Formu</h1> <form action="" method='POST'> {{form.as_p}} <input type="submit"> </form> When I run the program the only thing rendered is the tag, any idea? -
ValidationError occured only on heroku app but everything is fine in localhost
I have a problem when in my project everything works fine on localhost, but on the deployed app I keep getting this weird error: ['“false” value must be either True or False.'] This occures when I'm changing a checkbox value here: // edit preferences $(document).on("change", "#form_preferences input,select", function(e){ if ($(e.target).is("select")){ value = $(this).val(); } else { value = $(e.target).prop("checked"); } $.ajax({ url: '/edit_preferences', type: 'POST', data: { element_changed: this.id, value: value }, success: function(data){ // do something when preferences are changed } }) }); It also happans on other places on my website but this error only occures on Preferences model and only on heroku. models.py class Preferences(models.Model): user = models.OneToOneField(User, models.CASCADE, default=0) is_paypal_editable = models.BooleanField(default=False) default_month = models.BooleanField(default=True) # True for lastmonth else all start_month_day = models.IntegerField(default=16) # month will end in this day minus 1 sort_by_date = models.BooleanField(default=False) # True for sort by date else don't sort def __str__(self): s = "user = " + str(self.user) + " | " s += "is_paypal_editable = " + str(self.is_paypal_editable) + " | " s += "default_month = " + str(self.default_month) + " | " s += "start_month_day = " + str(self.start_month_day) + " | " s += "sort_by_date = " … -
Django question: Approval Form: Should I use DetailView of UpdateView?
A newbie question - I am stuck in dilemma between using DetailView or UpdateView in Django The scenario: A "request" object (e.g. requestor, date of request, status, etc.) is sent to an "approver" for an approval. The approver can either reject or approve the request, as well as enter their comment in a comment field. The form should display all the fields from the request object, but the approver should only be able to update the comment field and then click either on "Approve" or "Decline" buttons in a form (so POST method is required) Based on my current knowledge, I think I can hack the problem but I am looking for a "proper way" to design this type of requirement. I don't want to use readonly or disabled attributes approach, because I've tried it and fields can still be changed / navigated to on the screen - even though they won't be saved in the database. -
Receiving error 502 BAD CONNECTION nginx when deploying django app on Google app engine
Ive been trying to my django website but I've been having the same 502 BAD CONNECTION nginx error every time and I'm not sure how to troubleshoot it. When I run the program using py.manager runserver, it works perfectly fine, but but I only receive an error once I run gcloud app deploy, looking at the logs I haven't received any errors, just one warning stating that Container called exit(1). I've tried one solution from the Google's website: https://cloud.google.com/endpoints/docs/openapi/troubleshoot-response-errors and I added resources: memory_gb: 4 to my app.yaml file and I still end up with an error. I am not sure this is of much help my app.yaml currently looks like this: runtime: python39 handlers: # This configures Google App Engine to serve the files in the app's static # directory. - url: /static static_dir: static/ # This handler routes all requests not caught above to your main app. It is # required when static routes are defined, but can be omitted (along with # the entire handlers section) when there are no static files defined. - url: /.* script: auto resources: memory_gb: 4 And my gcloudignore looks like this: # This file specifies files that are *not* uploaded to … -
django templates, alpine.js - send tags to form
I have input that tokenizes words into tags built with alpine.js and tailwindcss. screenshot of the input I have 3 django forms: title body tags I want to send tags from words tokenizer input to "tags" form. How can i approach it? I'm struggling with alpine.js but i really want to have tokenized input functionality. django template, create_post.html: {% extends 'base.html' %} {% block title %}Create post{% endblock title %} {% block content %} <form method="post"> {% csrf_token %} <input type="text" name="title"> <input type="text" name="body"> <!-- send this to "tags" form--> <div x-data @tags-update="console.log('tags updated', $event.detail.tags)" data-tags='["aaa","bbb"]' class="max-w-lg m-6"> <div x-data="tagSelect()" x-init="init('parentEl')" @click.away="clearSearch()" @keydown.escape="clearSearch()"> <div class="relative" @keydown.enter.prevent="addTag(textInput)"> <input x-model="textInput" x-ref="textInput" @input="search($event.target.value)" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" placeholder="Enter some tags"> <div :class="[open ? 'block' : 'hidden']"> <div class="absolute z-40 left-0 mt-2 w-full"> <div class="py-1 text-sm bg-white rounded shadow-lg border border-gray-300"> <a @click.prevent="addTag(textInput)" class="block py-1 px-5 cursor-pointer hover:bg-indigo-600 hover:text-white">Add tag "<span class="font-semibold" x-text="textInput"></span>"</a> </div> </div> </div> <!-- selections --> <template x-for="(tag, index) in tags"> <div class="bg-indigo-100 inline-flex items-center text-sm rounded mt-2 mr-1"> <span class="ml-2 mr-1 leading-relaxed truncate max-w-xs" x-text="tag"></span> <button @click.prevent="removeTag(index)" class="w-6 h-8 inline-block align-middle text-gray-500 hover:text-gray-600 focus:outline-none"> <svg class="w-6 h-6 fill-current mx-auto" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 … -
'super' object has no attribute 'objects' Python Django
you need to get the filter using the get_related_filter class method views modelPath = 'Money.models' app_model = importlib.import_module(modelPath) cls = getattr(app_model, 'Money') related_result = cls().get_related_filter(search_query='search_query') models.py class Money(models.Model): money = models.DecimalField(max_digits=19, blank=True, default=0, decimal_places=2) def get_related_filter(self, **kwargs): results = super(Money, self).objects.filter(Q(money__icontains=kwargs['search_query'])) return results def __str__(self): return self.money why gives 'super' object has no attribute 'objects' Python Django, and does not return filter -
JWT Authentication with Django REST Framework using otp for getting api tokens
I have a custom user login where, I use mobile OTP verification and not at all using any django user model through out my project.need to authenticate jwt django restframework by otp. please help me with this. thanks -
clean_<fieldname>() won't raise ValidationError; ManyToManyField
In attempting to control how many tags a User can apply to any one question, I have created a validate_tags method to the QuestionForm for this edge case. Upon testing for this, the form accepts the list of tags exceeding the limit of 4 tags; it should be raising a ValidationError. The tags end up in the form's cleaned data. What is causing the ValidationError to not be raised? class Question(models.Model): title = models.CharField(unique=True, max_length=100) body = models.TextField() dated = models.DateField(auto_now_add=True) likes = models.IntegerField(default=0) user_account = models.ForeignKey( 'users.UserAccount', on_delete=models.SET_NULL, null=True, blank=True, related_name="questions" ) tags = models.ManyToManyField(Tag, related_name='questions') class Meta: ordering = ['dated'] class QuestionForm(forms.ModelForm): tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all()) def validate_tags(self): tags = self.cleaned_data['tags'] if tags > 4: raise ValidationError( "Only attach a maximum of 4 tags.", code="tags_limit" ) return tags def clean(self): cleaned_data = super().clean() title = cleaned_data['title'] tags = cleaned_data['tags'] for t in tags: try: self.Meta.model.objects.get( title__exact=title, tags__name__exact=t ) except self.Meta.model.DoesNotExist: continue else: message = "A question like this already exists." message += "Reformat your question and/or change your tags." self.add_error("body", ValidationError( message, code="invalid") ) class Meta: model = Question fields = ['title', 'body', 'tags'] error_messages = { 'name': { 'required': "Question must be provided.", 'unique': "Question already exists. Reformat … -
Django da web sayfasında veri gelmeme sorunu
Merhabalar Django da web sayfayı yapmaya çalışırken web sayfasındaki verileri göstermiyor. Baya araştırdım lakin bir sonca varamadım. Bilen birilerileri yardım edebilirse çok sevinirim -
Import Exceptions When I Update Pycharm to 2020.3.3
I was working on a bot Project in python on Pycharm. Then, I decided to Update Pycharm to 2020.3.3 version while I was installing Pycharm 2020.3.3 it asked me to uninstall the old version I accept when I finish I open the Same Project it Shows import Exceptions. I don't know if this happened because of wrong working directory path I think it the problem is something wrong with Paths but I don't know the Old working directory Path I know the path of the python file that I was working on it and the path of the Python.exe.. the path of the code in my computer is in : C:/Users/Microsoft/PycharmProjects/untitled4/conversationbot.py python.exe path in my computer is in : C:\Users\Microsoft\AppData\Local\Programs\Python\Python38\python.exe This is the Exceptions: C:\Users\Microsoft\AppData\Local\Programs\Python\Python38\python.exe C:/Users/Microsoft/PycharmProjects/untitled4/conversationbot.py Traceback (most recent call last): File "C:/Users/Microsoft/PycharmProjects/untitled4/conversationbot.py", line 4, in from telegram.ext import(Updater,CommandHandler,MessageHandler,Filters,ConversationHandler,CallbackContext) File "C:\Users\Microsoft\AppData\Local\Programs\Python\Python38\lib\site-packages\telegram\ext_init_.py", line 21, in from .basepersistence import BasePersistence File "C:\Users\Microsoft\AppData\Local\Programs\Python\Python38\lib\site-packages\telegram\ext\basepersistence.py", line 25, in from telegram import Bot ImportError: cannot import name 'Bot' from 'telegram' (C:\Users\Microsoft\AppData\Local\Programs\Python\Python38\lib\site-packages\telegram_init_.py) this is my code: https://github.com/zieadshabkalieh/bot/blob/main/conversationbot.py Note: There Wasn't Any Exceptions Before I Update Pycharm It was Working Perfectly. -
Django adding eventlistener to a for...loop on template tag
thanks for your time. i'm trying to add a event listener to a list of links created by django template tag. It should take the list of objects with class div.cat-link and add an eventlistener to each one to display the matching id of div.cat-select html <div class="cat"> <div class="cat-links"> {% for t in tags %} <div id="{{t|lower}}" class="cat-link"> <a class="cat" href="{% url 'list_product1' t %}">{{t}}</a> </div> {% endfor %} </div> </div> <div class="cat-list"> {% for t in tags %} <div class="cat-select" id="cat_{{t|lower}}"> {% for p in t.produto_set.all %} <div class="cat-product"> <!--IMAGES--> <div class='img'> <amp-carousel lightbox controls autoplay delay="3000" width="250" height="250" layout="responsive" type="slides"> {% for pic in p.images.all %} <amp-img src="{{ pic.image.url }}" width="250" height="150" layout="responsive" alt="{{ p.nome }}"> </amp-img> {% endfor %} </amp-carousel> </div> <!-- INFOS --> <div class='infos-prod'> <a class='cat-product' href="{% url 'detail_product' p.id %}"> <h3>{{p.nome}} </h3> </a> <a class='cat-product' href="{% url 'detail_product' p.id %}"> R$: {{ p.preco }} </a> </div> </div> {% endfor %} </div> {% endfor %} </div> JavaScript: <script id="cat-script" type="text/javascript" target="amp-script"> function Showing(one) { var v1 = document.getElementById(one); v1.style.display = "flex"; }; function Hiding(one) { var v1 = document.getElementById(one); v1.style.display = "none"; }; function Category() { var v1 = document.getElementsByClassName('cat-link'); for (o in v1) … -
Django on Heroku: KeyError: 'collectstatic'
I'm trying to deploy my simple Django web app on Heroku, but the build fails with the following error: Successfully installed asgiref-3.3.4 dj-database-url-0.5.0 django-3.2 django-heroku-0.3.1 gunicorn-20.1.0 numpy-1.20.2 pillow-8.2.0 psycopg2-2.8.6 pytz-2021.1 sqlparse-0.4.1 torch-1.8.1 torchvision-0.9.1 typing-extensions-3.7.4.3 whitenoise-5.2.0 -----> $ python pytorch_django/manage.py collectstatic --noinput Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 237, in fetch_command app_name = commands[subcommand] KeyError: 'collectstatic' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/tmp/build_6b3954ac/pytorch_django/manage.py", line 22, in <module> main() File "/tmp/build_6b3954ac/pytorch_django/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 244, in fetch_command settings.INSTALLED_APPS File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'project' ! Error while running '$ … -
SQL Query conversion to Django ORM
select l.student_id, SUM(l.sum_result) FROM (SELECT w.student_id, w.subject_id,r.total as sum_result from Student w INNER JOIN (SELECT COUNT(r.id) as total,r.subject_fk_id from Result r GROUP BY r.subject_fk_id) r ON w.subject_id=r.subject_fk_id) l GROUP BY student_id The tables are: Student ------------- -> id(PK) ->student_name ->student_email Subject -------------- -> id(PK) -> Students(Many to Many relationship) -> subject_name Results --------------- ->id (PK) ->subject_fk(FK to subject table) ->date there is one many to many table for student and subject Student_Subject ->id(PK) ->Student_id(FK) ->Subject_id(FK) I want to convert this SQL query to Django ORM I need to retreive the total number of results for a Student. I need to write this query in Django ORM without for loops. Thank you in advance -
how to pass a js value into the django url template tag
''' var c = "url chatloadchannel="+String(channel) fetch('% '+c+' %}') ''' how to pass this js value to the django