Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
How can I translate a curl command to Python request?
Following this Shopify tutorial, I'm trying to upload an image to Shopify. A subtask is to translate this curl command to a python request. The file is uploaded by users and can be accessed with request.FILES['filename']: curl -v \ -F "Content-Type=image/png" \ -F "success_action_status=201" \ -F "acl=private" \ -F "key=tmp/45732462614/products/7156c27e-0331-4bd0-b758-f345afaa90d1/watches_comparison.png" \ -F "x-goog-date=20221024T181157Z" \ -F "x-goog-credential=merchant-assets@shopify-tiers.iam.gserviceaccount.com/20221024/auto/storage/goog4_request" \ -F "x-goog-algorithm=GOOG4-RSA-SHA256" \ -F "x-goog-signature=039cb87e2787029b56f498beb2deb3b9c34d96da642c1955f79225793f853760906abbd894933c5b434899d315da13956b1f67d8be54f470571d7ac1487621766a2697dfb8699c57d4e67a8b36ea993fde0f888b8d1c8bd3f33539d8583936bc13f9001ea3e6d401de6ad7ad2ae52d722073caf250340d5b0e92032d7ad9e0ec560848b55ec0f943595578a1d6cae53cd222d719acb363ba2c825e3506a52b545dec5be57074f8b1b0d58298a0b4311016752f4cdb955b89508376c38f8b2755fce2423acb3f592a6f240a21d8d2f51c5f740a61a40ca54769a736d73418253ecdf685e15cfaf7284e6e4d5a784a63d0569a9c0cffb660028f659e68a68fb80e" \ -F "policy=eyJjb25kaXRpb25zIjpbeyJDb250ZW50LVR5cGUiOiJpbWFnZVwvcG5nIn0seyJzdWNjZXNzX2FjdGlvbl9zdGF0dXMiOiIyMDEifSx7ImFjbCI6InByaXZhdGUifSxbImNvbnRlbnQtbGVuZ3RoLXJhbmdlIiwxLDIwOTcxNTIwXSx7ImJ1Y2tldCI6InNob3BpZnktc3RhZ2VkLXVwbG9hZHMifSx7ImtleSI6InRtcFwvZ2NzXC80NTczMjQ2MjYxNFwvcHJvZHVjdHNcLzcxNTZjMjdlLTAzMzEtNGJkMC1iNzU4LWYzNDVhZmFhOTBkMVwvd2F0Y2hlc19jb21wYXJpc29uLnBuZyJ9LHsieC1nb29nLWRhdGUiOiIyMDIyMTAyNFQxODExNTdaIn0seyJ4LWdvb2ctY3JlZGVudGlhbCI6Im1lcmNoYW50LWFzc2V0c0BzaG9waWZ5LXRpZXJzLmlhbS5nc2VydmljZWFjY291bnQuY29tXC8yMDIyMTAyNFwvYXV0b1wvc3RvcmFnZVwvZ29vZzRfcmVxdWVzdCJ9LHsieC1nb29nLWFsZ29yaXRobSI6IkdPT0c0LVJTQS1TSEEyNTYifV0sImV4cGlyYXRpb24iOiIyMDIyLTEwLTI1VDE4OjExOjU3WiJ9" \ -F "file=@/Users/shopifyemployee/Desktop/watches_comparison.png" \ "https://shopify-staged-uploads.storage.googleapis.com/" I use chatgpt to come up with this python code: def uploadImage(stagedTarget, file): parameters = stagedTarget["parameters"] url = stagedTarget["url"] files = { 'file': file, } data = { 'Content-Type': parameters[0]['value'], 'success_action_status': parameters[1]['value'], 'acl': parameters[2]['value'], 'key': parameters[3]['value'], 'x-goog-date': parameters[4]['value'], 'x-goog-credential': parameters[5]['value'], 'x-goog-algorithm': parameters[6]['value'], 'x-goog-signature': parameters[7]['value'], 'policy': parameters[8]['value'], } print(f"{url = }, {data = }") response = requests.post(url, files=files, data=data) print(f"{response.status_code = }") print(f"{response.text = }") response = response.content response = json.loads(response) The server gives me this response: web_1 | response.status_code = 400 web_1 | response.text = "<?xml version='1.0' encoding='UTF-8'?><Error><Code>EntityTooSmall</Code><Message>Your proposed upload is smaller than the minimum object size specified in your Policy Document.</Message><Details>Content-length smaller than lower bound on range</Details></Error>" My file size is only 46KB. I don't know why it's too small. I tried to call the curl command to upload … -
Override test settings from a file
When one wants to change settings in a test (yes, it's ok to change it there), we can use override_settings() or modify_settings() (as observed here). That works when running the tests in parallel too. In my case, I have multiple test classes and would like to change various settings only when running the respective tests (it should restore the settings when not running that test). Generally speaking, would do something like this from django.test import TestCase, override_settings @override_settings(LOGIN_URL='/other/login/') class LoginTestCase(TestCase): def test_login(self): response = self.client.get('/sekrit/') self.assertRedirects(response, '/other/login/?next=/sekrit/') How to use a file for that instead of having a long list like LOGIN_URL='/other/login/', ...? -
Cannot build sphinx autodocumentation with Django via GitLab (docker) pipeline
this problem might be quite specific. My setup This is my project structure. It's a Django project. ├── docs │ ├── build │ │ ├── doctrees │ │ └── html │ ├── Makefile │ └── source │ ├── code │ ├── conf.py │ ├── contributing.md │ ├── index.rst │ ├── infrastructure.md │ └── _static ├── my-project-name │ ├── api.py │ ├── asgi.py │ ├── celeryconfig.py │ ├── celery.py │ ├── __init__.py │ ├── __pycache__ │ ├── routers.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py | ... some more apps It is hosted on a private GitLab instance and I have multiple runners installed. One is a docker executor that is responsible for building the documentation via Sphinx. The basic .gitlab-ci.yml looks like this: image: python:3.10-slim stages: - deploy pages: tags: - docs stage: deploy script: - python3 -m pip install django sphinx furo myst-parser - sphinx-build -b html docs/source public/ This has been working just fine as long as I haven't tried to include Django code via the sphinx-autodoc extension. Everything shows up on the GitLab pages. I know that Sphinx needs to load every module that it scans upfront. So this is why you have to initialize … -
Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'> ` error code
when I try to validations for each filed it does not work. instead of that it show about error. give me proper answer for that. views.py from moviList.models import moviListModel from moviList.api.serializers import moviSerializers from rest_framework.response import Response # from rest_framework.decorators import api_view from rest_framework.views import APIView class movi_list(APIView): def get(self, request): abc = moviSerializers(moviListModel.objects.all(), many = True) return Response(abc.data) def post(self, request): abc = moviSerializers(data = request.data) if abc.is_valid(): abc.save() return Response({'message' : 'you add the update infomation into your old one'}) serializers.py file from rest_framework import serializers from moviList.models import moviListModel class moviSerializers(serializers.Serializer): name = serializers.CharField() year = serializers.IntegerField() country = serializers.CharField() def validate(self, data): if data['name'] == data['country'] : raise serializers.ValidationError("this is real ") else: return data def create(self, validated_data): return moviListModel.objects.create(**validated_data) def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.year = validated_data.get('year', instance.year) instance.country = validated_data.get('country', instance.country) instance.save() return instance urls.py from django.urls import path from moviList.api.views import movi_list urlpatterns = [ path('', movi_list.as_view()), # path('<int:pk>/', item) ] both filed validation or object validations does not work with my simple situation -
Does CharField with no defined max_length in serializer accept unlimit character?
For example, I have a serializer like this class Question(serializers.Serializer): title = serializers.CharField(max_length=255) description = serializers.CharField() body = serializers.CharField(style={'base_template': 'textarea.html'}) For description field, I don't specific max_length attribute, so it accept lots of characters, but does it really unlimit? And what is the different between description field and body field above? Does they the same? -
'str' object has no attribute '\_meta' error throughs when i want to put data from form to database
I want to get data from the form but somehow I didn't get as I required plz help me to reach out at my required answer from django.db import models class Profile(models.Model): name=models.CharField(max_length=100) address=models.CharField(max_length=100) pin=models.CharField(max_length=100) contact=models.CharField(max_length=100) email=models.CharField(max_length=100) def __str__(self): return self.name from django.shortcuts import render from django.http import HttpResponse from .models import Profile def index(request): if request.method == 'POST': name = request.POST.get('name') address =request.POST.get('address') pin = request.POST.get('pin') contact = request.POST.get('contact') email = request.POST.get('email','') profile = Profile(name="name",address="address",pin="pin",contact="contact",email="email") profile.save() return render(request , 'index.html') As you can see , I am trying to put my form's data to the model but it throughs an error "'str' object has no attribute '_meta'" -
Django creating additional object in DB in django admin
I have AdminForm: class MenuItemAdminForm(forms.ModelForm): ancestor = forms.ModelChoiceField(required=False, queryset=MenuItem.objects.all()) def save(self, commit=True): instance = super().save(commit=commit) ancestor = self.cleaned_data['ancestor'] instance.ancestor_id = None if ancestor is None else ancestor.pk return instance and two models: class MenuItemClosureTable(models.Model): ancestor = models.ForeignKey('self', related_name='ancestor_item', on_delete=models.CASCADE) descendent = models.ForeignKey('self', related_name='descendent_item', on_delete=models.CASCADE) level = models.IntegerField() class MenuItem(models.Model): name = models.CharField(max_length=255, unique=True) slug = models.SlugField(max_length=255, unique=True) def save(self, *args, **kwargs): super().save(*args, **kwargs) # here I must create MenuItemClosureTable objest and save it # for example: MenuItemClosureTable(ancestor_id=self.id, descendent_id=self.id, level=1).save() But get "FOREIGN KEY constraint failed" error. The problem is after super().save(*args, **kwargs) record in DB is still not created. How can I manage this? -
ValueError: Field 'id' expected a number but got 'str' in Grappelli related field
I'm using grappelli and faced with problem. I have foreign key 'owner' in model hence foreign key related field in django admin add form. When attempting to input symbols in this field I got this error and the problem is in grappelli related field. enter image description here enter image description here Do you have any suggestions/solutions?