Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding nginx configuration to AWS Elastic Beanstalk
I got client request body is larger than the buffer size allowed by nginx error in the app so I decided to add an nginx.config file to fix the issue. Here is the file. user nginx; events { worker_connections 1024; } http { client_body_buffer_size 20M; client_max_body_size 20M; upstream api { server Sauftragdev-env.eba-zirmk4s9.eu-central-1.elasticbeanstalk.com:8000; } server { listen 80; location /static/ { alias /static/; } location / { proxy_pass http://api; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } } Now what do I need to add in the Elastic Beanstalk configuration to make this work? It's platform is Python 3.8 running on 64bit Amazon Linux 2/3.4.3. -
Django - revoke in celery does not cancel the task
I am trying to write Django command that will cancel existing celery task in my Django application. The idea is to use this command in APIView so user can cancel the task that is already running. When running python manage.py cancel_task I see in terminal that task was cancelled but the status of the task remains the same and it continues doing the task. In the end the status of the task is always SUCCESS. Task 0d5ffdd3-3a2c-4f40-a135-e1ed353afdf9 has been cancelled. Below is my command that I store in cancel_task.py from django.core.management.base import BaseCommand from celery.result import AsyncResult from myapp.celery import app as myapp class Command(BaseCommand): help = 'Cancel a long-running Celery task' def add_arguments(self, parser): parser.add_argument('task_id', help='ID of the task to cancel') def handle(self, *args, **options): task_id = options['task_id'] result = AsyncResult(task_id, app=myapp) if result.state not in ('PENDING', 'STARTED'): self.stdout.write(self.style.WARNING(f'Task {task_id} is not running.')) return result.revoke(terminate=True, wait=False) self.stdout.write(self.style.SUCCESS(f'Task {task_id} has been cancelled.')) I checked all answers in this post but nothing works in my application. What am I doing wrong and how to cancel task. I tried to use revoke directly in celery like this: >>> from myapp.celery import myapp >>> myapp.control.revoke(task_id) But the finnal effect is the same. I … -
how to write a comment and reply with django with this model?
im a newcomer and i have this problem that i can't send this comment to database it just refreshes the page and nothing happens def blog_detail(request , id): post = Post.objects.get(pk = id , status = True) comments = post.comments.filter(active=True) new_comment = None # Comment posted if request.method == 'POST': comment_content = request.POST['comment_content'] if comment_content == '' or comment_content == None : messages.error(request , 'comment is empty') try: comment = Comment.objects.get(body=comment_content,name=MyUser.first_name,email=MyUser.email,active=False) except: Comment.DoesNotExist() new_comment = None return render(request, 'blog/blog-detail.html', {'post': post, 'comments': comments, }) this is my model class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.name)``` i can't idenity the problem -
I got an error for not recognizing django render partial despite of installing it.(ModuleNotFoundError: No module named 'django_render_partial')
I've installed 'django-render-partial' following the 3 steps of https://pypi.org/project/django-render-partial, but I can't run my project because of this error: ModuleNotFoundError: No module named 'django_render_partial' I've put django_render_partial in installed apps and checked 'django.template.context_processors.request' in TEMPLATES['OPTIONS']['context_processors'] -
why is the output of make_password different than expected?
Sorry if this is a dumb question, but I'm new to django here. I'm creating a signup flow, one that needs the users email id and password to create the user. I'm trying to hash and salt the password, before saving the salted password in the db, along with the email. I'm using django's default make_password(password=password, salt=get_random_string(length=32)) to hash and salt the password. But the output I get is like "!KxPs6lAiW1Im2iuBbuK1lm6dqQz5h08gPSIWlEUr" instead of being something like "algorithm$iterations$salt$hash". Here's the code: salt = get_random_string(length=32) print(salt) salted_pwd = make_password(password=password, salt=salt) print("salted", salted_pwd) Why is this happening and what am I doing wrong here? -
Folders/files permission inference
I'm having some trouble working out how to implement this approach and I was wondering if anyone might offer an advice on how to handle it. Also, if there is a better approach to do it kindly let me know as this is my first time building something like this. I'm building a file system called Data room (DR) which each user will be able to create folders and uploads files in them. The user can share either files or folders as a whole. I was wondering how can I infer the permissions from the folder to the files. Like, if the user shared Folder A to User B and Folder A has 5 files I want User B to have access to all the files in Folder A with the permission of the folder (if the folder is shared with a R permission then the files should have the R permission). The user can either share individual files or the whole folder. The data room database model is ID User ID (FK) Folder Data room ID (fk) Name private (bool) File Folder id (fk) name path private (bool) ResourceManagement invitee (fk) inviter (fk) files: [] (fk), folders: [] (fk), … -
Query that cannot be written in django orm
Can you give me an example of a sql query that can't be written with django orm? -
CSRF checking with simpleJWT and DjangoRestFramework
I'm starting to use django and I'm lost in the request verification system. I find it difficult to grasp the intricacies of authentication methods. I am using JWT authentication with restframework_simplejwt to authenticate the user. Before using the JWT, I had the CSRF checks but it seems to me that I no longer have them since I defined this authentication system. Here are my settings and my view, built with DRF's ApiView. settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated' ], 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } view.py from rest_framework import status from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticated from rest_framework.authentication import SessionAuthentication from rest_framework_simplejwt.authentication import JWTAuthentication from rest_framework.response import Response class MakePredictionView(APIView): authentication_classes = [JWTAuthentication,] permission_classes = [IsAuthenticated, UserPermissionSpeedX] throttle_classes = [UserThrottleSpeedX,] serializer_class = MakePredictionSerializer def post(self, request): if not self.request.session.exists(self.request.session.session_key): self.request.session.create() serializer = self.serializer_class(data=request.data) if serializer.is_valid(): profil = SpeedX( player_name=serializer.data.get('player_name'), maturite_indice=serializer.data.get('maturite_indice'), resultat_vitesse_30m=serializer.data.get('resultat_vitesse_30m'), club=serializer.data.get('club'), categorie=serializer.data.get('categorie') ) profil.save() return Response(SpeedxSerializer(profil).data, status=status.HTTP_200_OK) If I replace JWTAuthentification by SessionAuthentification for example, it asks me for the CSRF token. But, If I add SessionAuthentification with JWTAuthentication in authentication_class, it no longer asks me for CSRF, and the authentication is done with JWT, without checking the CSRF token. Is this normal? is this risky? I … -
After populate form and formset it only save last row
Here is my view formset, about main form it populate and save well if formset.is_valid(): for form in formset: type_of_service = form.data["type_of_service"] item = form.data["item"] quantity = form.data["quantity"] rate = form.data["rate"] amount = form.data["amount"] if type_of_service and item and quantity and rate and amount: Grn_LineItem(vendor_name=grnmodel, type_of_service=type_of_service, item=item, quantity=quantity, rate=rate, amount=amount).save() grnmodel.save() return redirect('purchase_order_list') Here is my template <tbody> {% for lpo_line_item in lpo_line_item %} <tr class="{% cycle row1 row2 %} formset_row-{{ formset.prefix }}"> <td><input name="type_of_service" class="form-control input" value="{{ lpo_line_item.type_of_service }}"></td> <td><input name="item" class="form-control input" value="{{ lpo_line_item.item }}"></td> <td><input name="quantity" class="form-control input quantity_qty_rec" id="qty_rec" value="{{lpo_line_item.quantity}}"></td> <td><input name="rate" class="form-control input rate" value="{{ lpo_line_item.rate }}"></td> <td><input name="amount" class="input grn_amount form-control formset-field" id="grn_amount" value="{{lpo_line_item.amount}}"></td> </tr> {% endfor %} </tbody> </table> {{ formset.management_form }} it only save the main form and last row formset Thank you for your help -
variable already been declared after loading modal via htmx (after first load)
I'm loading a form using django in a modal (using htmx). I'm using a little vanilla javascript to load formsets dynamically as seen in this tutorial Dynamically Add Forms in Django with Formsets and JavaScript. Everything is working fine when you first load the modal but return an error when you load the modal a second time. After form saving I forced a complete reload of the page (not ideal as I want to refresh only a partial) but the problem is there when you load the modal. From what I understand (very little about JS) the problem is you cannot declare a variable more than 1 time using let (you can do let let ingredientForm = ... and only ingredientForm the second time) but obviously is not possible in my case as the script is loaded every time I fire the modal. Any solution? views.py @login_required def recipe_create(request): user = request.user template = "recipes/partials/_recipe_create.html" if request.method == "POST": form = RecipeForm(request.POST) formset = IngredientFormSet(request.POST) if form.is_valid() and formset.is_valid(): recipe = form.save(commit=False) recipe.creator = user recipe.save() for form in formset: if form.cleaned_data: name = form.cleaned_data["name"] ingredient, created = Ingredient.objects.get_or_create(name=name) RecipeIngredient.objects.get_or_create( ingredient=ingredient, recipe=recipe, ) return HttpResponse(status=204, headers={"HX-Redirect": reverse_lazy("recipes:recipe_list")}) form = RecipeForm(request.POST) … -
Docker container stops when running new one
I have project running on docker container in staging mode, actually I have two compose files, for staging and production in the same directory. At the moment stagin.yml is running, when I want to run production.yml , staging.yml stoppes running. staging.yml version: '3' volumes: staging_postgres_data: {} staging_postgres_data_backups: {} staging_staticfiles: {} staging_mediafiles: {} services: django: build: context: . dockerfile: ./compose/staging/django/Dockerfile image: project_staging_django depends_on: - postgres - redis env_file: - ./.envs/.staging/.django - ./.envs/.staging/.postgres volumes: - staging_mediafiles:/app/project/media command: /start postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: project_staging_postgres volumes: - staging_postgres_data:/var/lib/postgresql/data - staging_postgres_data_backups:/backups env_file: - ./.envs/.staging/.postgres bot: image: project_local_bot container_name: project_local_bot build: context: . dockerfile: ./compose/staging/pytelegrambot/Dockerfile volumes: - ./bot:/bots:z env_file: - ./.envs/.staging/.bot command: /start nginx: restart: unless-stopped build: context: . dockerfile: ./compose/staging/nginx/Dockerfile container_name: project_staging_nginx ports: - 3080:80 - 3443:443 volumes: - staging_mediafiles:/app/project/media depends_on: - django redis: image: redis:6 production.yml version: '3' volumes: production_postgres_data: {} production_postgres_data_backups: {} production_mediafiles: {} services: django: build: context: . dockerfile: ./compose/production/django/Dockerfile image: project_production_django container_name: project_production_django depends_on: - postgres - redis env_file: - ./.envs/.production/.django - ./.envs/.production/.postgres volumes: - production_mediafiles:/app/project/media command: /start postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: project_production_postgres container_name: project_production_postgres ports: - 5433:5432 volumes: - production_postgres_data:/var/lib/postgresql/data - production_postgres_data_backups:/backups env_file: - ./.envs/.production/.postgres nginx: restart: unless-stopped build: context: . dockerfile: ./compose/production/nginx/Dockerfile image: … -
insert data and display on another page
first I have insert data into table1 and show on html page using render method after display data this data IViews.py have to again insert into table2. `display data -try to insert on second page inserting on first page model of registration table model of main-registration table` -
Mocking an external API call in a Django view test
I have written a view in Django that receives text from the user and calls an external API for that text to be translated. View function: def translate_view(request): if request.method == 'POST': form = InputForm(request.POST) if form.is_valid(): source_lang = form.cleaned_data["source_lang"] target_lang = form.cleaned_data["target_lang"] source_text = form.cleaned_data["source_text"] deepl_result = call_deepl_api(source_text, source_lang, target_lang) return render( request, "output.html", { "source_lang": source_lang, "target_lang": target_lang, "source_text": source_text, "deepl_result": deepl_result, }, ) else: form = InputForm() return render(request, 'input.html', {'form': form}) I would like to test this view, and I think I have made the beginner's mistake of actually calling the API in my tests (they are very slow). As far as I understand it looks like I should mock the external API call, but I am struggling to understand how to do this. Could somebody teach me how to do this for the above view? Any help would be much appreciated! Tests: class TestOutput(SimpleTestCase): def setUp(self): self.valid_data_response = self.client.post( reverse('home'), {'direction': 'Ja>En', 'source_text': '花粉飛散情報',} ) def test_output_page_status_code_with_valid_data(self): self.assertEqual(self.valid_data_response.status_code, 200) ... more tests -
The first field in the models.py not created, how to fix it? (django)
I have written two classes in models.py (Django): class Name_tickers(models.Model): ticker = models.CharField(max_length = 32) name = models.CharField(max_length = 100) def __str__(self): return self.ticker class Close_stock(models.Model): date = models.DateField(), tiker_name = models.ForeignKey(Name_tickers, on_delete=models.CASCADE), price = models.DecimalField(max_digits=15, decimal_places=5) But was created: migrations.CreateModel( name='Close_stock', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('price', models.DecimalField(decimal_places=5, max_digits=15)), ], ), migrations.CreateModel( name='Name_tickers', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('ticker', models.CharField(max_length=32)), ('name', models.CharField(max_length=100)), ], ), How to fix it and add my first fields? I tried to delete migrations and create them again - it doesn't work -
Django Rest Framework Pytest Reverse Function Deeper
I am using Django Restframework and try to write unit test cases with pytest. I have been trying to use reverse function for getting the endpoint path. I have generally using this path as like "reverse("api:death_spec:field_types")" generally and it works fine. But if we need go deeper for action method it doesn't work. My view is: `class DeathSpecViewSet(viewsets.ModelViewSet): @action(detail=False, methods=["get"], url_path=r"(?P<transformation_id>[^/.]+)/case",name="case-list") def case(self, request, transformation_id): dagRunId = self.get_transformation_name() try: page = int(request.GET.get("page", 1)) page_size = int(request.GET.get("page_size", 10)) search = request.GET.get("search") except ValueError as e: return JsonResponse({"status": False, "message": "Enter a valid data.", "code": 400, "data": []}, status=status.HTTP_404_NOT_FOUND) first_data = 0 if page > 1: first_data = page_size * (page - 1) last_data = page_size * page case_query, total_count = filter_case_list(dagRunId, search, first_data, last_data) serializer = CaseListSerializer(case_query, many=True) return JsonResponse({"status": True, "message": "Cases listed successfully.", "code": 200, "data": serializer.data, "count": total_count}, status=status.HTTP_200_OK)` and my url.py is: from django.urls import path from apps.death_spec.api.views import * from rest_framework import routers app_name = "death_spec" urlpatterns = [ path("death-spec/field-types/<str:model_name>", DeathSpecFieldsView.as_view(), name="field_types"), path("death-spec/field-names", DeathSpecAllFieldsView.as_view(), name="all_field_names"), ] router = routers.DefaultRouter() router.register(r"death-spec", DeathSpecViewSet, basename="death_spec2") urlpatterns = router.urls + urlpatterns I have been trying to get path with reverse function. So far "reverse("api:death_spec:death_spec2:case-list" doesn't work. How can i reach … -
Stripe Subscription adding same card twice
I have implemented Stripe Subscription with the following steps : Add card via Stripe Elements using stripe.PaymentMethod.attach : stripe_customer = stripe.Customer.retrieve(str(customer.stripe_customer_id)) payment_methods_list = stripe.PaymentMethod.list(customer=stripe_customer.id, type="card") card = request.data['card'] stripe_paymentmethod_id = card['id'] # paymentmethod = stripe.PaymentMethod.create(type="card", card=card['id']) # logging.info(f"StripePaymentMethodCreate paymentmethod : {paymentmethod}") stripe.PaymentMethod.attach( stripe_paymentmethod_id, customer=stripe_customer.id) stripe.Customer.modify( stripe_customer.id, invoice_settings={ "custom_fields": None, "default_payment_method": stripe_paymentmethod_id, "footer": None, "rendering_options": None }, ) Then create a subscription, and generate a client secret : stripe.confirmCardPayment(resultState.data.clientsecret, { payment_method: { card: info.card_element, billing_details: { name: "Name Surname", }, } Then finally confirm payment card in FrontEnd : stripe_customer = stripe.Customer.retrieve(customer.stripe_customer_id) stripe_subscription_list = stripe.Subscription.list(customer=customer.stripe_customer_id) stripe_subscription_list_len = len(stripe_subscription_list.data) stripe_subscription = None if stripe_subscription_list_len != 0: stripe_subscription = stripe.Subscription.retrieve(stripe_subscription_list.data[0].id) if ((stripe_subscription_list_len == 0) or (stripe_subscription_list_len == 1)) and \ (selected_product.plan == 0 and customer.product.plan != selected_product.plan) or \ (selected_product.plan > 0 and stripe_customer.invoice_settings.default_payment_method != None and customer.product.plan != selected_product.plan): logging.info(f"SubscriptionCreate post Subscription Modify.") logging.info(f"stripe_customer.invoice_settings.default_payment_method : {stripe_customer.invoice_settings.default_payment_method}") logging.info(f"SubscriptionCreate customer.product.plan : {customer.product.plan}") logging.info(f"SubscriptionCreate selected_product.plan : {selected_product.plan}") # This will be removed in deployment logging.info(f"SubscriptionCreate Deleting Free Plan : {selected_product.plan}") if stripe_subscription: stripe.Subscription.delete(stripe_subscription.id) logging.info(f"SubscriptionCreate Free Plan Deleted : {selected_product.plan}") new_subscription = stripe.Subscription.create( customer=customer.stripe_customer_id, items=[{"price": stripe_product.stripe_plan_id},], payment_behavior='default_incomplete', payment_settings={'save_default_payment_method': 'on_subscription'}, expand=['latest_invoice.payment_intent'], ) if new_subscription: customer.product = stripe_product customer.active = False if customer.product.plan == 0: customer.active = True … -
Unittesting DRF Serializer validators one by one
We have an example Serializer class we'd like to test: from rest_framework import serializers class MySerializer(serializers.Serializer): fieldA = serializers.CharField() fieldB = serializers.CharField() def validate_fieldA(self,AVal): if not AVal: raise serializers.ValidationError("AField must not be empty") return AVal def validate_fieldB(self,BVal): if not BVal: raise serializers.ValidationError("BField must not be empty") return BVal This is a greatly simplified scenario, but it should do. We want to write unittests for this Serializer class. My friend argues we should test using the .is_valid() method, like so class TestMySerializer(unittest.TestCase): def test_validate_fieldA_not_empty(self): ser = MySerializer(data={"fieldA":"I'm not empty","fieldB":"Whatever"}), self.assertTrue(ser.is_valid()) self.assertTrue(ser.validated_data="I'm not empty") def test_validate_fieldA_empty(self): ser = MySerializer(data={"fieldA":"","fieldB":"Whatever"}) self.assertFalse(ser.is_valid()) #similarly tests for fieldB ... I argue that unittests are supposed to be atomic and test only one "thing" at a time. By using the .is_valid() method we run every validator in the class instead of just the one we want to test. This introduces an unwanted dependency, where tests for fieldA validators may fail if there's something wrong with fieldB validators. So instead I would write my tests like so: class TestMySerializer(unittest.TestCase): def setUp(self): self.ser = MySerializer() def test_fieldA_validator_not_empty(self): self.assertEqual(self.ser.validate_fieldA("not empty"),"not empty") def test_fieldA_validator_empty(self): with self.assertRaises(serializers.ValidationError) as catcher: self.ser.validate_fieldA('') self.assertEqual(str(catcher.exception),"AField must not be empty") #same for fieldB validators ... Which approach … -
Django setting nginx
I ran into a problem while publishing the site. When turned on Debug=False the pictures disappear. Log nginx error: 2023/03/06 11:17:39 [error] 646224#646224: *15 open() "/home/egor/mysite/PersonalPortfolio-project/staticportfolio/image/django_certificate-1.png" failed (2: No such file or directory), client: 109.198.191.208, server: zyoger.ru, request: "GET /media/portfolio/image/django_certificate-1.png HTTP/1.1", host: "www.zyoger.ru", referrer: "http://www.zyoger.ru/about" 2023/03/06 11:17:39 [error] 646224#646224: *14 open() "/home/egor/mysite/PersonalPortfolio-project/staticportfolio/image/python_certificate-1.png" failed (2: No such file or directory), client: 109.198.191.208, server: zyoger.ru, request: "GET /media/portfolio/image/python_certificate-1.png HTTP/1.1", host: "www.zyoger.ru", referrer: "http://www.zyoger.ru/about" Settings nginx: user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; Settings django: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.1/howto/static-files/ STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') I've read a lot of articles and I can't figure it out. How To Set Up Django with Postgres, Nginx, and Gunicorn on Ubuntu 18.04 -
Django app is giving WSGI error "ValueError: source code string cannot contain null bytes"
When I recently checked my django app I see the errors below in the error logs 2023-03-06 08:04:22,408: Error running WSGI application 2023-03-06 08:04:22,449: ValueError: source code string cannot contain null bytes 2023-03-06 08:04:22,450: File "/var/www/meitheal-carbontracking_pythonanywhere_com_wsgi.py", line 22, in <module> 2023-03-06 08:04:22,450: application = get_wsgi_application() Any pointers on where to start looking ? This seems like the like the app itself is not starting. I haven't touched the /var/www/meitheal-carbontracking_pythonanywhere_com_wsgi.py file since it's creation, when the app was working. In that ..wsgi.py file my understanding is that it sets the project home project_home = '/home/carbontracking/meitheal' and then points to the settings.py file with os.environ['DJANGO_SETTINGS_MODULE'] = 'meitheal.settings' and then kicks off the app on the server with application = get_wsgi_application() This setting file, in my case , should be /home/carbontracking/meitheal/meitheal/settings.py , is that correct ? Then in settings.py I have the lines INSTALLED_APPS = [ .... "quotes.apps.QuotesConfig", .... ] Which then has to correspond to what is in project_name/app_name/apps.py from django.apps import AppConfig class QuotesConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "quotes" Is this chain that I've shown correct? -
Django IntegerField - dynamic determination of max and min values based on a database record
How to set, max and min value in IntegerField, dependent on database record? The operation of this fragment: The database collects information about the quantity of a product in stock. The user can retrieve any quantity of the product from the warehouse, provided that the selected quantity is in the range from 0 to the quantity of the product in stock. So that it is not possible to download more than there is. My code looks as follows: In the forms.py file class QuantityForm(forms.ModelForm): def __init__(self, max_value, *args, **kwargs): # super().__init__(*args, **kwargs) self.fields['quty'].widget.attrs.update({'min':0, 'max': max_value,}) self.fields['quty'].label='Wprowadź wartość' class Meta: model = Products fields = ['quty'] In the views.py file def to_custemer(request, pk): pk_product = Products.objects.get(id=pk) max_value = pk_product.quty if request.method=="POST": form = QuantityForm(request.POST, max_value=max_value)# if form.is_valid(): enter_varible = form.cleaned_data['quty'] pk_product.quty -= enter_varible pk_product.save() return redirect('/my_pantry') else: form = QuantityForm(max_value=max_value)# context={ 'form':form, 'pk_product':pk_product, } return render(request, 'to_kitchen.html', context) In general, the code works half-heartedly. 1.(request.POST, max_value=max_value) - you can only select a quantity between 0 and the quantity in stock. But it doesn't work to retrieve the selected quantity, it also doesn't work to work on the database and pops up an error 500. 2.(request.POST) rigidly assign max value in forms … -
Any Way to Get Object ID from Django List
I am working on a Django project where I have a list of Customer Accounts, and from the List (In a HTML Table) I have a Button with link for Statement. And on this Statement Anchor Button, I want to check if Customer Account has made Deposit or not then be able to Display the Link for Checking his/her Transaction Statement or NOT. Below are my Models: class Profile(models.Model): customer = models.OneToOneField(User, on_delete=models.CASCADE, null = True) surname = models.CharField(max_length=20, null=True) othernames = models.CharField(max_length=40, null=True) gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True) address = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=11, null=True) image = models.ImageField(default='avatar.jpg', blank=False, null=False, upload_to ='profile_images', ) #Method to save Image def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) #Check for Image Height and Width then resize it then save if img.height > 200 or img.width > 150: output_size = (150, 250) img.thumbnail(output_size) img.save(self.image.path) def __str__(self): return f'{self.customer.username}-Profile' class Account(models.Model): customer = models.OneToOneField(User, on_delete=models.CASCADE, null=True) account_number = models.CharField(max_length=10, null=True) date = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return f' {self.customer} - Account No: {self.account_number}' class Deposit(models.Model): customer = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True) transID = models.CharField(max_length=12, null=True) acct = models.CharField(max_length=6, null=True) staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True) deposit_amount = models.PositiveIntegerField(null=True) date = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): … -
Can the User model be replaced by a Google NDB model in Django?
Usually when we create the the User model by inheriting AbstractUser which is eventually inherited from django.db.models.Model. e.g. from django.contrib.auth.models import AbstractUser class User(AbstractUser): id = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True) username = models.CharField(max_length=150, unique=True) email = models.EmailField(unique=True) But is it possible that instead of this, we create the user model using this code? from google.cloud import ndb class CustomUser(ndb.Model): username = ndb.StringProperty(required=True) email = ndb.StringProperty(required=True) Will this have any ripple effects? e.g. third-party apps that rely on the default user model(maybe DRF). I haven't tried it yet. I just wanna make sure if it's possible before I end up writing a lot of code. -
Cannot circumvent "more than one row returned by a subquery used as an expression" with Django ORM
I have two classes that looks like follows: class InstallmentSchedule(SMSVerifiedModel): invoice = models.ForeignKey("api.Invoice", related_name="installment_schedules", on_delete=models.PROTECT) reference_id = models.CharField( max_length=10, unique=True, help_text="..." ) amount_principal = models.DecimalField(max_digits=10, decimal_places=2) interest_rate = models.DecimalField(max_digits=10, decimal_places=4) fee_rate = models.DecimalField(max_digits=10, decimal_places=5) ... ... class Installment(models.Model): schedule = models.ForeignKey("api.InstallmentSchedule", related_name="installments", on_delete=models.PROTECT) type = models.IntegerField(choices=TYPE_CHOICES, default=TYPE_REGULAR) date_start = models.DateField() date_end = models.DateField() ... ... What I want to do is to find all InstallmentSchedule objects with installment_ids listed next to them, such as <InstallmentScheduleQuerySet [{'id': 1, 'installment_ids': [1,2,3,4,5]}, {'id': 2, 'installment_ids': [6,7,8]}, {'id': 4, 'installment_ids': [34,35,36,37]}, ... I tried some query like this: InstallmentSchedule.objects.filter( ...: installments__invoice__date_paid__isnull=True, ...: installments__date_invalidated__isnull=True ...: ).values('id').annotate( ...: installment_ids=Subquery( ...: Installment.objects.filter(schedule=OuterRef("pk")).values('schedule__id').annotate(ids=ArrayAgg('schedule__id')).order_by('id').values('ids' ...: ), ...: output_field=Field() ...: ) ...: ).values("installment_ids", "id").distinct() I always get ProgrammingError: more than one row returned by a subquery used as an expression Subquery always forces me to return a single row or single column. I thought using values() would group correctly. I also tried the suggestion in this answer, but still the same. -
using if else condition with for loop in Django
I fairly new to Django, I have a list of usecase model shown in a a table, and a usecase progress model that includes a foreign key of the usecase. Initially a new usecase doesn't have a progress yet, so in my template I'm trying to say check if the usecase doesn't have a progress yet set a default value so the progress columns aren't empty and looking weird. Can't seem to write my logic write. I hope I'm clear. below is an image of my output: My template: {% extends 'EmpDashboard.html' %} {% block body %} <div class="row d-flex"> <div class="col-12 mb-4"> <div class="card border-light shadow-sm components-section d-flex"> <div class="card-body d-flex row col-12"> <div class="row mb-4"> <div class="col-lg-12 col-sm-16"> <h3 class="h3 mb-4">View Usecases:</h3> </div> {% if usecase_details is not none and usecase_details %} <div class="table-responsive"> <table id="example" class="table table-flush text-wrap table-sm" cellspacing="0" width="100%"> <thead class="thead-light"> <tr> <th scope="col">No.</th> <th scope="col">Usecase ID</th> <th scope="col">Usecase Name</th> <th scope="col">Client</th> <th scope="col">KPI</th> <th scope="col">Progress</th> <th scope="col">Progress date</th> <th scope="col">Pipeline</th> <th scope="col">Phase</th> <!-- <th scope="col">Estimated Delivery</th> --> <th scope="col">Details</th> </tr> </thead> <tbody> {% for result in usecase_details %} <tr> <td>{{ forloop.counter }}</td> <td><span class="badge bg-info">{{result.usecase_id}}</span></td> <td>{{result.usecase_name}}</td> <td>{{result.business_owner.business_owner_name}}</td> <td>{{result.kpi.kpi_name}}</td> {% if result.usecaseids.all is not none … -
link the django project to the ftp server
I upload my files to my FTP server: DEFAULT_FILE_STORAGE = 'storages.backends.ftp.FTPStorage' FTP_STORAGE_LOCATION = f'ftp://{FTP_USER}:{FTP_PASS}@{FTP_LOCALHOST }:21/upload/' but I can't download them back later in the django project. Maybe you should rewrite MEDIA_ROOT and MEDIA_URL? Who can help? MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(FTP_STORAGE_LOCATION,) I tried changing the media_root. But nothing works