Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cart delete an item and apply a coupon in js
I am trying to remove an item without removing the cart and reducing a price if the customer has a coupon or exceeds a certain quantity while js before using Django here is the html code js if you have any advice do not hesitate html <div data-name="name" data-price="250" data-id="2"> <img src="x.jpg" alt="" /> <h3>name</h3> <input type="number" class="count" value="1" /> <button class="tiny">Add to cart</button> </div> <script type="text/template" id="cartT"> <% _.each(items, function (item) { %> <div class = "panel"> <h3> <%= item.name %> </h3> <span class="label"> <%= item.count %> piece<% if(item.count > 1) {%>s <%}%> for <%= item.total %>$</span > </div> <% }); %> </script> js addItem: function (item) { if (this.containsItem(item.id) === false) { this.items.push({ id: item.id, name: item.name, price: item.price, count: item.count, total: item.price * item.count }); storage.saveCart(this.items); } else { this.updateItem(item); } this.total += item.price * item.count; this.count += item.count; helpers.updateView(); }, containsItem: function (id) { if (this.items === undefined) { return false; } for (var i = 0; i < this.items.length; i++) { var _item = this.items[i]; if (id == _item.id) { return true; } } return false; }, updateItem: function (object) { for (var i = 0; i < this.items.length; i++) { var _item = this.items[i]; … -
Best way to render a sortable table from a Django Model which displays custom fields?
I want to generate a table based on selected fields from a model(decided by an algorithm), and I want to be able to sort the columns in that table. I also want the user to be able to click on a button on each row which leads to a new page generated by a key from that row (ie. "edit") I have tried django-tables2, but it seems that this would prevent me from adding the buttons and adding the algorithms I want which govern what types of fields are on display. The generation of the custom table itself is not a problem - but I can't seem to find any sources on making a sorting function. Where can I find this? -
Incorrect redirect of NGINX with Docker
I'm building my first project with Django, NGINX and Docker. Below the nginx.conf: upstream project { server website:8000; } server { listen 80; server_name MY-DOMAIN; location / { proxy_pass http://project; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; client_max_body_size 4G; } location /static/ { alias /app/static-folder/; } location /media/ { alias /app/media-folder/; } } And the docker-compose: version: '3.7' services: website: container_name: web_project image: project/django build: ./djangodocker restart: always env_file: prod.env command: sh -c "cd djangodocker/ && gunicorn djangodocker.wsgi:application --bind 0.0.0.0:8000" volumes: - static-folder:/app/static-folder - media-folder:/app/media-folder expose: - 8000 nginx: container_name: nginx_web_project image: project/nginx build: ./nginx volumes: - static-folder:/app/static-folder - media-folder:/app/media-folder ports: - 8000:80 depends_on: - website volumes: static-folder: media-folder: I can build the image but I can't see the website into the correct url. I see the website at MY-DOMAIN:8000 instead of MY-DOMAIN and this is my problem. -
How to map different request types to different views using the same exact path in Django?
I want to have a url something like api/instrument/{id} and then based on the request type GET, POST, DELETE route the request to a different view in my Django app. I have these views: from django.shortcuts import render from django.http.response import JsonResponse, from django.http.request import HttpRequest from rest_framework.parsers import JSONParser from rest_framework import status from Instruments.services import instruments_service from models import Instrument from serializers import InstrumentsSerializer from rest_framework.decorators import api_view from services import InstrumentsService # Application views live here @api_view('GET') def get_instrument_by_id(request:HttpRequest, id): instrument_service = InstrumentsService() data={} try: data = instrument_service.get_instrument_by_id(id) return JsonResponse(data,status=status.HTTP_200_OK, safe=False) except Exception as exc: return JsonResponse({"Status":f"Error: {exc}"},status=status.HTTP_404_NOT_FOUND , safe=False) @api_view('POST') def update_instrument_by_id(request:HttpRequest, id): instrument_service = InstrumentsService() instrument_data = JSONParser().parse(request) data={} try: data = instrument_service.update_instrument_by_id(id, instrument_data) return JsonResponse(data,status=status.HTTP_200_OK, safe=False) except Exception as exc: return JsonResponse({"Status":f"Error: {exc}"},status=status.HTTP_404_NOT_FOUND , safe=False) @api_view('DELETE') def delete_instrument_by_id(request:HttpRequest, id): instrument_service = InstrumentsService() data={} try: data = instrument_service.delete_instrument_by_id(id) return JsonResponse(data,status=status.HTTP_200_OK, safe=False) except Exception as exc: return JsonResponse({"Status":f"Error: {exc}"},status=status.HTTP_404_NOT_FOUND , safe=False) I see that people using django make ONE function to hanlde all requests and then they have logioc inside it but that seems so wrong to me. Is there a way to map the same URL endpoint to different function based on the request type? -
How to read a specific field in a MongoDB collection
I want to print a specific field on html on mongodb, but I am getting an error, how can I do it? I'm getting IndexError: list index out of range error. view py; def deleted2(request): mpid = ('XX') tuy = ('XX') client = MongoClient("XX") print('connectionsuccess') database = client["1"] collection = database["2"] query = {} query["XX"] = mpid query["$or"] = [ { "Tuy": tuy } ] print('querysuccess') cursor = collection.find(query) sonuc= loads(dumps(cursor)) msg=sonuc[0]["_id"] print(msg) client.close() return render(request, 'deleted.html',{'msg':msg}) -
Identity Verification by SMS/Email | Django
Please help me with choosing a solution for implementing identity verification using a one-time token with a limited lifetime. By identity verification, i mean the need to send a token/code to a user via a phone number or email. For example, to reset password. I am interested in a solution that is best for use in a modern web application. Please tell me based on your experience in developing such systems. The solutions I have on my mind: Use redis as storage. In case of working with email, generate a token and save it in redis, where the key - user's email address. In the case of working with SMS, create a code and save it in redis, where the key - user's phone number. Possible disadvantage: since redis is designed to work with a key-value pair, it is impossible to have two tokens/codes at once. (meaning that they will have different purposes). It is possible that this is not necessary at all. Use the Django object model as storage. Something like this: class TokenManager(models.Manager): # Some util-methods. # ... def delete_expired(self): expires = models.ExpressionWrapper( models.F("created_at") + models.F("lifetime"), models.DateTimeField() ) self.annotate(expires_at=expires).filter(expires_at__lte=now()).delete() class Token(models.Model): # Roughly speaking, token identifier. Examples: "password-reset", … -
How to limit CheckboxSelectMultiple choices for paid membership in Django
I'm struggling with my code in Django. My app is Garden, when you create a new garden and you are a member of 'plus' membership, you can select unlimited plants. But if you are a member of free membership you can select only 3 plants. How can I do that? models.py class Garden(models.Model): name = models.CharField(max_length=256) description = models.TextField(blank=True, default='') address = models.CharField(max_length=512) plant = models.ManyToManyField(Plant, related_name="gardens", through="GardenPlant") user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) class Membership(models.Model): PLUS = 'PL' FREE = 'FR' MEMBERSHIP_CHOICES = ( (PLUS, 'plus'), (FREE, 'free') ) slug = models.SlugField(null=True, blank=True) membership_type = models.CharField(choices=MEMBERSHIP_CHOICES, default=FREE, max_length=30) price = models.DecimalField(default=0, max_digits=999, decimal_places=2) class UserMembership(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='user_membership', on_delete=models.CASCADE) membership = models.ForeignKey(Membership, related_name='user_membership', on_delete=models.SET_NULL, null=True) class Subscription(models.Model): user_membership = models.ForeignKey(UserMembership, related_name='subscription', on_delete=models.CASCADE) active = models.BooleanField(default=True) def __str__(self): return self.user_membership.user.username forms.py class GardenForm(forms.ModelForm): class Meta: model = Garden fields = ['name', 'description', 'address', 'plant'] def clean_plant(self): value = self.cleaned_data['plant'] if len(value) > 3: raise forms.ValidationError("You can't select more than 3 items.") return value plant = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=Plant.objects.all()) def save(self, user): garden = super().save(commit=False) garden.user = user garden.save() garden.plant.add(*self.cleaned_data.get('plant')) views.py def create_garden(request): form = GardenForm(request.POST or None) if form.is_valid(): form.save(request.user) return redirect('/garden') context = {"form": form, "has_subscription": subscription_check(request.user)} return render(request, "create_garden.html", … -
Heroku push is failing with error: node:internal/modules/cjs/loader:936 throw err;
I'm trying to build a small web application with django and react. I already added the buildpacks for both. Now I wanted to run git push heroku master, but I keep getting this output: remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpacks: remote: 1. heroku/nodejs remote: 2. heroku/python remote: -----> Node.js app detected remote: remote: -----> Creating runtime environment remote: remote: NPM_CONFIG_LOGLEVEL=error remote: NODE_VERBOSE=false remote: NODE_ENV=production remote: NODE_MODULES_CACHE=true remote: remote: -----> Installing binaries remote: engines.node (package.json): 16.13.0 remote: engines.npm (package.json): 8.1.0 remote: remote: Resolving node version 16.13.0... remote: Downloading and installing node 16.13.0... remote: npm 8.1.0 already installed with node remote: remote: -----> Installing dependencies remote: Prebuild detected (node_modules already exists) remote: Rebuilding any native modules remote: rebuilt dependencies successfully remote: Installing any new modules (package.json) remote: remote: changed 3 packages, and audited 567 packages in 1s remote: remote: 55 packages are looking for funding remote: run `npm fund` for details remote: remote: found 0 vulnerabilities remote: remote: -----> Build remote: Running build remote: remote: > frontend@1.0.0 build remote: > webpack --mode production remote: remote: node:internal/modules/cjs/loader:936 remote: throw err; remote: ^ remote: remote: Error: Cannot find module '../lib/bootstrap' … -
django extra select to qs
How can i add addition select in queryset? queryset = ActivityCollection.objects.filter(date_at__gte=from_date, date_at__lte=to_date).order_by('date_at') it looks { "date_at": "2021-11-24", "views": 25, "clicks": 1, "cost": "25.00" }, i need to get: { "date_at": "2021-11-24", "views": 25, "clicks": 1, "cost": "25.00", "cpc": "25" } cpc = cost / clicks -
Django static css is not loading on page
I know there are many posts about this, but I have been unable to resolve my problem (for example following this: Django static files (css) not working). I can't get my css static file to load on this practice page, css_practice.html. I have the following structure djangoAjax settings.py ... djangoAjaxApp static ok.css templates css_practice.html My settings.py: import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = '############################################' # SECURITY WARNING: don't run with debug turned on in production! 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', "crispy_forms", 'djangoAjaxApp', ] 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 = 'djangoAjax.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'djangoAjax.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL … -
how to save two dynamic relates forms together - django
I'm trying to save three forms together : this the scenario ; form 1 Invoice number, form 2 item names can have several items in one invoice , form 3 Serial number, serial number if in the form2 item one quantity = 10 then we have 10 unique serial numbers , and second item quantity = 4 we have to add 4 unique serial number , in one submit button . i've used maodelformset_factory to make the forms dynamic here is the models class ItemName(models.Model): item_name = models.CharField(max_length=60,unique=True) class Invoice(models.Model): admin = models.ForeignKey(User,on_delete=models.PROTECT) company = models.ForeignKey(ClientCompany,on_delete=models.PROTECT) invoice_no = models.IntegerField(blank=True,null=True) items = models.ManyToManyField(ItemName,through='Item') class Item(models.Model): invoice = models.ForeignKey(Invoice,on_delete=models.PROTECT,related_name='invoice') item = models.ForeignKey(ItemName,on_delete=models.PROTECT,related_name='item_name') qnt = models.IntegerField() price = models.DecimalField(decimal_places=3,max_digits=20) class Serial(models.Model): item = models.ForeignKey(Item,on_delete=models.PROTECT) serial_no = models.CharField(max_length=15,unique=True) status = models.BooleanField(default=True) and i've used modelform i think it doesnt require to post the forms , the Serial and Item are modelformset_factory , and here is the view @login_required def create_invoice_view(request): form = InvoiceForm() item_formset = itemformset(queryset=Item.objects.none()) serial_formset = serialformset(queryset=Serial.objects.none()) if request.POST: form = InvoiceForm(request.POST) item_formset = itemformset(request.POST) serial_formset = serialformset(request.POST) if form.is_valid() and item_formset.is_valid() and request.user.is_superuser: invoice_obj = form.save(commit=False) invoice_obj.admin = request.user invoice_obj.save() data = { 'id':invoice_obj.id } for item in item_formset: item_obj = … -
infinite loop while overriding save method in Django
I want to override the save method in order to update quantity if the cart_item already exists insert new entry if the cart_item does not already exists but every time after the save method it gets stuck in infinite loop class Cart(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self) -> str: return str(self.id) class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE, related_name='items') product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() def __str__(self) -> str: return self.product.name def save(self, *args, **kwargs): try: cart_item = CartItem.objects.get(cart_id=self.cart.id, product_id=self.product.id) cart_item.quantity += self.quantity pprint(cart_item) cart_item.save() #after this line goes into infinite loop except CartItem.DoesNotExist: super().save(*args, **kwargs) #after this line goes into infinite loop pprint("-------------------------here") `` -
Django Celery with Redis Issues on Digital Ocean App Platform
After quite a bit of trial and error and a step by step attempt to find solutions I thought I share the problems here and answer them myself according to what I've found. There is not too much documentation on this anywhere except small bits and pieces and this will hopefully help others in the future. Please not that this is specific to Django, Celery, Redis and the Digital Ocean App Platform. This is mostly about the below errors and further resulting implications: OSError: [Errno 38] Function not implemented and Cannot connect to redis://...... The first error happens when you try run the celery command celery -A your_app worker --beat -l info or similar on the App Platform. It appears that this is currently not supported on digital ocean. The second error occurs when you make a number of potential mistakes. -
How to calculate sums and multiplications in a django formset without using javascript?
I am a newbie in django and more in javasript, the question is that I am trying to do calculations in my formset with javascript but it does not come out, is there any way to do addition and multiplication in django formsets in an easier way? -
local variable 'verify_payment' referenced before assignment
i;m having the local variable renfrenced before assign and i have tried a lot of ways that i can use to fix this. any help would be greatly appreciated let me show some code views.py (the error after the top of the second if statement) def call_back_url(request): reference = request.GET.get('reference') # We need to fetch the reference from PAYMENT check_pay = PayHistory.objects.filter(paystack_charge_id=reference).exists() if check_pay == False: # This means payment was not made error should be thrown here... print("Error") else: payment = PayHistory.objects.get(paystack_charge_id=reference) # We need to fetch this to verify if the payment was successful. def verify_payment(request): url = 'https://api.paystack.co/transaction/verify/'+reference headers = { 'Authorization': 'Bearer '+settings.PAYSTACK_SECRET_KEY, 'Content-Type' : 'application/json', 'Accept': 'application/json', } datum = { "reference": payment.paystack_charge_id } x = requests.get(url, data=json.dumps(datum), headers=headers) if x.status_code != 200: return str(x.status_code) results = x.json() return results initialized = verify_payment(request) if initialized['data']['status'] == 'success': PayHistory.objects.filter(paystack_charge_id=initialized['data']['reference']).update(paid=True) new_payment = PayHistory.objects.get(paystack_charge_id=initialized['data']['reference']) instance = Membership.objects.get(id=new_payment.payment_for.id) sub = UserMembership.objects.filter(reference_code=initialized['data']['reference']).update(membership=instance) user_membership = UserMembership.objects.get(reference_code=initialized['data']['reference']) Subscription.objects.create(user_membership=user_membership, expires_in=dt.now().date() + timedelta(days=user_membership.membership.duration)) return redirect('subscribed') return render(request, 'payment.html') def subscribed(request): return render(request, 'subscribed.html') traceback System check identified 1 issue (0 silenced). November 26, 2021 - 18:50:42 Django version 3.2.9, using settings 'dexxapikprj.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Error Internal … -
Google App Engine Django Project Infinite Loading and error 500 does not raise any error in logs
Im am trying to deploy a Django project on Google Cloud App Engine. I deployed my app using the command gcloud app deploy. As I try to load the page in my browser, there is an infinite loading until the page finally returns a "Server 500 Error". I decited then to see if there is something weird in the logs by executing gcloud app logs tail but it does not raise any type of error, this is what i get. 2021-11-26 17:38:31 default[version_code] [2021-11-26 17:38:31 +0000] [11] [INFO] Starting gunicorn 20.1.0 2021-11-26 17:38:31 default[version_code] [2021-11-26 17:38:31 +0000] [11] [INFO] Listening at: http://0.0.0.0:5432 (11) 2021-11-26 17:38:31 default[version_code] [2021-11-26 17:38:31 +0000] [11] [INFO] Using worker: sync 2021-11-26 17:38:31 default[version_code] [2021-11-26 17:38:31 +0000] [16] [INFO] Booting worker with pid: 16 This is my Python Django settings.py: if os.getenv('GAE_APPLICATION', None): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': 'cloudsql/<my-google-cloudsql-connection-string>', 'NAME': 'database_name', 'USER': 'username', 'PASSWORD': 'password', 'PORT': '5432', } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } This is my app.yaml file: runtime: python39 env: standard app_engine_apis: true handlers: - url: /static static_dir: static/ - url: /.* script: auto entrypoint: gunicorn -b :5432 NG.wsgi I also get this … -
Django MANAGERS and ADMINS settings, do we need it configured?
I know ADMINS can be used to receive error notifications on email Something that can be better handled by datadog or sentry For manager seems to be something even more specific, since you need t use BrokenLinkEmailsMiddleware as well # MANAGER CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#admins ADMINS = [ ("Admin", "admin@mail.com"), ] # See: https://docs.djangoproject.com/en/dev/ref/settings/#managers MANAGERS = ADMINS Does it have any other purpose? Any reason to keep it on the Django settings? -
insert data through django automatically
I have made crawler and I want to link it with my django app so i can see this data in admin panel , but my problem is I do not know how do I insert crawled data automatically to django database. -
python Django middleware to check license. How to avoid code cracking
I wanted to have a license key to use the django application I am creating a signed file using pub and private keys This singed file will contain the details of the license, like username, date of expiry, version number etc. One after purchasing the software they will download the signed file. They have to place the file at a location mentioned Basically i will have a middleware in the Django which will read the signed file and it also has the pubkey. Using that it will verify the signed document, and if it passes, then checked the expiry date and allow to continue class CheckDate: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. response = self.get_response(request) # Code to be executed for each request/response after # the view is called. current_date = datetime.datetime.now() pub_key = "key is passed here" allowed_date = get from signed document the expiry date if current_date < allowed_date: return response else: #return render(request, 'licence_expired.html') return HttpResponse(json.dumps({"message":f"License Expired on {allowed_date}"}),content_type='application/json',status="401") return response Now using nuitka i am trying to obfuscate the code of … -
Django: how store multiple data types to the same model field
I want to create a database model somewhat similar to the example below: The idea is that User (or any model) can have multiple different features (or whatever) with different values. Feature can be anything, for example integer (salary), date (birthdate), or multiple selection (competences like C, Python, etc.). To keep the database design simple, I've tried an approach where I have only one Feature table which has optional choices via Choice table, instead of having separate database table for each feature type. User selection for feature value is stored to a User_has_Feature table "value" field, which is a CharField which can store multiple different data types, like integer, date, choice, multiple choice etc. My question is, how can I validate all data so that it validates against the field data type, and also shows everything correctly in admin or UI (having different UI widgets for different types)? I've tried an approach where I store the field type for each feature to Field table, which can be CharField, IntegerField, DateField, etc. Then in User_has_Feature model clean() I can dynamically validate against the field type, for example: FIELDS = { 'DateField': DateField, 'IntegerField': IntegerField, etc. } def clean(self): class_ = FIELDS.get(self.feature.field) … -
Django: Group and then Calculate the Sum of the column values through query
I have a model: bill_status_choice = ( ('Paid','Paid'), ('Pending','Pending'), ('Partially Paid','Partially Paid'), ) class Bill(models.Model): company_name = models.ForeignKey(Contact, on_delete=models.CASCADE) grand_tot = models.DecimalField(max_digits=9, decimal_places=2) status = models.CharField(max_length=100, choices=bill_status_choice) ... which has a fk to: class Contact(models.Model): associated_company = models.CharField(max_length=100) ... In my Views.py ... from bills.models import Bill from django.db.models import Sum def home(request): total = Bill.objects.filter(status='Paid').aggregate(Sum('grand_tot'))['grand_tot__sum'] context = { 'total':total, } return render(request, 'home.html',context) The problem: I am using charts.js in my front end template and I am trying to display a chart in which as a user creates new company names the chart should display the total amount grouped by company names how would I achieve that? eg: I create two invoices for "xyz" company with amounts: $100 & $200 || & create one invoice for "abc" company with amount $100 I want the chart to group the "xyz" invoice amounts and display $300 (ie:100+200) || & "abc" = $100 FYI I'm aware I'm using something completely wrong in the view function but its just something that I tried. Thanks -
How do I implement a login system in Django with GRPC?
I read GRPC documentations but it was not clear for me: How do I implement a registration form and then login with username and password? In JWT requests (REST) we always send the token with each request, but what is authentication in GRPC? -
Any way to figure out the reverse chain of Django relationship string?
Imagine you have a valid model relation string b__c__d__e for some model modelA, so that,say, the expression ModelA.objects.filter(b__c__d__e__in=[...]) is valid. My goal is to come up with a sort of "reverse" string which defines the "path" of relation from ModelE to ModelA. Is there any built-in way to do that? I am going to write such a function myself. But before dwelving into that, I wonder if there's any built-in way to do that. -
TypeError: Cannot read properties of undefined (reading 'params') when using match.params.id to fetch json data React Django rest API
I am trying to access specific data from my django backend based on using the unique id in the url for my react app on the frontend. I expect to see the body of the journal Instead i get this error: TypeError: Cannot read properties of undefined (reading 'params') I tried to use, 'useParams' instead but it lead to more errors. I also found similar questions on SO but they mentioned using 'props', is this the method i should be attempting instead? my App.js import { BrowserRouter, Routes, Route, Router, } from "react-router-dom"; import './App.css'; import Header from './components/Header' import JournalDashboard from './pages/JournalDashboard' import JournalPage from './pages/JournalPage' function App() { return ( <div className="App"> <BrowserRouter> <Header /> <Routes> <Route path="/" exact element={<JournalDashboard/>}></Route> <Route path="/journals/:id" element={<JournalPage/>} ></Route> </Routes> </BrowserRouter> </div> ); } export default App; my JournalPage.js import React, { useState, useEffect } from 'react' const JournalPage = ({ match }) => { let journalId = match.params.id let [journal, setJournal] = useState(null) useEffect(() => { getJournal() }, [journalId]) let getJournal = async () => { let response = await fetch(`/api/journals/${journalId}/`) let data = await response.json() setJournal(data) } return ( <div> <p>{journal?.body}</p> </div> ) } export default JournalPage Thanks in advance -
Django - show and verify email domains in registration form
I am using crispy forms to display the registration form and I have an issue with label_suffix in my form because it is not showing in the register.html file. When I change {{form|crispy}} to {{form}} then I can see it. Could you please tell me what am I doing wrong? Moreover, I'd like to limit the email domains that my registration system will accept and I want to check if the email is @companyname.com, @companyname2.com, @companyname3.com and it will accept only these emails in the registration process. Could you please tell me how can I do it? register.html <form method="post" novalidate> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-secondary">Register</button> </form> views.py class SignUpView(View): form_class = SignUpForm template_name = 'user/register.html' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False # Deactivate account till it is confirmed user.save() current_site = get_current_site(request) subject = 'Activate Your Account' message = render_to_string('user/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) messages.success(request, ('Please Confirm your email to complete registration.')) return redirect('login') return render(request, self.template_name, {'form': form}) forms.py TRUSTED_EMAILS = ['@companyname.com','@companyname2.com', …