Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change visibility on div multiple times with javascript and css?
I have a popup in my app: <div id="modal"></div> let modal = document.getElementById('modal') modal.innerHTML = ` <button class="close-button" onclick="close_modal()">Close</button> ` #modal{ width: 30em; height: 24em; overflow: hidden; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); visibility: hidden; } When I click certain button function is triggered which has modal.classList.add('open-modal') in it. .open-modal{ visibility: visible !important; } close_modal function is: function close_modal(){ modal.classList.add('close-modal') } CSS: .close-modal{ visibility: hidden !important; } It works just fine once(i can open and close popup but when I try to open it second time it doesn't. Why is this happening and how to fix it? -
a music app ,where i was trying to display the album detail once it is newlycreated using reverse...recieving the below mentioned error please assist
Traceback (most recent call last): File "C:\Users\Sanath\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Sanath\anaconda3\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Sanath\anaconda3\lib\site-packages\django\views\generic\base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Sanath\anaconda3\lib\site-packages\django\views\generic\base.py", line 142, in dispatch return handler(request, *args, **kwargs) File "C:\Users\Sanath\anaconda3\lib\site-packages\django\views\generic\edit.py", line 184, in post return super().post(request, *args, **kwargs) File "C:\Users\Sanath\anaconda3\lib\site-packages\django\views\generic\edit.py", line 153, in post return self.form_valid(form) File "C:\Users\Sanath\anaconda3\lib\site-packages\django\views\generic\edit.py", line 136, in form_valid return super().form_valid(form) File "C:\Users\Sanath\anaconda3\lib\site-packages\django\views\generic\edit.py", line 65, in form_valid return HttpResponseRedirect(self.get_success_url()) File "C:\Users\Sanath\anaconda3\lib\site-packages\django\views\generic\edit.py", line 125, in get_success_url url = self.object.get_absolute_url() File "C:\Users\Sanath\Desktop\website\music\models.py", line 12, in get_absolute_url return reverse('music:detail',kwargs = {'pk' : self.pk}) File "C:\Users\Sanath\anaconda3\lib\site-packages\django\urls\base.py", line 88, in reverse return resolver._reverse_with_prefix(view, prefix, *args, **kwargs) File "C:\Users\Sanath\anaconda3\lib\site-packages\django\urls\resolvers.py", line 828, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'detail' with keyword arguments '{'pk': 11}' not found. 1 pattern(s) tried: ['music/(?P<album_id>[0-9]+)/\\Z'] urls.py from django.urls import path from . import views app_name = 'music' urlpatterns = [ #music/ path('', views.index,name = 'index'), #music/71/ path('<int:album_id>/', views.detail,name = 'detail'), path("register/",views.UserFormView.as_view(),name = 'register'), path("album/add/",views.albumcreate.as_view(),name = 'album-add'), #url pattern for the view albumcreate ] models.py from django.db import models from django.urls import reverse # Create your models here. class album(models.Model): #inherit from models.Model artist = models.CharField(max_length=250) #when migrated to db it will … -
django query with manytomany as list
I'm working with django (4.1) and I have a problem with a QuerySet. models.py class Publication(models.Model): title = models.CharField(max_length=30) class Meta: ordering = ['title'] def __str__(self): return self.title class Article(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField(Publication) class Meta: ordering = ['headline'] def __str__(self): return self.headline python manage.py shell >>> from many2many.models import Article, Publication >>> qsA = Article.objects.values("id","headline","publications") >>> qsP = Publication.objects.values("id","title") >>> for a in qsA: ... print(a) ... {'id': 1, 'headline': 'A', 'publications': 1} {'id': 1, 'headline': 'A', 'publications': 2} {'id': 2, 'headline': 'B', 'publications': 3} {'id': 2, 'headline': 'B', 'publications': 4} >>> for a in qsP: ... print(a) ... {'id': 1, 'title': 'tA1'} {'id': 2, 'title': 'tA2'} {'id': 3, 'title': 'tB1'} {'id': 4, 'title': 'tB2'} >>> I'd like to have a QuerySet that returns the "headline" of the Articles, and the list of the "title" of the Publication. Something like {'headline': 'A', 'list_publications': 'tA1 tA2'} {'headline': 'B', 'list_publications': 'tB1 tB2'} -
How to translate the route system in django 1 to django 2,3?
In tutorial the author used an old version of urls.py in urlpatterns and I cannot translate url(r'^image/(?P<width>[0-9]+)x(?P<height>[0-9]+)/$') this into path() Thanks a lot I would like to resolve this issue -
! [remote rejected] main -> main (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/mighty-island-82287.git' error
I enter git push heroku main and so: Total 0 (delta 0), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-22 stack remote: -----> Determining which buildpack to use for this app remote: -----> Python app detected remote: -----> Using Python version specified in runtime.txt remote: Traceback (most recent call last): remote: File "/tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/vendor/runtime-fixer", line 8, in <module> remote: r = f.read().strip() remote: File "/usr/lib/python3.10/codecs.py", line 322, in decode remote: (result, consumed) = self._buffer_decode(data, self.errors, final) remote: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte remote: /tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/bin/steps/python: line 9: warning: command substitution: ignored null byte in input remote: ' is not available for this stack (heroku-22). remote: ! For supported versions, see: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: 50c9a488b59502f133b3cce812e40e89000d2414 remote: ! remote: ! We have detected that you have triggered a build from source code with version 50c9a488b59502f133b3cce812e40e89000d2414 remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different … -
when I want to deploy my djnago project to aws elastic beanstalk it gives me error
when I want to deploy my Django project to AWS elastic beanstalk it gives me the error this is my error and I do not know how to fix it -
How to implement async await function in Django application when retrieving information from remote database
I have a Django application where I am retrieving information from remote Oracle database and I populate those information in chart using Chart.js. As you can see in my code, I am calling two times connection to database since I am popul.ating two charts The point is that process of retrieving information sometimes is taking so much time, and I read there is option to include async await option , where I can decrease I/O time. (attach and gngp_ntp is query that I am taking from other .py file) Can someone help me how to make simple async below function. def index(request): cursor1=connections['default'].cursor() cursor1.execute(attach) // execute the query r1= dictfetchall(cursor1) cursor2=connections['default'].cursor() cursor2.execute(gngp_ntp)// execute the query r2= dictfetchall(cursor2) return render(request,'app_sins/ps_capacity.html', {"all_post" : r1,"jokso" : r2}) -
django-imagekit - do not crash when source file does not exist
I have a Django model that has an image and an autogenerated thumbnail: img = ImageField(upload_to=..., max_length=64) img_thumbnail = ImageSpecField([ResizeToFit(width=64, height=64)], source='img') For a number of reasons, the img field may contain a filename that is no longer present in the filesystem. When the file is not there, the view crashes with a FileNotFoundError - No such file or directory: '....png' Is it possible to configure the img_thumbnail field / django-imagekit to fail silently? Also without writing having to catch the exception in the view. -
API Query in Django Rest Framework
I have created an API from Database, I can view the API but I am unable to do a query via URL for example: 127.0.0.1:8000/author?author_id=9, I am not sure where to add the query code. I want to filter using fields. Here is my models.py class AuthorAPI(models.Model): author_id=models.IntegerField() name=models.TextField() author_img_url=models.TextField() title=models.TextField() first_published_at=models.DateTimeField() excerpt=models.TextField() class Meta: db_table = 'view_author' serializers.py from rest_framework import serializers from .models import SortAPI, AuthorAPI class AuthorAPISerializer(serializers.ModelSerializer): class Meta: model=AuthorAPI fields='__all__' views.py from .serializers import APISerializer,AuthorAPISerializer from .models import SortAPI, AuthorAPI from rest_framework.response import Response from rest_framework.decorators import api_view @api_view(['GET']) def getauthor(request): if request.method == 'GET': results = AuthorAPI.objects.all() serialize = AuthorAPISerializer(results, many=True) return Response(serialize.data) -
Django serializer possibility of either creating new object or using an existing
Below is an example input: 'abc_obj': { "comments": string, "ref": string, "customer": 1, "address": { "street": string, "country": string, } } This is the serializer: class ABCObjSerializer(ModelSerializer[ABCObj]): address: AddressSerializer = AddressSerializer(required=False) customer: CustomerSerializer = CustomerSerializer(required=False) class Meta: model = ABCObj fields = "__all__" extra_kwargs = { "created_by": {"read_only": True}, } Is it possible with the existing serializer that I reuse / link the customer with the id=1. And in the next request if there is customer data (like address data in this request) then I create a new customer. The purpose is to enable the user to either create a new record or use an existing one. -
Display selection field in Django template
I 'm trying to find a workable solution for my problem. I have found two similar questions answered before, but still I can't solve it. If we have a class like this: from django.db import models class Consumer(models.Model): SIZES = ( ('S', 'Small'), ('M', 'Medium'), ('L', 'Large'), ) name = models.CharField(max_length=60) size = models.CharField(max_length=2, choices=SHIRT_SIZES) And I did in my view and template like this (Learned from one tutorial) ***view with combined queries*** def staff_filter(request): qs = Consumer.objects.all() shirt_size= request.GET.get('size') # I have some other queries in between .... if is_valid_queryparam(size) and size!='Choose...': qs = qs.filter(size=consumer.get_size.display()) return qs def filter(request): qs=admin_staff_filter(request) context={ 'queryset':qs, 'consumer':consumer.objects.all() } return render(request, 'filter.html',context) **template*** <div class="form-group col-md-4"> <label for="size">size</label> <select id="size" class="form-control" name="size"> <option selected>Choose...</option> {% for size in consumer.get_size.display %} <option value="{{ size }}">{{size}}</option> {% endfor %} </select> </div> How should I correct it? Thanks! Display selection field in Django template -
Django model: get QuerySet from OneToOne
Let's say I have this model: class Place(models.Model): name = models.CharField(max_length=50) class Restaurant(models.Model): place = models.OneToOneField(Place, on_delete=models.CASCADE) And I have this QuerySet: <QuerySet [<Place: 123>, <Place: 456>]> I would like to get the list of Restaurants associated with the Place. I tried: restaurant_list = Restaurant.objects.filter(place__in=queryset) but it returns me a QuerySet of Place, not Restaurant: <QuerySet [<Place: 123>, <Place: 456>]> How can I get the Restaurant associated with the Place of my QuerySet? -
Changing the order of django objects in site using javascript
On the html page I have a list of songs {% for comp in composition %} .... <p>{{ comp.title }}<p> .... {% endfor %} also each track has two buttons: up and down. How to make it so that when you press the up or down button, the track changes with the neighboring track and so that the position of the tracks also changes in the django database. -
Difference between multiple gunicorn workers with one server instance and 1 gunicorn worker with multiple server instances
I have a django application running with gunicorn (with the gevent worker type) that is hosted on aws. What would the difference be between having 1 gunicorn worker but with multiple instances of the app hosted and having multiple workers but only with one instance of the app hosted? Or am I completely misunderstanding and these 2 things serve different purposes and is not related at all? -
DJango: AUTO REDIRECT TO DEFAULT LANGUAGE
Hi, I have a strange problem with my Django website. In my settings.py my default LANGUAGE_CODE = 'nl'. When I go to www.example.be with DEBUG = True then I am automatically redirected to www.example.be/nl. When I go to www.example.be with DEBUG = False then I am not redirected to the default language and I get "Server error (500)". Why is this not working when DEBUG = False? I checked for other posts regarding to this problem but I could not find a solution. -
AttributeError: Got AttributeError when attempting to get a value for field `review_rating` on serializer `ReviewSerializer`
i have the following issue error AttributeError: Got AttributeError when attempting to get a value for field `review_rating` on serializer `ReviewSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance. Original exception text was: 'QuerySet' object has no attribute 'review_rating'. This is my model model class Review(models.Model): review_id = models.AutoField(primary_key=True) review_message = models.CharField(max_length=300, blank=True) review_rating = models.IntegerField() serializer class ReviewSerializer(serializers.ModelSerializer): class Meta: model = Review fields = '__all__' view class ReviewView(APIView): def get(self, request): queryset = Review.objects.all() serializer = ReviewSerializer(queryset) return Response(serializer.data, status=status.HTTP_200_OK) why am i getting this error -
Authenticate a wordpress website user to a django website
I have a pre-existing wordpress website and I am creating a django website which would provide other services to the users of the wp website. Now I want to display the products in the django website but I want to know how could I automatically authenticate the user while he has accessed the wordpress website so that the dynamic content of the website could be shown to him. Earlier I was trying to generate query in the url for the django website by I'm not a php guy and further I came across the idea of generating cookies from the wp website and retrieving it on the django website but I didn't know how to do this. -
Getting information from Jquery in Django views
in the jquery script, I get the information from the table into the data variable in json format: <script> var $table = $('#table') var $button = $('#button') $(function() { $button.click(function () { data = JSON.stringify($table.bootstrapTable('getData')) $.ajax({ url: "{%url 'addCampaign'%}", type: "POST", data: { 'mails_inf': data, 'csrfmiddlewaretoken': '{{ csrf_token }}', } }) }) }) </script> And in the function with views, I try to get this list for further processing as follows: def add_campaign(request): error = '' if request.method == 'POST': data = request.POST.get('mails_inf') print(data) But the data variable turns out to be None, when alerting this variable in the script itself, all the information is there. My tab where it all happens handles this url: path('addCampaign', views.add_campaign, name='addCampaign') I would be grateful if you could tell me where I am wrong, or offer another solution to the problem -
DRF Serializer relations Erro: Direct assignment to the forward side of a many-to-many set is prohibited. Use group.set() instead
I'm creating an api that will register users related to a customer and also to an organizational group, but I'm having problems registering the user's group. whenever I try to register I get the following error: "Direct assignment to the forward side of a many-to-many set is prohibited. Use group.set() instead." Could you help me understand what I'm doing wrong? my models.py class Cliente(models.Model): nome = models.CharField(max_length=100, unique=True, null=True) documento = models.CharField(max_length=30, blank=True, default='00.000.000/0001-00') logo = models.CharField(max_length=255, blank=True, null=True) data_de_criacao = models.DateField(default=date.today) cliente_ativo = models.BooleanField(default=True) background_img = models.CharField(max_length=255, blank=True, null=True) cor_primaria = models.CharField(max_length=10, blank=True, null=True) cor_secundaria = models.CharField(max_length=10, blank=True, null=True) def __str__(self): return self.nome class GrupoOrganizacional(models.Model): id_grupo = models.BigAutoField(primary_key=True, unique=True) nome_grupo = models.CharField(max_length=100, blank=False, null=False) cliente = models.ForeignKey(Cliente, blank=True, null=True ,on_delete=models.CASCADE) def __str__(self): return self.nome_grupo class Usuario(AbstractUser): objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] cliente = models.ForeignKey(Cliente, blank=True, null=True ,on_delete=models.CASCADE) first_name = models.CharField(max_length=100, blank=False, null=False) last_name = models.CharField(max_length=100, blank=False, null=False) username = models.CharField(max_length=50, blank=True, null=True) email = models.EmailField(max_length=100, blank=False, null=False, unique=True, error_messages={'unique': "O email cadastrado já existe."}) password = models.CharField(max_length=100, blank=False, null=False) usuario_ativo = models.BooleanField(default=True) grupo = models.ManyToManyField(GrupoOrganizacional, related_name='grupos') is_staff = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) def __str__(self): return "%s (%s)" %(self.first_name, self.cliente) my views.py class GruposViewSet(viewsets.ModelViewSet): ''' Lista … -
pass a JSON data from React to Django using POST request problem
I'm trying to pass information using POST but I get a request in OPTIONS. the request - "OPTIONS /store-register HTTP/1.1" 200 13. when i change views.py request.method == 'POST' to: request.method == 'OPTIONS' i get "Broken pipe from ('127.0.0.1', 61126)" I can't figure out the problem. view.py: @csrf_exempt def store_register(request): if request.method == 'POST': form = json.loads(request.body) vendor = Vendors.objects.create(store_name=form['storeName'],company_name=form['companyName'],img=form['storeImage'],business_email=form['storeEmail'],pay_pal=form['payPalEmail']) vendor.save() return JsonResponse({'user': 'testONly'}) React Companent: class StoreRegister extends React.Component { constructor(props) { super (props); this.state = { acceps: '' } } getAndSendInput = () => { const storeName = document.getElementById('storeName').value const companyName = document.getElementById('companyName').value const storeImage = document.getElementById('storeImage').value const storeEmail = document.getElementById('storeEmail').value const payPalEmail = document.getElementById('payPalEmail').value this.setState({storeName: storeName,companyName: companyName,storeImage: storeImage, storeEmail: storeEmail,payPalEmail: payPalEmail}) fetch('http://127.0.0.1:8000/store-register', { method: "POST", body: JSON.stringify ({ 'storeName':storeName, 'companyName':companyName, 'storeImage':storeImage, 'storeEmail':storeEmail, 'payPalEmail':payPalEmail }), headers: new Headers ({'Content-type': 'application/json; charset=UTF-8'}) }) console.log(storeName,companyName,storeImage, storeEmail,payPalEmail) } render () { return ( <div> <label>Store Name</label> <input type={"text"} name={"storeName"} id={"storeName"} ></input> <br></br> <label>Company Name</label> <input type={"text"} name={"companyName"} id={"companyName"} ></input> <br></br> <label>Store Image</label> <input type={"file"} name={"storeImage"} id={"storeImage"}></input> <br></br> <label>Store Email</label> <input type={"email"} name={"storeEmail"} id={"storeEmail"} ></input> <br></br> <label>Pay Pal Email</label> <input type={"email"} name={"payPalEmail"} id={"payPalEmail"}></input> <br></br> <button onClick={() => this.getAndSendInput()}>Register</button> </div> ) } } export default StoreRegister -
How to perform a Django ORM calculation across an m2m field
I'm trying to figure out how to get a specific clients percentage share of income which may be split between multiple owners or shared equally. The models (simplified) are: class Client(Model): ... class Loan(Model): applicants = ManyToManyField(Client) class Income(Model): loan = ForeignKey(Loan) amount = DecimalField() income_type = CharField(choices=['INVESTMENT', ...]) proportions = CharField(default='EQUAL', choices=['EQUAL', 'SPECIFIED']) class IncomeOwner(Model): income = ForeignKey(Income, related_name='owners') client = ForeignKey(Client) percent = DecimalField() From those models I'm attempting the following to calculate income shares, by category, for a given client/loan combination. It's important to note that the owners relation only matters if proportions is 'SPECIFIED' - otherwise all applicants have an equal share. For performance reasons I'm trying to keep the logic in the ORM: def get_income(loan, client): # This income can be associated with multiple applicants as follows: # - If the "proportions" are "EQUAL" then assign this applicant an equal split # between the other applicants (amount / num_applicants) # - Otherwise use the amount directly assigned to the income owner # The percentage based on number of applicants or taken from the owner percent field equal_share_percent = ExpressionWrapper(100 / F('num_applicants'), output_field=PercentageValueField()) applicant_share_percent = Case( When(proportions='SPECIFIED', then=F('owners__percent')), <-- ONLY WANT % FOR THIS CLIENT default=equal_share_percent … -
Django: Display SessionWizard multi-step form inside a modal of existing view
I am trying to create an Instagram Clone and have the home page in the index view. I want to add a Multi-Step form to add a new Post as below: Step 1: Upload Image Step 2: Add caption and submit Just like Instagram, i want this form to show up as a Modal/Pop-up when the Create Post icon is clicked from the Home Page. From the documents and other sources, I was only able to create a SessionWizard form as a separate view. Also, i would like to know if the done() function can be modified/skipped and only a custom confirmation message can be shown inside the modal after submission. -
nginx is unconfigured and inactive after upgrading AL2 Docker platform to newest version
We have a dockerized Django application on Elastic Beanstalk running on the now-deprecated AMI platform, deployed via the EB CLI. I'm the sole technical employee and only recently inherited this environment with little to no handover and no prior experience with AWS. When I first deployed a new environment on the AL2 Docker 3.5.0 platform, following the upgrade guide from Amazon, the new instances come up and immediately fail all health checks. Turns out that nginx service is inactive and the applied config files are all just nginx defaults and neither the EB platform defaults nor the .conf files I placed in .platform/nginx/conf.d/elasticbeanstalk are present. Just starting the nginx service allows health checks to succeed but since the config is all missing all it shows is the default nginx welcome page. After some trials and tribulations I tried cloning the environment, then downgrading that to AL2 Docker 3.0.3. After deploying to the downgraded platform everything works out of the box. Primary difference I can see between 3.0.3 and 3.5.0 is a jump from docker version 19.03 to 20.10 (ref), and nginx from 1.16 to 1.20. I then tried the last platform version available that still used the docker 19 which … -
import "django.shortcuts" could not be resolved from sauce Pylance(reportMissingModuleSoucre)
[![import "django.shortcuts" could not be resolved from sauce Pylance(reportMissingModuleSoucre) from django.shortcuts import render # Create your views here. def get_home(request): return render(request,'home.html') i didnt try anything,i need some help -
Django - Error when I filter my form field's queryset
I created a form and view (FBV) to add new model. I overrided form's __init__ but now when I try to access my view it raise an error CreationForm' object has no attribute 'get' My view : def Creation(request): user = None if request.user.is_authenticated: user = request.user # POST METHOD if request.method == "POST": form = CreationForm(request.POST) form.user = user if form.is_valid(): sheet = form.save() return redirect("sheet_detail", pk=sheet.id) form = CreationForm(initial={'user': request.user}) return render(request, "jde/creation_form.html", context={"form": form}) My form : class CreationForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CreationForm, self).__init__(self, *args, **kwargs) self.fields["contest"].queryset = Contest.objects.filter(active=True) class Meta: ...