Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Hello, what's the best way to create an ordering for model based on it's group category
I'm in a bit of a situation, I have Two models class Category(models.Model): title = models.CharFiels(max_length=200) def __str__(self): return self.title class Question(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=200) order = models.PositiveSmallIntegerField(default=0, editable=False) def __str__(self): return self.title ##Tried solution. For the above I decided to try using signals @receiver(pre_save, sender=Question) def pre_save_order_field(sender, instance, **kwargs): # get object before save, and +1 to the order field before save pass My problem is how to increment order field with respect to the current question group I'm doing input with django admin page. -
I can't load a Django template partial from a JQuery ajax call
I need to send a list from an ajax call using JQuery, and send a response with Django {{ variables }} inside them, I tried everything, but the JQuery always loads the entire current page instead of loading the html file that contains the template partial, which is just <!-- city_dropdown_list_options.html --> <option value="">----city list----</option> {% for city in cities %} <option value="{{ city.pk }}">{{ city.name }}</option> {% endfor %} Here's the template where the JQuery is located person_form.html {% extends 'base.html' %} {% load i18n %} {% load static %} {# NOTE: templates must be defined into a folder having the same name than the application, like here countries/person_list.html, because Django automatically search from <template_folder_in_app_folder/app_name/template.html #} {% block content %} <h2>{% trans "Person Form" %}</h2> <form method="post" novalidate> {% csrf_token %} <table> {{ form.as_table }} </table> <button type="submit">Save</button> <a href="{% url 'person_changelist' %}">Nevermind</a> </form> <div id="test"></div> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> {# <script src="{% static 'js/test.js' %}"></script> #} <script> $("#id_country").change(function (){ // getting the url of the load_cities view var url = $("#personForm").attr("data-cities-url"); // get the selected country id from the html element var countryId = $(this).val(); $.ajax({ url: url, data: { // adding the countryId to GET parameters 'country': countryId }, … -
Get image from django rest framework into react-native
I have an api in django that i use to get data into my react native application. I need to get the image for every article which only shows its id. like this { "id": 5, "title": "sdadasd", "author_name": "ibtsam", "image": [ 2 ], "author": 2, "published": "2021-09-13", "modified_on": "2021-09-13", "excerpt": "asdasda", "content": "dasdasdas", "status": "published" }, I need to know how can i get the image path in my react native application. My serializers.py class is as follow: from rest_framework import serializers from blog.models import Post from blog.models import Image from versatileimagefield.serializers import VersatileImageFieldSerializer from rest_flex_fields import FlexFieldsModelSerializer class ImageSerializer(FlexFieldsModelSerializer): image = VersatileImageFieldSerializer( sizes=[ ('full_size', 'url'), ('thumbnail', 'thumbnail__100x100'), ] ) class Meta: model = Image fields = ['pk', 'name', 'image', 'full_size'] class PostSerializer(FlexFieldsModelSerializer): author_name = serializers.CharField( source='author.username', read_only=True) class Meta: model = Post fields = ('id', 'title', 'author_name', 'image', 'author', 'published', 'modified_on', 'excerpt', 'content', 'status') expandable_fields = { 'image': (ImageSerializer, {'many': True}), } -
AWS w/nginx redirect to docker containers; getting bad gateway 502
The setup is a RHEL AWS instance. On this instance, nginx is installed and working. That means if I go to http://[root] I get the html in the nginx folder like I'm supposed to. If I go to http://[root]/[sub1] I also get the other html in the nginx folder like I'm supposed to. Now, http://[root]/[sub2] is a django server in a docker container. When runserver, the django app is listening on http://127.0.0.1:8000. My docker container translates :38000->:8000 via docker-compose.yml. My nginx.conf file looks like this: server { listen 80; root /usr/share/nginx/html; location / {} location /test { index text.html; alias /usr/share/nginx/html; } location /mod { proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Server $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect off; proxy_pass http://127.0.0.1:38000; } } While the root and /test (sub1) locations work, whenever I go to /mod (sub2), I get a 502 Bad Gateway. My docker-compose.yml (version 2) contains ports: 38000:8000. When I create the container, I use docker-compose run --name mod mod. Any suggestions? -
Problems with Django when trying to show error message when form insn't valid
Description In my applicattion i have a user registration form, but, when simulating not following the recommendations for form validation, i get an httpresponse error. But, what i'm trying to do is display an error message using the message framework from django Error page Code My template {% block body %} {% if messages %} {% for message in messages %} <div class="text-center alert alert-{{ message.tags }}"> {{ message|safe }} </div> {% endfor %} {% endif %} {% load crispy_forms_tags %} <form class = "" method="post" action="{% url 'registro' %}"> {% csrf_token %} {{registro_form|crispy}} <button class = "btn btn-primary" type="submit">Registrar</button> </form> {% endblock body %} My Form class NovoUsuarioForm(UserCreationForm): class Meta: model = User fields = ['first_name', 'last_name', 'email'] def save(self, commit = True): user = super(NovoUsuarioForm, self).save(commit=False) user.username = self.cleaned_data['first_name'] user.email = self.cleaned_data['email'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] if commit: user.save() return user My View class RegistroView(generic.View): def get(self,request, *args, **kwargs): return render(request, 'main/registro.html', {'registro_form': NovoUsuarioForm()}) def post(self,request, *args, **kwargs): form = NovoUsuarioForm(request.POST) if form.is_valid(): user = form.save() login(request,user) messages.success(request, "Registration successful." ) return HttpResponseRedirect(reverse('pesquisa')) messages.error(request, "Unsuccessful registration. Invalid information.") Other Info When i go back to the form page, from the error page after the post method, … -
GraphQL Variables 3 level
mutation CreateArticle( $id: ID!, $p: [AuthorInput] ) { article( id: $uuid p: $p ) { id } } Variable: { "id":1, "p": [{ "id":5, "x": [ { "id": 5 "text": "Text 1" }, { "id": 7 "text": "Text 2" }, ] }] } I still have an attachment in AuthorInput how do I write annotation in attachments? Arguments AuthorInput id ID! question [QuestionInput] Arguments QuestionInput id ID! text String -
Using Mask-RCNN with Flask and TF 2.5.0 rc3
Minimal repro with Flask. # app.py # run with: flask run from flask import Flask app = Flask(__name__) import tensorflow as tf import numpy as np from mrcnn import model as modellib from mrcnn.config import Config import cv2 class BaseConfig(Config): # give the configuration a recognizable name NAME = "IMGs" # set the number of GPUs to use training along with the number of # images per GPU (which may have to be tuned depending on how # much memory your GPU has) GPU_COUNT = 1 IMAGES_PER_GPU = 2 # number of classes (+1 for the background) NUM_CLASSES = 1 + 1 # Most objects possible in an image TRAIN_ROIS_PER_IMAGE = 100 class InferenceConfig(BaseConfig): GPU_COUNT = 1 IMAGES_PER_GPU = 1 # Most objects possible in an image DETECTION_MAX_INSTANCES = 200 DETECTION_MIN_CONFIDENCE = 0.7 def load_model_for_inference(weights_path): """Initialize a Mask R-CNN model with our InferenceConfig and the specified weights""" inference_config = InferenceConfig() model = modellib.MaskRCNN(mode="inference", config=inference_config, model_dir=".") model.load_weights(weights_path, by_name=True) # model.keras_model._make_predict_function() return model detection_model = load_model_for_inference("mask_rcnn_0427.h5") @app.route('/detect') def ic_model_endpoint(): image = cv2.imread('img.jpg') image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) results = detection_model.detect([image], verbose=1) print(results) @app.route("/") def hello_world(): return "<p>Hello, World!</p>" Using the fork at https://github.com/sabderra/Mask_RCNN, but you can't post issues there, so I figured I … -
How to enable https in Django using already exist key
For generating certificates i using openssl command. I'm run my django app on docker using nginx proxy.I'm new with this, therefore i read some article for lunching my app . This my defaulf.conf: upstream rancher { server api_django:8080; } map $http_upgrade $connection_upgrade { default Upgrade; '' close; } server { listen 443 ssl http2; server_name <my domain name> www.<my domain name>; ssl_certificate /etc/ssl/private/cert.pem; ssl_certificate_key /etc/ssl/private/key.pem; location / { proxy_set_header Host $host; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Port $server_port; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://rancher; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_read_timeout 900s; } } server { listen 80; server_name <my domain name> www.<my domain name>; return 301 https://$server_name$request_uri; } In seting.py i set such parameters: CSRF_COOKIE_SECURE = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') My docker-compose.yml version: '3.7' services: api_django: volumes: - static:/static env_file: - .env build: context: . ports: - "8000:8000" nginx: build: ./nginx volumes: - static:/static - /root/docker_ssl_proxy:/etc/ssl/private ports: - "80:80" - "443:443" depends_on: - api_django volumes: static: When i running my docker-compose nothing is changed -
OperationalError at /admin/my_app/users/- Django
i'm adding a picture of the error in django page (it happend after i put another line in models.py and did "pip install pillow", when i remove the line it works as usual) PLEASE TELL ME IF YOU WANT TO SEE MY CODE OR SOMETHING ELSE, BECAUSE THE REST WORKS FINE -
How to render foreignkey relationship in Django
I have a simple ManyToOne relationship where users can post comments to a poller object. Comments Model class Comments(models.Model): poller = models.ForeignKey(Pollers, on_delete=models.CASCADE, related_name='comments') created_on = models.DateTimeField(auto_now_add=True) comment = models.CharField(max_length=250) created_by = models.CharField(max_length=80) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.name) The View def single_poller(request, poller_id): """retrieves the item clicked by the user from DB and renders the single_poller template for further user interaction """ # Retrieve the item via get poller = Pollers.objects.get(poller_id=poller_id) # Increase the view field of the object by poller.poller_views += 1 # Save the changed instance and overwrite new view integer poller.save() # Get the form for comments form = CommentsForm context = { 'poller': poller, 'form': form } return render(request, 'pollboard/single_poller.html', context) Now I want to render the comments for each poller into my template like so <div id="comments-choice-one-wrapper" class="comments-wrapper"> {{ poller.comments.comment }} </div> Somehow it doesn't render the comment I created beforehand. I checked in Django admin if the comment is rly related to the poller and this looks just fine. -
Asking help for a user creation form validation
I'm working on a user creation form and I think I did everything right until I submit the form it does not save on the database. My views.py in creating the view and the user validation form. from journal.forms import CommentForm, CreateUserForm from django.contrib.auth.forms import UserCreationForm from .models import * def signup(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() context= {'form': form} return render(request, 'account/signup.html',context) forms.py the form handled with a widget connected to my static file, everything seems to be fine class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] widgets = { 'username': TextInput(attrs={ 'class': 'form-control', }), 'email': TextInput(attrs={ 'class': 'form-control', }), 'password1': TextInput(attrs={ 'class': 'form-control', }), 'password2': TextInput(attrs={ 'class': 'form-control', }), } -
how do i get the current username in my vieuw?
i am trying to get the username of the current user in my vieuw.py it will has to replace the fake_cur_user. and should insert the username tryed a whole lot but i cant find the right way. pls help import datetime from django.urls import reverse from django.views.generic import CreateView from odin.actie.actie import Actie from odin.actie.actie_styleformfields import styleFormFields from odin.medewerker.medewerker import Medewerker # noqa from project.settings.base import fake_cur_user class CreateActie(CreateView): template_name = "odin/actie/actie_aanmaken_form.html" model = Actie fields = '__all__' def get_success_url(self, **kwargs): return reverse("create_inzetlijst", kwargs={'pk': self.object.pk}) cur_user_yf = 0 cur_user_team = "" initial_gespreksgroep = "" cur_user_yf = fake_cur_user # TODO: fake server val vervangen door LDAP waarde - staat nu opgeslagen in base.py if not cur_user_yf == 0: try: cur_user_team = Medewerker.objects.values_list('team', flat=True).get(youforce=cur_user_yf) except: -
convert SQL create query to Django Model
I'm specifically having a problem with the following lines: `created_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), `updated_at` datetime(6) DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(6), Here is the full SQL query: CREATE TABLE `billing_package` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(200) NOT NULL, `start` datetime(6) NOT NULL, `expiry` datetime(6) DEFAULT NULL, `price` decimal(10,2) NOT NULL, `count` int(11) DEFAULT NULL, `created_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), `updated_at` datetime(6) DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(6), PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; Django Model class Package(models.Model): name = models.CharField(max_length=200, null=False) price = models.CharField(max_length=200, null=False) start = models.DateTimeField() expiry = models.DateTimeField(null=True) price= models.DecimalField(max_digits=10, decimal_places=2) count = models.IntegerField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.user After running migrations with Django, when i check the database, there is no default value for created_at and updated_at? How do i correctly do the following in a Django Model? `created_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), `updated_at` datetime(6) DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(6), -
Djongo and Django
Project Django and Djongo Model.py from djongo import models class Son(models.Model): name=models.CharField() last_name=models.CharField() class Master (models.Model) _id = models.ObjectIdField() son = models.EmbeddedField() objects = models.DjongoManager() Error -> return getattr(self, meta.pk.attname) AttributeError: 'NoneType' object has no attribute 'attname' help please -
Django (drf) add new parameters/fields only for output with existing queryset(used for output) from database
I am working on a project on drf, where I need to fetch data from database (in thousands), and display selective fields in response. models.py class TblDemo(models.Model): tbl_id = models.IntegerField() tbl_name = models.CharField(max_length=50) tbl_size = models.CharField(max_length=50) tbl_height = models.Charfield(max_length=50) tbl_material = models.Charfield(max_length=50) class Meta: managed = True db_table = 'tbl_demo' views.py class data_fetch(viewsets.ViewSet): get tbl_list(self, request, format=None) serializer = Tbl_Serializer_input(data=request.data) if serializer.is_valid(): queryset1 = tbl_name.objects.all() queryset2 = queryset1.filter(tbl_name=request.data.get("title")) serializer = Tbl_Serializer_output(queryset2, many=True) return Response(serializer.data) serializers.py class Tbl_Serializer_input(serializers.Serializer): title = serializers.CharField(required=True, max_length=50) refer_no = serializers.CharField(required=True, max_length=50) class Tbl_Serializer_output(serializers.Serializer): tbl_id = serializers.CharField(max_length=50) tbl_name = serializers.CharField(max_length=50) tbl_size = serializers.CharField(max_length=50) tbl_height = serializers.Charfield(max_length=50) output [ { "tbl_id":"1", "tbl_name":"white table", "tbl_size": "square", "tbl_height": "2 feet" }, { "tbl_id":"2", "tbl_name":"black table", "tbl_size": "square", "tbl_height": "3 feet" }, .......and so on. but now, requirement is that I can't change database/model, but need to add some more fields like ("refer_no", "material" and "density", which is overall same in every cases) and with every object in queryset, which will not be stored in database, but it is only for response/output. so, after adding new parameters my output will be like : where, "refer_no" is taken directly from input to show output fields. and "material" and "density" can't be added … -
Hi, please I am finding it difficult to pass a display form in my templates from views.py please any help would be highly appreciated
I have been trying to fix this error for days now and to no avail, i really need help on how to pass in the display the context in templates Views.py def registerView(request): if request.method == 'POST': form = UserRegisterForm(request.POST) p_reg_form = ProfileRegisterForm(request.POST) if form.is_valid() and p_reg_form.is_valid(): user = form.save() user.refresh_from_db() # load the profile instance created by the signal p_reg_form = ProfileRegisterForm(request.POST, instance=user.profile) p_reg_form.full_clean() p_reg_form.save() messages.success(request, f'Your account has been sent for approval!') return redirect('login') else: form = UserRegisterForm() p_reg_form = ProfileRegisterForm() context = { 'form': form, 'p_reg_form': p_reg_form } return render(request, 'stackusers/register.html', context) Forms.py class ProfileRegisterForm(forms.ModelForm): class Meta: model = Profile fields = ['city', 'state', 'country', 'referral'] models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') confirmed = models.BooleanField("Confirmed", default=False) city = models.CharField("City", max_length=50, blank=True) state = models.CharField("State", max_length=50, blank=True) country = models.CharField("Country", max_length=50, blank=True) referral = models.CharField("Referral", max_length=50, blank=True) def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) Register.html <form method="POST"> {% csrf_token %} {{context}} </form> -
Deploy django to elastic bean in production mode using WhiteNoise
I am trying to deploy my django app in debug=false condition using whitenoise but i am getting 502 Bad Gateway error.I don't understand what i am doing wrong so i need help with this subject. In the log, there is this error saying: /var/app/current/static/js/bootstrap.bundle.min.js.map" failed (2: No such file or directory), My settings file like this: import os from pathlib import Path import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration BASE_DIR = Path(__file__).resolve().parent.parent sentry_sdk.init( dsn="***", integrations=[DjangoIntegration()], traces_sample_rate=1.0, SECRET_KEY = 'secret-key' DEBUG = False; ALLOWED_HOSTS = [ '127.0.0.1', 'localhost', 'www.gamehunterz.com', 'gamehunterz.com' ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'games', 'authapp', 'crispy_forms', 'django.contrib.sitemaps', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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 = 'newgamehunterz.urls' STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['newgamehunterz/templates'], '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', 'newgamehunterz.context_processors.neceseeary', 'newgamehunterz.context_processors.fav_games', ], }, }, ] WSGI_APPLICATION = 'newgamehunterz.wsgi.application' X_FRAME_OPTIONS = 'SAMEORIGIN' AUTH_USER_MODEL = 'authapp.User' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '***', 'USER':'***', 'PASSWORD':'***', 'HOST':'***', 'PORT':'***', } } 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', }, … -
How to directly sign up user in allauth django with google?
I use allauth django so that I can log into the site in one click. I don't really understand how: save the user's email as a login automatically register a user and log him in with a redirect to the desired page. Django takes me to social / signup, where I have to click the signup button, only then everything works. How do I register a user without this page? -
null value in column "id" of relation "survey_surveyuser" violates not-null constraint
I'm trying to deploy a django and postgres app to heroku. when i change the postgres credintial to the heroku postgres credintial and try to submit a data this error appears: null value in column "id" of relation "survey_surveyuser" violates not-null constraint my views: def Signin(request): form = SigninForm() if request.method == 'POST': form = SigninForm(request.POST) if form.is_valid(): user = form.save() return redirect('user', pk = user.id) models: class SurveyUser(models.Model): name = models.CharField(max_length = 60) email = models.EmailField(max_length = 255) phone = models.CharField(max_length = 60) def __str__(self): return self.name -
django.core.exceptions.ImproperlyConfigured: Set the DATABASE_URL environment variable
I get this error when I try to run py manage.py runserver in pycharm terminal. I am trying to use Docker for the first time in one of the Django projects. I cloned the project and installed Docker and docker-compose successfully. Then I did the following commands in my root folder. docker-compose -f local.yml build docker-compose -f local.yml up Everything went well and all the packages got installed and all the migrations were applied too. I can see both my django and postgre running in the docker desktop. Now when I went to pycharm terminal and try to run localhost through runserver, I got above error. It is not able to find my db_url. My base.py in settings folder: DATABASES = {"default": env.db("DATABASE_URL")} DATABASES["default"]["ATOMIC_REQUESTS"] = True My entrypoint in production folder: export DATABASE_URL="postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}" Although the db_url is not defined in files inside env folder, it is exported in entrypoint in prod folder and I think that should work, but it is not working. My rootfolder looks like this: -
Annotated value gives None, need 0
order_list_cases =(order_list.values('user_id').annotate(dcount=Count('user_id'),customer_paid_sum=(Sum('invoice__transaction_invoice__transaction_amount')) In this code, the customer_paid_sumis returning None, I want to give it as 0 if it is None. I tried else case along with it but didn't work. -
Django-admin filter button
I am trying to create an admin page in Django for my Video model. The view is quite simple, all I want to do view and filter video records based on dropdown and datetime filters. Here is my code. from django.contrib import admin from django_admin_listfilter_dropdown.filters import DropdownFilter from rangefilter.filters import DateTimeRangeFilter @admin.register(Video) class VideoAdmin(admin.ModelAdmin): list_display = ('file_hash', 'file_path', 'height', 'width', 'frames', 'camera_model' 'created_at') list_filter = ( ('frames', DropdownFilter), ('created_at', DateTimeRangeFilter), ('height', DropdownFilter), ('width', DropdownFilter), ('camera_model', DropdownFilter), ) search_fields = ('file_hash', 'file_path', 'model',) The solution works well for reasonable amount of records. However, it becomes very slow when the records saved on db increase significantly (~1M). When filtering with multiple criteria, one has to: Filter by frames Wait for the new response Filter by camera_model Wait again And so on.. Is there a way to trigger the filtering once for all instead of performing it at each field change? -
Conditional component render if user is an owner of post React + Django Rest Framework
I have f.e. User and Post models. User object has an id and Post object has owner id. I want to render the <Edit /> button just when User is the owner of the Post. What is the best way to do this? Simply I can just get the current User id from database using one of my django's endpoints and check if user.id === post.owner but is it the best way? (I am using JWT in my project) Also how can I block or redirect users which are not the owner if someone of them open the site by link. Should I also simply check if if user.id === post.owner? One extra question: I am storing my JWT tokens at the moment in the localStorage. What I should looking for if I want to hide it in my blowser (if I click F12, I can find it in Application tab)? -
How to stop Django function from producing duplicate results?
I'm having trouble with this function that is creating duplicate records. I have a couple pages with documents that contain a response with document as a list of records. Each page contains a different number in this list. When all the records are created in the database, it starts to duplicate them because the amount of pages exceeds the number of pages that have documents in them. Here is what the response for each page looks like: { "page": 3, "limit": 10, "count": 2, "machines": [ { "1234", "location": "123 Random address", "location_name": "Scraton", "location_coordinates": { "latitude": 54.443454, "longitude": -124.9137471 }, { "document_id": "1235", "location": "124 Random address", "location_name": "New York", "location_coordinates": { "latitude": 233.385037, "longitude": -40.1823481 }, ] } Here is the function that is creating duplicates. def sync_all_documents(limit=1000, page_start=0,page_end=10): for page in range(page_start, page_end): try: response_data = get_documents(limit=limit, page=page) logger.info(f"Page Count: {response_data['count']}") if(response_data['count'] == 0): return except RequestError as ex: return # loop short circuits here try: documents = response_data[“documents”] for document in documents: # STEP 1 - Location try: serialized_location = serialize_location_information(document) location, l_created = Location.objects.get_or_create( latitude=serialized_location["latitude"], longitude=serialized_location["longitude"], defaults={ "country": serialized_location["country"], "state": serialized_location["state"], "city": serialized_location["city"], "street_address": serialized_location["street_address"], "postal_code": serialized_location["postal_code"], "name": serialized_location["name"], "status": serialized_location["status"], } ) if l_created: … -
Django Forms - how to access fields inside a class
im working with django forms and want to access the field variable inside its class: class CarPurchase(forms.Form): brand = forms.CharField(max_length=30) color = forms.CharField(max_length=20) @classmethod def set_color(cls, color): cls.color = color and that will give error says CarPurchase has no attribute 'name'. do you guys see what i have problem?