Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, PIL: No such file or directory
I am working on a django project with the face-recognition library, but I get this error: Traceback (most recent call last): ... File "/.../site-packages/rest_framework/views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "/.../views.py", line 51, in post test_1 = face_recognition.load_image_file(path_) File "/.../site-packages/face_recognition/api.py", line 86, in load_image_file im = PIL.Image.open(file) File "/.../site-packages/PIL/Image.py", line 2878, in open fp = builtins.open(filename, "rb") FileNotFoundError: [Errno 2] No such file or directory: 'http://127.0.0.1:8000/media/profile_pics/me.jpg' This is what I have: req_user = Profile.objects.all().filter(user__username=user_) req_img = req_user.values('image')[0]['image'] #.partition("/")[2] path_ = 'http://127.0.0.1:8000/media/'+req_img test_1 = face_recognition.load_image_file(path_) test_1_enc = face_recognition.face_encodings(test_1)[0] test_2 = face_recognition.load_image_file(newimage) test_2_enc = face_recognition.face_encodings(test_2)[0] results = face_recognition.compare_faces([test_1_enc],test_2_enc) if results[0]: print('Match') else: print('Please login with your password') The image is located at path_ Thank you for any suggestions -
How can I serialize ManyToManyField in django?
I want to make a post model and show the person who clicked like. So after creating models and serializers, the server runs and the following error occurs. TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use liker.set() instead. I think the error occurred during the serialization of ManyToManyField, but I don't know the solution. How can I implement the features I want? Here is my code. models.py class post (models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='authorName', null=True) title = models.CharField(max_length=40) text = models.TextField(max_length=300) image1 = models.ImageField(blank=True, null=True) image2 = models.ImageField(blank=True, null=True) image3 = models.ImageField(blank=True, null=True) image4 = models.ImageField(blank=True, null=True) image5 = models.ImageField(blank=True, null=True) like = models.IntegerField(default=0) liker = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='liker', blank=True) tag1 = models.CharField(max_length=20, null=True) tag2 = models.CharField(max_length=20, null=True) tag3 = models.CharField(max_length=20, null=True) tag4 = models.CharField(max_length=20, null=True) tag5 = models.CharField(max_length=20, null=True) class comment (models.Model) : author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) post = models.ForeignKey(post, on_delete=models.CASCADE) text = models.TextField(max_length=200) class view (models.Model) : post = models.ForeignKey(post, on_delete=models.CASCADE) viewCnt = models.IntegerField(default=0) serializers.py class commentSerializer (serializers.ModelSerializer) : class Meta : model = comment fields = ['author', 'text'] class viewSerializer (serializers.ModelSerializer) : class Meta : model = view field = ['viewCnt'] class postSerializer (serializers.ModelSerializer) : author = serializers.CharField(source='author.username', read_only=True) image1 … -
Access Token Matching Query Does Not Exist, django + OAUTH
I have the following code I am trying to test: def customer_add_order(request): """ params: access_token restaurant_id address order_details(json format), example: [{"meal_id": 1, "quantity":2}, {"meal_id": 2, "quantity":3}] stripe_token return: {"status": "success"} """ if request.method == "POST": #Get token access_token = AccessToken.objects.get(token = request.POST.get("access_token"), expires__gt = timezone.now()) #Get profile customer = access_token.user.customer # Check if customer has a order that is not delivered if Order.objects.filter(customer = customer).exclude(status = Order.DELIVERED): return JsonResponse({"status": "fail", "error": "Your Last Order must be completed"}) # Check Address if not request.POST("address"): return JsonResponse({"status": "failed", "error": "Address is required."}) # Ger Order Details order_details = json.load(request.POST["order_details"]) order_total = 0 for meal in order_details: order_total += Meal.objects.get(id = meal["meal_id"]).price * meal[quantity] if len(order_details)>0: # Step 1 - Create an Order order = Order.objects.create( customer = customer, restaurant_id = request.POST["restaurant_id"], total = order_total, status = Order.PENDING, address = request.POST["address"] ) # Step 2 - Create Order details for meal in order_details: OrderDetails.objects.create( order = order, meal_id = meal["meal_id"], quantity = meal["quantity"], sub_total = Meal.objects.get(id = meal["meal_id"]).price * meal["quantity"] ) return JsonResponse({"status": "success"}) I enter the params in Postman, and use an access token that shows valid in django, and it hasn't expired. I am using the rest framework and the function … -
HTML page or JSON object as response of single API depending on the type of incoming request
I'm planning to create a service with Django which can serve REST APIs and a web application. Right now I'm in a situation where a function needs to send JSON in response if called from another application and should serve HTML page with the same JSON rendered if requested from a web browser. Is it possible to differentiate the incoming request type and return response accordingly in Django? Thanks in advance. -
User Level Registration in Django
I am trying to create two user levels in Django. When they register, they will see a dropdown field where they can choose whether they are a customer or a driver. models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_customer = models.BooleanField(default=False) is_driver = models.BooleanField(default=False) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) address = models.CharField(max_length=300) contact_no = models.CharField(max_length=11) profile_pic = models.ImageField(blank=True, null=True) def __str__(self): return self.user.username views.py def RegisterPage(request): form = RegisterForm() if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): form.save() context = {'form':form} return render(request, 'accounts/register.html', context) forms.py from django.contrib.auth.forms import UserCreationForm from .models import * from django import forms from django.db import transaction class RegisterForm(UserCreationForm): email = forms.EmailField() first_name = forms.CharField(max_length=60) last_name = forms.CharField(max_length=150) address = forms.CharField(max_length=300) contact_no = forms.CharField(max_length=11) profile_pic = forms.ImageField(required=False) LEVELS = ( ('Customer', 'Customer'), ('Driver', 'Driver'), ) user_level = forms.ChoiceField(choices=LEVELS) class Meta(UserCreationForm.Meta): model = User fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2', 'address', 'contact_no', 'profile_pic', 'user_level'] @transaction.atomic def save(self, commit=True): user = super().save(commit=False) level = self.cleaned_data.get('user_level') if level == 'Customer': user.is_customer = True if commit: user.save() elif level == 'Driver': user.is_driver = True if commit: user.save() profile = Profile.objects.create(user=user) profile.address = self.cleaned_data.get('address') profile.contact_no = self.cleaned_data.get('contact_no') profile.profile_pic = self.cleaned_data.get('profile_pic') profile.save() … -
How to build a Selenium Chrome extension and Django?
Is there a way to build a scraper with Django but instead of using Selenium, could it use a Chrome extension? I want anybody could use a scraper in my website, but instead of install selenium on pc, only download a chrome extension and done. How could I do that? Thank you so much for your help! -
Preventing duplicate XMLHttpRequests in Django
In my app, clicking a button sends a XHR request to my server to upgrade an account and charge the user. def upgradeView(request): if request.user.upgraded == False: billAccount(request.user.id) else: return HttpRequests('Already billed') request.user.upgraded = True request.user.save() return HttpResponse('OK!') I can alter the button using Javascript so that it will be disabled after the user clicks it once. How can I confirm on the server side that the user can't submit 5 XHR requests simultaneously and end up getting billed 5 times? I have a manual check, checking whether they have already been billed, but what if the billAccount function takes a few seconds, and multiple requests are able to trigger the billAccount call before the user is able to be set as upgraded? The more I think about it, the more it seems impossible prevent multiple requests sliding in. Even if the billAccount call is a milisecond, that's still enough time for multiple requests to come in. -
Deploying Django App to Heroku Cant load Staticfiles
I have successfully deployed my django app to heroku. but for some reason, they cant load the templates and staticfiles. my directories are as such: eximia (project directory) eximia: init.py asgi.py settings.py wsgi.pyurls.py web: templates, static: web: style.css, images: (all the images are in this folder) and the rest of the files are normal typical django app files. my settings.py are as follows: Django settings for eximia project. Generated by 'django-admin startproject' using Django 3.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve(strict=True).parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'sy4a^dk+1%2!g2@4s$2ihk0^9%!9or&+ycy2#0a^*qqhdksk#t' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [ "eximia-denim.herokuapp.com" ] # Application definition INSTALLED_APPS = [ 'web', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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 = 'eximia.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': … -
serializing image data from diffrent fields
From my little knowledge on how serializers works, i know we mostly use modelserializers, and for that we would have a model for all we want to serialize but how can i join all the images in the different models and then serialize These are my models class Vendors(models.Model): title = models.CharField(max_length=50, blank=False) image = models.ImageField(upload_to='static/vendors', blank=True, null=True) class Riders(models.Model): title = models.CharField(max_length=50, blank=False) image = models.ImageField(upload_to='static/riders', blank=True, null=True) class VendorsRiders(models.Model): VendorImg = models.ForeignKey(Vendors, on_delete=models.CASCADE) RiderImg = models.ForeignKey(Riders, on_delete=models.CASCADE) This is my serializer Class VendorsRidersSerializers(models.Model): Class Meta: model = VendorsRiders fields = '__all__' Please I am a lerner in DRF, when i tried this i didn't thee required result i had in mind, WHICH BASICALLY WAS TO GET ALL THE IMAGES TO THE ENDPOINT I WOULD SPECIFY -
Django does not catch the requests from Traefik
I recently configured traefik to manage my subdomains and their certificates (LetsEncrypt). So currently there are three services: traefik itself, nginx (for handling static files, not yet fully configured) and django. All these services work fine and without errors. But I have bad luck with the communication between traefik and my django app. In the following I show you my project folder structure and the configuration files, it would be great if someone could help. . ├── proxy │ ├── acme.json │ ├── docker-compose.yml │ └── traefik.toml └── services ├── django │ ├── docker-compose.yml │ ├── Dockerfile │ ├── example │ │ ├── asgi.py │ │ ├── __init__.py │ │ ├── settings │ │ │ ├── base.py │ │ │ ├── dev.py │ │ │ ├── __init__.py │ │ │ └── prod.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── manage.py │ ├── media │ ├── Pipfile │ ├── Pipfile.lock │ ├── scripts │ │ ├── entrypoint.sh │ │ └── entrypoint.sh_backup │ └── staticfiles └── nginx ├── default.conf └── docker-compose.yml # cat proxy/traefik.toml [accessLog] [log] level = "INFO" [api] dashboard = true insecure = false [providers] [providers.docker] exposedByDefault = false watch = true network = "web" [entryPoints] [entryPoints.web] … -
How to send a custom message as a sms using Twilio with django-two-factor-auth
Currently django-two-factor-auth package sends a default message Your Twilio security code is 1231230 . I would like to customize this text except the 7 digit different/dynamically generated code. -
How to use mysql dump with django?
I am new to both django and mysql, I am given a mysql dump file that will be used in a django app. I created a new database and restored the dump file into that using mysqldump. Now I am lost about how to use both of them together. Please help. -
How to integrate coinbase commerce Webhook API in Django
I am trying to integrate Coinbase Commerce Webhook API in my Django App; but it seems am doing things in the right way. I have searched the web for more than 2 days but no solution available for this. Coinbase commerce official documentation did not provide way to integrate this in Django. Please your help will be appreciated. This is what I have tried; but keep on throwing an error. from django.conf import settings from django.views.decorators.csrf import csrf_exempt from coinbase_commerce.error import WebhookInvalidPayload, SignatureVerificationError from coinbase_commerce.webhook import Webhook from django.http import HttpResponse import json WEBHOOK_SECRET = settings.COINBASE_SECRET @csrf_exempt def payment_webhook(request): request_data = request.data.decode('utf-8') request_sig = request.headers.get('X-CC-Webhook-Signature', None) try: event = Webhook.construct_event(request_data, request_sig, WEBHOOK_SECRET) except (WebhookInvalidPayload, SignatureVerificationError) as e: return HttpResponse(e, status=400) print("Received event: id={id}, type={type}".format(id=event.id, type=event.type)) return HttpResponse('ok', status=200) -
Erro chave estrangeira django
estou tentando adicionar um saldo, meta, gastos e descrição em um usuario logado, mas a foreign key não está funcionando quando envio os dados lá pelo template. os dados são salvos no banco de dados mas não registra a fk.aqui está a views.py template models.py aqui está o erro. o campo user_id fica NULL -
How can I fix no module named blog?
After creating a django_project, I right click the project name and choose open in terminal. I was able to run the server using python manage.py runserver. Now after creating a blog app in the project using python manage.py startapp blog, I tried to run the server again but it did not work. The following error message pops up: File "C:\Users\Sam Iam \AppData\Local\Programs\Python\Python38-32\lib\importlib_init_.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'blog.urls' How can that module be found? -
how to provide only bold option for django textField
I am working on django project where it has a model called slide that includes textField. model.py file this is a picture for the model.py file. I am trying to provide only "bold" option to edit the text of the content field. All text editors that i have tried (such as summernote and ckeditor) provide a lot of options (bold, italic,...) while i need only bold. -
Docker - make my application use secrets instead of env. vars
My Django application uses at lot of environment variables, around 35 in total. Currently all these are handeld by a .env file that I source before I start my application stack. I guess that I don't have to point out that this is by far a very insecure way especially if it's about secret key's in production ... Now my problem is that I don't really understand how to make the switch from a .env file to secrets, as I don't understand how to process the secrets at my container. For example, Django uses a connection string to connect with my MySQL database, see below: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", }, 'NAME': env.str('MYSQL_DB'), 'USER': env.str('MYSQL_USER'), 'PASSWORD': env.str('MYSQL_PWD'), 'HOST': env.str('MYSQL_HOST'), 'PORT': env.str('MYSQL_PORT'), } } Most of the time I use "env.str" to fetch my vars that I pass to the container at start. So how can I make my Django application work with docker secrets and if possible stay with fetching vars the way like shown above? Is it maybe possible to load all needed vars on start at my docker-entrypoint.sh, and if yes, how can this be accomplished? I already came acorss this … -
Trying to add new row to sqlite table using Django. Getting Integrity error message
Scratching my head trying to figure out what I'm doing wrong. I am trying to retrieve data from an input field on my website and insert it into a sql table. When i click the submit button on my website I keep getting this error NOT NULL constraint failed:auctions_bid.listing_id_id What is causing this? any help is very much appreciated. Thanks I've attached my models.py, views.py and html pages below for additional context. Models.py class User(AbstractUser): pass class Category(models.Model): category_id = models.AutoField(primary_key=True) category_name = models.CharField(max_length=100) def __str__(self): return f"{self.category_name}" class Auction_listing(models.Model): listing = models.AutoField(primary_key=True) user_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name="listings") start_price = models.IntegerField() product_name = models.CharField(max_length=50) prod_description = models.CharField(max_length=350) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="bids") list_img = models.ImageField(null=True, blank=True) def __str__(self): return f"{self.user_id}: {self.product_name} ${self.start_price}" class Bid(models.Model): bid = models.IntegerField() user_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_bids") listing_id = models.ForeignKey(Auction_listing, on_delete=models.CASCADE, related_name="all_bids") class Comments(models.Model): comment = models.CharField(max_length=500) user_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_comments") listing_id = models.ForeignKey(Auction_listing, on_delete=models.CASCADE, related_name="all_comments") views.py def listing(request, listing): #Find user id current_user = request.user new_bid = '' bid_count = Bid.objects.filter(listing_id=listing).count() #Gets the max bid for a particular listing in dictionary form max_bid = Bid.objects.filter(listing_id=listing).aggregate(Max('bid')) #Gets value of the bid__max key max = max_bid['bid__max'] #Get all objects for particular listing page_listing = Auction_listing.objects.get(pk=listing) … -
Communication between discord bot and web server
I am making a python project which involves communication between a Discord bot and a Django web server. Essentially the bot would ask the web server for a temporary URL which will then be sent to the Discord user. Not being an expert on the subject, I have no idea what to use for the communication between the discord bot and the web server. Can anyone give me some suggestions? Thanks in advance -
how to show relation(ManyToManyField) in html
I have traped show relation post by ManyToManyField python3 / django3.1 models.py class Post(models.Model): title = models.CharField(max_length=10) relation = models.ManyToManyField('self', blank=True) there is 3 posts post.title = [title1, title2, title3] title1 related [title1, title2, title3] index.html {% for p in post %} <p>{{ p.title }} </p> <p>{{ p.relation.all }}</p> {% endfor post %} the result is title1 <QuerySet [<Post: title1 >]> My question is how do I show all relation in {{ p.relation.all }} ? and I would like to remove this[ <QuerySet ] in html thank you for reading. -
heroku deployment for django react
I followed this precisely https://librenepal.com/article/django-and-create-react-app-together-on-heroku/ when I do git push heroku master everything succeeds. When I do heroku open it just takes me to application error page 2020-08-28T23:42:53.936006+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=loadedwhat.herokuapp.com request_id=6c4c0602-4239-4b39-a428-88796437ddfd fwd="73.15.209.31" dyno= connect= service= status=503 bytes= protocol=https 2020-08-28T23:42:55.130985+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=loadedwhat.herokuapp.com request_id=61ab916b-8f79-4fff-bc0a-6583b96bd757 fwd="73.15.209.31" dyno= connect= service= status=503 bytes= protocol=https 2020-08-28T23:42:58.478573+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=loadedwhat.herokuapp.com request_id=6c70af08-0509-4c6d-a156-c1794b26b619 fwd="73.15.209.31" dyno= connect= service= status=503 bytes= protocol=https 2020-08-28T23:42:58.681158+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=loadedwhat.herokuapp.com request_id=45ca19c4-4463-4b70-8615-5bc29b1e71e6 fwd="73.15.209.31" dyno= connect= service= status=503 bytes= protocol=https 2020-08-28T23:42:59.789188+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=loadedwhat.herokuapp.com request_id=6ae32d53-7abd-44f8-b480-f3acc22f7b27 fwd="73.15.209.31" dyno= connect= service= status=503 bytes= protocol=https 2020-08-28T23:42:59.994456+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=loadedwhat.herokuapp.com request_id=d4e6b599-51f5-445b-a153-5b314e11d095 fwd="73.15.209.31" dyno= connect= service= status=503 bytes= protocol=https 2020-08-28T23:43:24.120340+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=loadedwhat.herokuapp.com request_id=7410e150-adfa-4be8-80d9-821415f55f50 fwd="73.15.209.31" dyno= connect= service= status=503 bytes= protocol=https 2020-08-28T23:43:24.430225+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=loadedwhat.herokuapp.com request_id=9ad8bc02-2811-459d-8c35-1a9cdce4248e fwd="73.15.209.31" dyno= connect= service= status=503 bytes= protocol=https 2020-08-28T23:43:25.778014+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=loadedwhat.herokuapp.com request_id=678c2225-3fb8-42c5-8f5b-ee83792f7d94 fwd="73.15.209.31" dyno= connect= service= status=503 bytes= protocol=https 2020-08-28T23:43:25.983635+00:00 heroku[router]: … -
GraphQL query isn't refreshed with graphene-django
Here's my schema definition: class TemperatureRecordType(DjangoObjectType): unit = graphene.String() class Meta: model = TemperatureRecord fields = ("timestamp", "value") def resolve_unit(parent, info): return "Celcius" class Query(graphene.ObjectType): currentTemperature = DjangoListField(TemperatureRecordType) schema = graphene.Schema(query=Query) Query is : { currentTemperature{ timestamp value unit } } There's only one entry in TemperatureRecord, with value and timestamp changed by a management command every second running the refresh method in my model's class : class TemperatureRecord(models.Model): timestamp = models.DateTimeField(default=now) # Last time temperature value changed value = models.IntegerField(default=get_random_temperature_value) # Value to be changed every second, always in Celcius def refresh(self): # Updates entry's temperature value and timestamp self.value = get_random_temperature_value() self.timestamp = now() self.save() Here's the management command : class Command(BaseCommand): help = 'Refreshes temperature record every second, indefinitely' def handle(self, *args, **options): while True: time.sleep(1) try: TemperatureRecord.objects.get().refresh() except TemperatureRecord.DoesNotExist: TemperatureRecord.objects.create() Django shell works fine and shows data changes every second, but Graphene always returns the same stale data, and only refreshes if I change my schema and save the file. Is there some sort of caching? What am I doing wrong? -
django model optimization, fields applicable on two Models
I question myself on how to create my models well. I have Project Model which contains multiple Control (and each Control is applicable on multiple Project). But each Control got specific attributes for the Project I mean, a Project can have 10 Controls, and each control Applicable can be "Applicable" or "Not Applicable" Status can be "Not Planned", "Planned", "Done" So I made this : class Project(models.Model): name = models.CharField(max_length=100) code = models.PositiveSmallIntegerField("code", null=True, blank=True) description = models.TextField(default="") class Control(models.Model): control_description = models.TextField() and a third Model for the links between Project / Control / Others class ProjectControl(models.Model): APPLICABLE_CHOICES = ( ("A","Applicable"), ("NA","Not Applicable"), ) STATUS_CHOICES = ( ("D","Done"), ("NP", "Not Planned"), ("P", "Planned") ) project = models.ForeignKey('Project', verbose_name="Project", on_delete=models.CASCADE) control = models.ForeignKey('Control', verbose_name="Controle", on_delete=models.CASCADE) applicable = models.CharField(max_length=100, null=True, choices=APPLICABLE_CHOICES) status = models.CharField(max_length=100, choices=STATUS_CHOICES) Is there a better (or more conventional) way to do this ? I'm just facing an issue when using API, if I want all applicable controls of a project, I have to parse the whole ProjectControl Table, and I think, if the project goes big, performance issues. I tried this to resolve the issue by using M2M Field: class Project(models.Model): controls = models.ManyToManyField("Control", related_name="controls", default="", null=True, … -
Receiving form with two input at once and saving them separately with Django
I am trying to separately save two inputs that i named as item1 and item2 to different forms. But it doesn't work when i use request.POST['item1'] I tried to use get('item1') and getlist('item1') but none of them worked. How can i do it or can i do it actually? My HTML <form class="form-inline my-2 my-lg-0" method="POST"> {% csrf_token %} <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="item1" > <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="item2" > <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> My Django file if request.method == 'POST': form1 = listForm(request.POST['item1']) form2 = listForm(request.POST['item2']) if form1.is_valid() and form2.is_valid(): form1.save() form2.save() -
Getting a POST request to act like a GET request? djangorestframework-datatables
I don't want to add data to the database, like what djangorestframework-datatables is trying to do with the POST request. I need to use a POST request instead of a GET request because the URI for the GET request is too long (I had to change nginx and gunicorn limits on the production server, to unlimited length (max wasn't enough) which opens the site up to ddos attacks, which is obviously not ideal. Here is the code: # api/serializers class ReportSerializer(serializers.ModelSerializer): class Meta: model = Report fields = "__all__" # api/views class ReportViewSet(viewsets.ModelViewSet): queryset = Report.objects.all() serializer_class = ReportSerializer # reports/models class Report(models.Model): contribution_expenditure_type = models.CharField(max_length=255, choices=CONTRIBUTION_EXPENDITURE_TYPES) filer_id = models.BigIntegerField() filer_namL = models.CharField(max_length=255) report_num = models.CharField(max_length=255) committee_type = models.CharField(max_length=255) rpt_date = models.CharField(max_length=255) from_date = models.CharField(max_length=255) thru_date = models.CharField(max_length=255) elect_date = models.CharField(max_length=255) rec_type = models.CharField(max_length=255) form_type = models.CharField(max_length=255, blank=True, null=True) tran_id = models.CharField(max_length=255, blank=True, null=True) entity_cd = models.CharField(max_length=255, blank=True, null=True) tran_namL = models.CharField(max_length=255) tran_namF = models.CharField(max_length=255, blank=True, null=True) tran_city = models.CharField(max_length=255, blank=True, null=True) tran_state = models.CharField(max_length=255, blank=True, null=True) tran_zip4 = models.CharField(max_length=255, blank=True, null=True) tran_emp = models.CharField(max_length=255, blank=True, null=True) tran_occ = models.CharField(max_length=255, blank=True, null=True) tran_self = models.CharField(max_length=255, blank=True, null=True) tran_type = models.CharField(max_length=255, blank=True, null=True) tran_date = models.CharField(max_length=255) tran_date1 = models.CharField(max_length=255, blank=True, null=True) …