Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I create a group as well as add members to it to make a queryset for Postman?
class AddUserToGroupApiView(APIView): """ Create a hello message with our name """ def post(self, request): serializer = GroupSerializer(data=request.data) if serializer.is_valid(): data = serializer.validated_data group = Group.objects.create(group_name=data.get('group_name')) print(group) group_name = request.data.get('group_name') members = request.data.get('members') print(members) print(group_name) user = UserProfile.objects.filter(name=members) print(user) groups = Group.objects.get(group_name=group_name) print(groups) if not groups.members.filter(members=user).exists(): groups.members.add(user.email) return Response({"status": "Group Created"}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) How can add users to the created group and make a group_name , members query in Postman? -
name 'c' is not defined in python
I tried to make a calculator with Django, but got this error this view function takes the input from html page and do the calculation where is the problem here? views.py - from django.shortcuts import render from django.template import loader from django.http import HttpResponse # Create your views here. def indx(request): template = loader.get_template('calculator/calc_home.html') if request.method=='POST': global c,a,b a=request.POST.get('num1') b=request.POST.get('num2') option=request.POST.get('select_val') if a=="" or b=="" : c='please select 2 numbers' else: if option=='add': c=int(a)+int(b) elif option=='multiply': c=int(a)*int(b) elif option=='substract': c=int(a)-int(b) elif option=='devide': if int(b)+0== 0: c='infinity' else: c=int(a)/int(b) else: c='please choose an option' context={ 'sum':c } return HttpResponse(template.render(context,request)) calc_home.html html code takes the input and passes it to the view <h1>welcome to calculator</h1> <p>enter 2 numbers</p> <form method="POST"> {% csrf_token %} <label for="num_1">enter 1st number:</label> <input type="number" name="num1" value='num_1'><br> <label for="num_2">enter 2nd number:</label> <input type="number" name="num2" value='num_2' ><br> <input type="radio" value="add" name="select_val" id="add" > <label for ="add">+</label><br> <input type="radio" value="substract" name="select_val" id="subs" > <label for ="subs">-</label><br> <input type="radio" value="multiply" name="select_val" id="multiply" > <label for ="multiply">*</label><br> <input type="radio" value="devide" name="select_val" id="devide" > <label for ="devide">/</label><br> <input type="submit" name="submit" value="submit"> </form> <h1>{{ sum }}</h1> <br><a href="{% url 'home:homex' %}">go to home</a> error this error is coming in the html page name 'c' … -
Module not found: Error: Can't resolve '@popperjs/core' in 'C:\Users\jkids\mit-tab\node_modules\bootstrap\dist\js'
I'm trying to do a python devserver and keep getting this error, it's running with MySQL and Django; I've tried npm installing @poppyjs/core and poppy.js and neither work -
Linked the css file in django html template but no output
I linked my django html template with the css file, but there is no error and no changes in the page. And when I write the same css code in the same html file under the tag, it works correctly, can someone please guide on what is going wrong? Attaching the code of html file and settings file. HTML File <!DOCTYPE html> {% load static %} <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>TPC - Student Dashboard</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> ::placeholder { /* Chrome, Firefox, Opera, Safari 10.1+ */ color: white; opacity: 1; /* Firefox */ } :-ms-input-placeholder { /* Internet Explorer 10-11 */ color: white; } ::-ms-input-placeholder { /* Microsoft Edge */ color: white; } *{ background:#E7E9F0; font-family: "Segoe UI", Arial, sans-serif; } </style> <link rel='stylesheet' src="{% static 'Dashboards/student_dashboard.css' %}"> </head> <body> </body> </html> settings.py from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = DEBUG = TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'loginRegistration', 'dashboards', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'tpcAutomation.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates")], 'APP_DIRS': True, … -
How to change the behaiour of django_spanner application on entire djano project? As I am using 2 databases inside my django application
My Django application has 2 databases (spanner and AWS RDS). I am trying to integrate spanner DB with existing RDS (following the Django spanner document mentioned at the link below). It says we should include the django_spanner application inside the INSTALLED_APPS list. I have multiple applications inside my Django project but I want to use spanner only for one app. After following the steps that are mentioned in the below document, it says The django_spanner application changes the default behavior of Django's AutoField so that it generates random values (instead of automatically incrementing sequentially). This seems to be done to avoid a common anti-pattern in Cloud Spanner usage. I don't want this to happen for other tables where auto-generated id keys are getting randomly generated after including django_spanner, because the other tables will still be in AWS RDS(where we need automatically increasing ids). Can anyone please suggest any solution? https://cloud.google.com/blog/topics/developers-practitioners/introducing-django-cloud-spanner-databas -
how to instance and update multiple row in a table with Django
I have a simple table with some rows: My goal is to instantiate the current value of the quantity and eventually save the new data for all the lines. At the moment I have a simple view: @login_required def compilaDocMultiRow(request,pk): member = get_object_or_404(testaDoc, pk=pk) family = corpoDoc.objects.filter(doc=pk) if request.method == "POST": form = multiCorpoDocForm(request.POST or None) if form.is_valid(): reg = form.save(commit=False) reg.doc_id = member.pk reg.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) else: print(form.errors) else: form = multiCorpoDocForm() return render(request, "compilaDocMultiRow.html", {'family':family, 'member':member, 'form':form}) Is there a way to do this using only Django? -
One to Many field in Model of Django
I am creating a model in Django, but quite confuse about the type of field should i take: Problem: I have to access multiple domains in one web classification, advice me please how do i make these field relationship so that if I try to get one web classification details then it will also contain list of related domain in that as well. Model.py: class WebClassification(models.Model): vendor_id = models.ForeignKey(Vendor, on_delete=models.CASCADE, default=None, null=True) id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) description = models.CharField(max_length=1000) domain_name = models.[what type i take here] def __str__(self): return self.name Domain.py class Domain(models.Model): id = models.IntegerField() domain_name = models.CharField(max_length=200) def __str__(self): return self.domain_name -
How to create a url for two apps that have index function in django?
I am a newbie in Django. In one django project, I have two apps say college app and company app. In the college app, I have in the college\urls.py path('', index, name="index") and in another company app, I have path('company/', HomeView.as_view(), name="index"). How do I create a url of both these in the header.html ? I tried these but its not working College Home Page ||` Company Home Page || -
print out celery settings for django project?
I'd like to know if celery settings specified in the settings.py file is actually being recognized. How can I tell if celery picked up the options? -
Two .css file in Django static folder only one can be found
I can't understand as the title described. Please refer to image below: The two css files is under the same folder and in the template file I copy the link line just changed the file name. Why the abc.css file can't be found as shown in the command line screen? I just can't understand. Also anther image file is also not found either, also a mystery to me. -
DeleteView lead to error 405 when submit is clicked on django
I have this small blog post where everything works fine apart from delete view. As soon as I hit confirm from DeleteView html page I get 405 error my views.py looks like this my html file where the link is mentioned is like this urls looks this way and html for deleteview -
Django celery unregistered task
I'm running two django projects in one VM and for that two separate celery process is running with supervisor. Now suddenly the tasks is getting clashed with other process. I'm getting unregistered task error. I don't know how of sudden i'm facing this issue. Earlier it was working and nothing changed in the configurations. The above attached image is a reference and task is registered in other service but how of a sudden it's running here. I tried so many solution not able to find the root cause. Any help is appreciated. -
(Django) Сменил директорию проекта, перестали работать команды в терминале
Перекинул папку проекта в другую, вродь как указал путь интерпретатора, но все равно не могу выполнить командуenter image description here -
Automating Celery monitoring for abnormal queue length
I'm using Django/Celery/Redis to handle tasks that import large amounts of data into my db. Occasionally, something will go wrong and the workers seemingly hang -- I'm curious if there's a way for me to monitor the size of my queues inside of my Django application so that I can create a custom alert. For example, if my queue grows above 100, I'd like to create an alert. Right now, I'm just periodically checking the queues via the Redis CLI, but that is not sustainable. I realize that this question may be vague since there's no code, but I'm just not sure where to start here. -
Add a new attribute in serializer but doesn't appear
I want to add a new attribute apartment_sold in the Transaction serializer, but I seem it doesn't work! serializes.py class TransactionSerializer(serializers.HyperlinkedModelSerializer): buyer = serializers.ReadOnlyField(source='buyer.username') apartment_sold = serializers.HyperlinkedRelatedField(view_name='sold-detail', read_only=True) class Meta: model = Transaction fields = [ 'id','buyer','apartment_sold','timestamp' ] views.py class SoldViewSet(viewsets.ReadOnlyModelViewSet): queryset = Apartment.objects.filter(issold=True).order_by('-timestamp') serializer_class = ApartmentSerializer class TransactionViewset(viewsets.ModelViewSet): queryset = Transaction.objects.all().order_by('-timestamp') serializer_class = TransactionSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] def perform_create(self, serializer): transaction = serializer.save(buyer=self.request.user) transaction.apartment.issold = True transaction.apartment.save() -
how to add if condition in django with compare session value in html
I have an error when I compare the value of the session in the HTML templates error: Could not parse the remainder: '{{' from '{{' {% if {{ request.session.userinput }} == "Too low!" and {{ request.session.attempt }} < 5 %} <div class="box" style="background-color:rgb(235, 66, 66);"> <h1 class="boxh1">{{request.session.userinput}}!</h1> </div> {% elif {{request.session.userinput }} == "Too high!" and {{request.session.attempt}}< 5 %} <div class="box" style="background-color:rgb(235, 66, 66);"> <h1 class="boxh1">{{ request.session.userinput }}!</h1> </div> {% elif {{ request.session.userinput }} == {{ request.session.number }} and {{request.session.attempt}} < 5 %} <div class="box" style="background-color: rgb(119, 245, 147);"> <h1 class="boxh1">{{ request.session.number }} was the number!</h1> <a href="/destroy_session"><button class="replay-btn">Play again!</button></a> </div> {% endif %} <div id="k" class="form" > <form action="/guess" method="post"> <input class="num" type="text" name="num" required value=""/><br> <input class="btn" type="submit" value="Submit" /> </form> </div> view.py def guess(request): if request.session["attempt"]==5: request.session["attempt"]=5 if request.session["number"] == int(request.POST["num"]): request.session["userinput"] =request.session["number"] elif request.session["number"] < int(request.POST["num"]): request.session["userinput"]="Too high!" request.session["attempt"] += 1 elif request.session["number"] > int(request.POST["num"]): request.session["userinput"]="Too low!" request.session["attempt"] += 1 context ={ "attempt":request.session["attempt"], "userinput":request.session["userinput"], "number":request.session["number"] } return render(request,'index.html',context) Is correct the way that I compare session values in HTML? -
Confused about the import syntax in django for Render()
Im trying to understand the period in from django.shortcuts import render Does it mean from the django directory in the shortcuts file? Or does it mean from the django directory, from the shortcuts directory, import the render file? -
TypeError: 'ModelBase' object is not iterable when trying to use Exclude
I have the following two models: class Listings(models.Model): CATEGORY = [ ("Miscellaneous", "Miscellaneous"), ("Movies and Television", "Movies and Television"), ("Sports", "Sports"), ("Arts and Crafts", "Arts and Crafts"), ("Clothing", "Clothing"), ("Books", "Books"), ] title = models.CharField(max_length=64) description = models.CharField(max_length=500) bid = models.DecimalField(max_digits=1000000000000, decimal_places=2) image = models.URLField(null=True, blank=True) category = models.CharField(max_length=64, choices=CATEGORY, default=None) user = models.ForeignKey(User, on_delete=models.CASCADE, default="") class CloseListing(models.Model): listings = models.ForeignKey(Listings, on_delete=models.CASCADE, default="") user = models.ForeignKey(User, on_delete=models.CASCADE, default="") I want to be able to query through all the objects of every listing that is not in the CloseListing model. How can I do this? def index(request): listings = Listings.objects.all().exclude(id__in=CloseListing) return render(request, "auctions/index.html",{ "listings": Listings.objects.all() }) error message: TypeError: 'ModelBase' object is not iterable because of listings = models.ForeignKey(Listings, on_delete=models.CASCADE, default=""). -
UPS API call format with django to html
import xml.etree.ElementTree as ET from zeep import Client, Settings from zeep.exceptions import Fault, TransportError, XMLSyntaxError # Set Connection settings = Settings(strict=False, xml_huge_tree=True) client = Client('SCHEMA-WSDLs/RateWS.wsdl', settings=settings) # Set SOAP headers headers = { 'UPSSecurity': { 'UsernameToken': { 'Username': 'username', 'Password': 'password' }, 'ServiceAccessToken': { 'AccessLicenseNumber': 'asdasdasdasd' } } } # Create request dictionary requestDictionary = { "RequestOption": "Shop", "TransactionReference": { "CustomerContext": "Your Customer Context" } } # Create rate request dictionary rateRequestDictionary = { "Package": { "Dimensions": { "Height": "10", "Length": "5", "UnitOfMeasurement": { "Code": "IN", "Description": "inches" }, "Width": "4" }, "PackageWeight": { "UnitOfMeasurement": { "Code": "Lbs", "Description": "pounds" }, "Weight": "1" }, "PackagingType": { "Code": "02", "Description": "shop" } }, "Service": { "Code": "03",#3 – Standard List Rates "Description": "Service Code" }, "ShipFrom": { "Address": { "AddressLine": [ "1 toronto rd", ], "City": "North York", "CountryCode": "CA", "PostalCode": "M3J1C8", "StateProvinceCode": "ON" }, "Name": "Name" }, "ShipTo": { "Address": { "AddressLine": "15 Hillpark Trail", "City": "Brampton", "CountryCode": "CA", "PostalCode": "L6S1R1", "StateProvinceCode": "ON" }, "Name": "Name" }, "Shipper": { "Address": { "AddressLine": [ "Street Name", ], "City": "Toronto", "CountryCode": "CA", "PostalCode": "M3J1C8", "StateProvinceCode": "ON" }, "Name": "ZTL", "ShipperNumber": "+66666666" } } # Try operation try: response = client.service.ProcessRate(_soapheaders=headers, Request=requestDictionary, Shipment=rateRequestDictionary) … -
Django CORS - localhost with any port
Running into a CORS issue with my Django app. I've got it configured properly and I've narrowed the issue down to my list of URLS - settings CORS_ORIGIN_ALLOW_ALL = True fixes it. This is my current list: CORS_ALLOWED_ORIGINS = [ "http://localhost", ... ] My front end is a Flutter app, the problem is that in development Flutter runs on any random port e.g., localhost:12345, so I can't hardcode this into the CORS list. My question is this - how can I add localhost with any arbitrary port to the list? I can't seem to find docs on it, the only alternative seems to be to just allow everything which I'd prefer not to do. Thank you in advance! -
Django Template with a Dicitonary of Lists
Using django I am passing a dictionary of lists as the context for my template. The dictionary is structured as such: weather = { 'temp' : temp, 'time' : time, 'pop' : pop } Temp, time, and pop are lists of equal length with each index of those lists going together. Meaning temp[1] , time[1], and pop[1] are together and temp[2] , time[2], and pop[3] and so on. I would like to display these values like so: temp[1] time[1] pop[1] temp[2] time[2] pop[2] . . . temp[y] time[y] pop[y] #y is the length of the lists I have tried to do this by making a for loop in my template the looks like this: {%for x in weather%} <p> <span>{{weather.temp.x}}</span> <br> <span>{{weather.pop.x}}</span> <br> <span>{{weather.time.x}}</span> <br> </p> {%endfor%} But all this does is make empty lines. Could I get some help please? -
How to get access to a different object through a variable storing Django Max object?
I have a Django model called Bids with the following objects: listing, bid, and user. I am trying to get access to the user with the largest bid. How do you do that? I am currently trying: winning_bid = Bids.objects.aggregate(Max('bid')) winner = winning_bid.user -
Django Crispy Form with Toggle switch element
I am using Crispy Forms and layout helper to generate my Input form. I'd like to add a Toggle switch into the form. desired result: what I get: forms.py: class RequestForm(forms.ModelForm): on_prem = forms.CharField(widget=forms.CheckboxInput(attrs={"class": "slider form-control"})) class Meta: model = Request fields = ['on_prem'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.layout = Layout( Div( Div(Field('on_prem'), css_class='col-md-3', ), css_class='row', ), ) models.py: class Request(models.Model): on_prem = models.BooleanField(default=False) form.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} {% crispy form %} <button type="submit" class="d-block btn btn-outline-inverse mt-4 w-50 mx-auto"> Save Request </button> </form> I have seen in the Bootstrap documentation that the toggle switch effect I desire is achieved with nested css classes and I am not sure how to achieve that via the form helper. Any help would be greatly appreciated. -
django-environ can't read docker container variables
I'm using Docker containers with Django. In my container I'm using environment variables via .env file container_name: env_file: .env I have echoe'd SECRET_KEY after the container is up and it shows the correct value set in .env file. The problem is in my settings. When I do the following... import environ env = environ.Env() SECRET_KEY = env('SECRET_KEY', default='some_other_value') ... I was expecting "try to read 'SECRET_KEY' from the OS, but if you can't find it set it to 'some_other_value'. It turns out it isn't, having the following output: get 'SECRET_KEY' casted as 'None' with default '<NoValue>' On the other hand, if I do os.environ.get('SECRET_KEY') it gets the correct value. What am I doing wrong with django-environ package? -
Django: No module named 'admin'
I deleted my sqlite database and all migration folders and this happend: ModuleNotFoundError: No module named 'admin' I tried to do django.setup(), but it`s not working https://github.com/himokkk/django_images