Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Why the Django Local Server is not running?
TypeError: view must be a callable or a list/tuple in the case of include(). trying to run server and live the django project -
How to check given date is sunday or not in dajngo
Here i am getting a list of dates check whether the day is sunday or not date_list = ['2023-03-17', '2023-03-18', '2023-03-19', '2023-03-20'] Now check each date's days and if date is sunday return that date (using for loop) -
ERROR recieved: django.db.utils.IntegrityError: FOREIGN KEY constraint failed in a MultiUser Django setup
I have been trying to set up DjangoRESTframework as a backend of my project. While defining my model, and then creating a superuser via the terminal, I received the the following error (as mentioned in the title of question) what my code looks like (models.py) The Wallet Model: class Wallet(models.Model): user = models.OneToOneField( "CustomUser", on_delete=models.CASCADE, primary_key=True ) balance = models.DecimalField(max_digits=10, decimal_places=2, default=0) transactions = models.ManyToManyField("Transaction") def __str__(self): return f"{self.user.username}'s wallet" The Transaction model: class Transaction(models.Model): sender = models.ForeignKey("CustomUser", on_delete=models.CASCADE, related_name="sender", db_constraint=False) receiver = models.ForeignKey("CustomUser", on_delete=models.CASCADE, related_name="receiver", db_constraint=False) timestamp = models.DateTimeField(default=timezone.now) transaction_amount = models.DecimalField(max_digits=10, decimal_places=2) transaction_id = models.CharField(max_length=TXN_ID_LENGTH, primary_key=True, unique=True) # status of the transaction SUCCESS = 0 FAILED = 1 PENDING = 2 IN_REVIEW = 3 TRANSACTION_STATUS = [ (SUCCESS, "Success"), (FAILED, "Failed"), (PENDING, "Pending"), (IN_REVIEW, "In Review"), ] transaction_status = models.IntegerField(choices=TRANSACTION_STATUS, default=PENDING) class Meta: unique_together = ('sender', 'receiver', 'transaction_id') def __str__(self): return f"{self.transaction_id} - {self.transaction_status}" def clean(self): if self.transaction_amount < 0: raise ValidationError("Transaction amount cannot be negative") if self.sender == self.receiver: raise ValidationError("Sender and receiver cannot be the same") if self.sender.wallet.balance < self.transaction_amount: raise ValidationError("Insufficient balance") def save(self, *args, **kwargs): self.clean() if not self.transaction_id: self.transaction_id = generate_random_string(TXN_ID_LENGTH) self.sender.wallet.balance -= self.transaction_amount self.receiver.wallet.balance += self.transaction_amount self.sender.wallet.save() self.receiver.wallet.save() if self.sender.wallet.balance < 0: … -
django rest framework giving psycopg2 Error
End developers, I am a FE dev having trouble with setting up BE. I need to connect django project with my FE which uses React.js. I have installed all the required stuff and finally when I ran make runserver, it's giving me this error raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2' When I ran make install, I get another error, ~/.poetry/venv/lib/python3.10/site-packages/poetry/installation/chef.py:152 in _prepare 148│ 149│ error = ChefBuildError("\n\n".join(message_parts)) 150│ 151│ if error is not None: → 152│ raise error from None 153│ 154│ return path 155│ 156│ def _prepare_sdist(self, archive: Path, destination: Path | None = None) -> Path: Note: This error originates from the build backend, and is likely not a problem with poetry but with psycopg2 (2.9.5) not supporting PEP 517 builds. You can verify this by running 'pip wheel --use-pep517 "psycopg2 (==2.9.5) ; python_version >= "3.6""'. I am using Macbook Air M2, if that is related to my specific device. I am not sure what psycopg2 is and why I am getting this error. I just simply need my django project to run smoothly so that I can connect to it from FE. Can someone help me … -
VPS server nginx + gunicorn not rendering tiny.mce media form in django project
The problem is observed only on the production server. The nginx and gunicorn logs do not show any errors. I have not previously been involved in server administration and I don’t understand it at all. Recently, I independently launched the project on the server for the first time using ubuntu + nginx + gunicorn. At the same time, to be honest, I don’t remember if the problem has been observed from the very beginning or has appeared recently. I did not write anything about tiny.mce in the nginx and gunicorn configurations. And do I need to prescribe it? If I understand correctly, this is not necessary and django should do this work. If necessary to prescribe it, where to delegate it and what is the syntax for this? I will be grateful for any answer! -
How to add new folder in pycharm?
I am practicing django on pycharm , I want to add new folder in existing project but didn't getting any option to add new folder, how can I add? How to add new folder -
Docker - Unable to make URL Requests to outside sites
This is first Docker project and I am not an IT person. I installed Docker using Django Cookiecutter. https://cookiecutter-django.readthedocs.io/en/latest/deployment-with-docker.html All seems to be well until i try to do a URL request. I assume it is some port sort of thing? Just a simples request will not work. response = requests.get(url) Thanks. here is the local.yml: version: '3' volumes: prelim_local_postgres_data: {} prelim_local_postgres_data_backups: {} services: django: &django build: context: . dockerfile: ./compose/local/django/Dockerfile image: prelim_local_django container_name: prelim_local_django depends_on: - postgres - redis - mailhog volumes: - .:/app:z env_file: - ./.envs/.local/.django - ./.envs/.local/.postgres ports: - "8000:8000" command: /start postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: prelim_production_postgres container_name: prelim_local_postgres volumes: - prelim_local_postgres_data:/var/lib/postgresql/data - prelim_local_postgres_data_backups:/backups env_file: - ./.envs/.local/.postgres ports: - "5432:5432" nginx-proxy: image: jwilder/nginx-proxy:alpine container_name: nginx-proxy ports: - "80:80" - "443:443" volumes: - /var/run/docker.sock:/tmp/docker.sock:ro # - ./certs:/etc/nginx/certs restart: always depends_on: - django whoami: image: jwilder/whoami environment: - VIRTUAL_HOST=whoami.local mailhog: image: mailhog/mailhog:v1.0.0 container_name: prelim_local_mailhog ports: - "8025:8025" redis: image: redis:6 container_name: prelim_local_redis celeryworker: <<: *django image: prelim_local_celeryworker container_name: prelim_local_celeryworker depends_on: - redis - postgres - mailhog ports: [] command: /start-celeryworker celerybeat: <<: *django image: prelim_local_celerybeat container_name: prelim_local_celerybeat depends_on: - redis - postgres - mailhog ports: [] command: /start-celerybeat flower: <<: *django image: prelim_local_flower container_name: prelim_local_flower ports: … -
Python Django Profit Calculator
I trying to make a profit calculator in Python/Django. The user will input some values and then they will be redirect to another html that will show the user values plus calculations values. Is that the best way to do it? url image enter image description here forms from django import forms comissao_choices = ["1","2","3","4","5"] itbi_choices = ["1","2","3","4","5"] despesa_vendas_choices = ["1","2","3","4","5"] class InvestmentForm(forms.Form): comissao_leiloeiro_percentual = forms.ChoiceField(label = 'Comissão do Leiloeiro', choices = comissao_choices, required = True) itbi_percentual = forms.ChoiceField(label = 'ITBI * - Preencha o percentual da sua cidade, em São Paulo é 3%', choices = itbi_choices, required = True) despesa_venda_percentual = forms.ChoiceField(label = 'Na hipótese da venda ser intermediada por corretor informar a comissão',choices = despesa_vendas_choices, required = True) arrematacao = forms.DecimalField(label='Valor da Arrematação (R$)', min_value=100, decimal_places=2, widget=forms.NumberInput(attrs={'class':'form-control', 'placeholder':'This field is required'})) valor_venal = forms.DecimalField(label='Valor Venal do Imóvel (R$)', min_value=100, decimal_places=2, widget=forms.NumberInput(attrs={'class':'form-control', 'placeholder':'This field is required'})) valor_esperado_venda = forms.DecimalField(label='Valor Esperado de Venda (R$)', min_value=100, decimal_places=2, widget=forms.NumberInput(attrs={'class':'form-control', 'placeholder':'This field is required'})) oficial_imissao = forms.DecimalField(label='Oficial (imissão na posse) (R$)', min_value=100, decimal_places=2, widget=forms.NumberInput(attrs={'class':'form-control', 'placeholder':'This field is required'})) carta_arrematacao = forms.DecimalField(label='Expedição da Carta de Arrematação (R$)', min_value=100, decimal_places=2, widget=forms.NumberInput(attrs={'class':'form-control', 'placeholder':'This field is required'})) honorarios_advocaticios = forms.DecimalField(label='Honorários Advocatícios (imissão na posse) (R$)', min_value=100, decimal_places=2, …