Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to migrate data in Django
My Django structure follows this article: https://studygyaan.com/django/best-practice-to-structure-django-project-directories-and-files#:~:text=The%20way%20I%20like%20to,content%20in%20the%20media%20folder. where I put my app sync_wits_meta in apps folder and add app_1 in INSTALLED_APPS INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.sync_wits_meta', # <--- here ] then when I run python manage.py makemigrations, it shows the error: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/apps/config.py", line 210, in create app_module = import_module(app_name) File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'sync_wits_meta' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/usr/local/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.8/site-packages/django/apps/config.py", line 212, in create raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Cannot import 'sync_wits_meta'. Check that 'apps.sync_wits_meta.apps.SyncWitsMetaConfig.name' is correct. The command '/bin/sh -c python manage.py makemigrations apps/sync_wits_meta' returned a non-zero code: 1 How can I do migration if I put app in the apps folder? I am using … -
How to create a App Specific User roles and access in Django?
I want to create a user management system in Django where I will have multiple apps and for a single user, I want to assign different roles for the various apps as in the image below. Expert advice would be appreciated. The Image shows the different roles assigned to a user for different apps -
Django Admin Crash When Default Storage Changed
I'm trying to change the default storage of a model in django so that it stores files in an amazon S3 bucket the bucket has the next permissions: { "Version": "2012-10-17", "Id": "Policy1680906499830", "Statement": [ { "Sid": "Stmt1680906498320", "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::tuenlaceinmobiliariodevelopmentbucket/*" } ] } I need to be able to load images from django admin, but the page loads only in html, the admin tried to load static files from the bucket and I don't know how to make it work correctly, I can still navigate to the create images form, however when I fill out the file form and press the button save, the manager throws an ERR_EMPTY_RESPONS error. Even so, the image is stored in the Amazon S3 bucket, but django admin stops working. This is my configuration #model class Image(Item,models.Model): image = models.ImageField( upload_to='images/' ) #admin @admin.register(Image) class ImageAdmin(admin.ModelAdmin): list_display = ( 'nombre', 'descripcion', 'image' ) search_fields = ( 'nombre', 'descripcion', 'image' ) #compose_file DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" STATICFILES_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" COLLECTFAST_STRATEGY = "collectfast.strategies.boto3.Boto3Strategy" -
django on_delete = DO_NOTHING
I am developing an app where I need some of the data to be protected even when some models are deleted. I've been reading on the on_delete options, and seems to be a lot of warnings against using on_delete=DO_NOTHING. In my case, I need the results to be maintained even when a yacht or event gets deleted. The basic structure is this; # models.py class Yacht(models.Model): yacht_name=models.CharField(max_length=100) class Event(models.Model): event_name=models.CharField(max_length=100) yachts = models.ManyToManyField(Yacht, through="Result") class Result(models.Model): yacht = models.ForeignKey(Yacht, on_delete=DO_NOTHING) event = models.ForeignKey(Event, on_delete=DO_NOTHING) ranking = models.IntegerField(max_lenght=4) For record keeping, I need the results to remain even if a yacht or event is deleted. What is the best approach here? Some thoughts; Create additional Result field (_yacht = models.CharField()) and use a post_save signal to provide a string. Create a separate table to keep records of the events. Table gets created/updated at post_save Thanks in advance, J -
Django deployment missing/admin view css/media/static files
I developed an e-commerce project, and I tried to publish it in my domain. When I publish my website, I see that media/static files and admin view css is missign in my website. (Of course, everything works fine in development mode localhost server.) I bought the web server and domain from Antagonist.nl by knowing it supports Python; however, they do not give me any technical support to deploy my Django project, and I see that documentation is missing. When I do deploy my project in antagonist.nl webserver provider, I see it works with errors. Altough I see many similar posts are available in stackoverflow, I couldn't find the answers for my case yet. Moreover, I see need of manual work from Django documentation in this https://docs.djangoproject.com/en/4.2/howto/static-files/deployment/. However, they are all for apache and nginx web servers. I would like to get help from the community for my webserver. Part of my settings.py file: from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = False INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'store', # Django app 'cart', # Django app 'account', # Django app 'payment', # Django app 'mathfilters', … -
GenericForeignKey in Django Admin Panel
I'm having issues with displaying GenericForeignKey fields in the Django Admin Panel. Additionally, I'm wondering if there's a way to vary the options for the object ID field based on the content type, while ensuring that the selected ID is saved correctly. Can anyone offer guidance or suggestions on how to accomplish this? Thanks in advance for your help.enter image description here I need help to improve the wording of the following issue. I've tried creating forms with JavaScript and modifying the admin, but the closest I got was using JavaScript to change the options and display them correctly. However, I had trouble with self.cleaned_data not saving the new choices when they varied, and form.is_valid() always returned false due to validation issues and lost data. from django.contrib import admin from django.contrib.contenttypes.models import ContentType from django.contrib.admin.widgets import ForeignKeyRawIdWidget from django.core.exceptions import ValidationError from django.forms.widgets import ClearableFileInput from django.forms import ModelForm, ModelChoiceField from django import forms from .models import PlaylistContent, Playlist, Image, Video from django import forms class PlaylistContentForm(ModelForm): object_select = forms.ChoiceField( choices=[], widget=forms.Select() ) class Meta: model = PlaylistContent fields = '__all__' class Media: js = ('admin/playlist_content/playlist_content.js',) def update_object_select_choices(self, choices): print(choices) self.fields['object_select'].choices = choices def __init__(self, *args, **kwargs): global EDIT_DATA_FORM super().__init__(*args, … -
CSS files not showing up in Django
Setting up a new Django project and can't seem to get the CSS sheets to load. I added a directory in the base directory of my project named 'static'. Inside of that I have a directory named 'css' and inside of that I have a file named 'styles.css' At the moment I just want to prove everything is connected and functioning properly so the styles.css has only one line. In styles.css: h1 { color: orange; } In Settings.py: STATIC_URL = "static/"` STATICFILES_DIRS = [os.path.join(BASE_DIR, "static"),] In base.html: {% load static %} <link rel="stylesheet" href="{% static 'css/styles.css' %} The template is showing fine in the browser. It's simply a h1 tag that reads: 'hi' The text color is black and it should be orange according to CSS. -
How to check if a user is subscribed to a product in Django template
I am working on a Django project whereby I want to check if a user is subscribed to a product or not. I have created in my models.py several model instances and I am stuck on how to check if the user is subscribed inside the template. Here is my template where I loop through the fetched data: <ul> {% for content in content %} {% if content.model.is_premium and user.is_subscribed %} <li>Premium</li> {% else %} <li>Not premium</li> {% endif %} {% endfor %} </ul> Here is my views.py : @login_required(login_url='/user/login') def homepage(request): content = ModelContent.objects.all() categorys = Category.objects.all() models = MyModels.objects.all() suggestions = MyModels.objects.all()[:3] # profiles = Profile.objects.filter(user__is_creator=True) context = {"categorys": categorys, "models": models, "content":content, "suggestions":suggestions} return render(request, 'users/home.html', context) And here is the models.py: User = get_user_model() class MyModels(models.Model): owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null=False, blank=False) name = models.CharField(max_length=500, null=False, blank=False) username = models.CharField(max_length=500, null=False, blank=False, unique=True) title = models.CharField(max_length=500, null=False, blank=False) description = models.TextField(max_length=500, null=False, blank=False) image = models.ImageField(upload_to='img', blank=True, null=True) placeholder = models.ImageField(upload_to='img', blank=True, null=True) sex = models.CharField(max_length=50, choices=SEX_CHOICES, default=NONE) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=False, blank=False) content_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True, editable=False) created = models.DateField(auto_now_add=True) is_popular = models.BooleanField(default=False) is_premium = models.BooleanField(default=False) # posted_content = models.ManyToManyField('ModelContent', related_name='model_content') def __str__(self): … -
ERROR: Failed building wheel for reportlab
I am trying to install a project from git hub and tried to install libraries using requirements.py and for some reason its just giving me this error ERROR: Failed building wheel for reportlab, I don't know much of python just doin this for sake of college project haha. I am currently using python 3.11 git hub repo I am using : https://github.com/Jawwad-Fida/HealthStack-System/ -
I want to link one model field to another
I want to be able to show unit_price field on the orderItems model the same price as the photograph model. OrderItem class OrderItem(models.Model): order = models.ForeignKey( Order, on_delete=models.PROTECT, null=True, blank=True) product = models.ForeignKey( Photograph, on_delete=models.PROTECT, null=True, blank=True) quantity = models.PositiveBigIntegerField(default=0, null=True, blank=True) unit_price = models.DecimalField(max_digits=6, decimal_places=2, validators=[MinValueValidator(1)] ) order_added = models.DateTimeField(auto_now_add=True) def __str__(self): return 'ID: %s' % (self.order.id) Photograph model class Photograph(models.Model): photo = models.ImageField(null=False, blank=False, upload_to="photos/", default="default.png") title = models.CharField( max_length=100, null=False, blank=False, default="") description = models.TextField() date = models.DateTimeField(auto_now_add=True) slug = models.SlugField() price = models.DecimalField(max_digits=6, decimal_places=2, validators=[MinValueValidator(1)] ) inventory = models.IntegerField() last_update = models.DateTimeField(auto_now=True) promotions = models.ManyToManyField(Promotion, blank=True) -
How can I order_by using difference in annotation Django
I have two models which refer to a third The 1st one: class question(models.Model): title = models.CharField(max_length=100) description = models.TextField(max_length=1000) tag = models.ManyToManyField('tag',related_name='tgs') publicationMoment = models.DateTimeField(auto_now=True) authorId = models.ForeignKey('user',on_delete=models.PROTECT,default = 1) objects=questionManager() def __str__(self): return f'{self.title}' And 2 objects that refer to question: class upvoteQuestion(models.Model): question = models.ForeignKey('question',on_delete=models.CASCADE) user = models.ForeignKey('user',on_delete=models.CASCADE) class downvoteQuestion(models.Model): question = models.ForeignKey('question',on_delete=models.CASCADE) user = models.ForeignKey('user',on_delete=models.CASCADE) I need to sort questions by difference of number of entries like this: class questionManager(models.Manager): def orderByRating(self): return question.objects.annotate( likes = Count('upvotequestion'), dis = Count('downvotequestion') ).annotate( rat = F('likes')-F('dis') ).order_by( '-rat','-publicationMoment' ) I tried this: class questionManager(models.Manager): def orderByRating(self): return question.objects.annotate(rat = Count('upvotequestion')-Count('downvotequestion')).order_by('-rat','-publicationMoment') and this: def orderByRating(self): return question.objects.annotate(rat = F('upvotequestion')-F('downvotequestion')).order_by('-rat','-publicationMoment') But it still doesn't work -
Django Http response/Json Response?
I need help getting my receipt printer working with post/get commands. Here is the code in django/python. It runs without any error message, but it's not printing anything import requests import json from email import header import mimetypes import urllib.request from urllib import response from django.http import HttpResponse from django.http import JsonResponse content = "some content" if request.method == "POST": data = {"jobReady": "true", "mediaTypes":["text/plain"]} return JsonResponse(data) if request.method == "GET": data = open("print.txt","r") response_r = { 'response':data, 'status':200, 'mimetype':'text/plain' } return HttpResponse(response_r) if request.method == "DELETE": status_code = request.GET['code'] if (status_code == "200 OK"): print("Success") return HttpResponse(status=200) if (status_code == "211 OK Paper Low"): print("Success, Paper Low") return HttpResponse(status=200) Here's the code in flask. It's working and printing properly, but I want to rewrite it in Django. from email import header import mimetypes from urllib import response import urllib.request from flask import Flask, request, jsonify, Response, make_response app = Flask(__name__) #flask --app CloudPRNTDemo run -h 192.168.1.218 -p 8000 @app.route('/') def home(): yes = ("home page") return(yes) @app.route('/print/', methods=['POST', 'GET', 'DELETE']) def cloudPRNTPOST(): if request.method == "POST": data = {"jobReady": "true", "mediaTypes":["text/plain"]} print(data) return jsonify(data) if request.method == "GET": data = open("print.txt","r") response_r = app.response_class( response=data, status=200, mimetype='text/plain' ) # … -
Django-filter filtering by relation model associated with the second model
Have a DRF, django-filter and 3 models: Product model that has properties. class Product(models.Model): id = models.UUIDField(primary_key=True, verbose_name='ID', default=uuid.uuid4, editable=False, unique=True) code = models.CharField(max_length=128, blank=True, default='',) name = models.CharField(max_length=250, blank=True, default='') group = models.ForeignKey(Group, on_delete=models.SET_NULL, null=True, blank=True, related_name='products_group') properties = models.ManyToManyField(PropertyVariant, blank=True) # <--- property value price = models.DecimalField(max_digits=10, decimal_places=2, default=Decimal('0')) quantity = models.IntegerField(default=0) is_active = models.BooleanField(default=False) def __str__(self): return f'{self.name}' A property model whose type is specified in its associated model. class PropertyVariant(models.Model): id = models.UUIDField(primary_key=True, verbose_name='ID', default=uuid.uuid4, editable=False, unique=True) value = models.CharField(max_length=256, blank=True, default='') property_id = models.ForeignKey(Property, on_delete=models.CASCADE, null=True, blank=True) # <--- next relation def __str__(self): return f'{self.value}' Model of property types. class Property(models.Model): id = models.UUIDField(primary_key=True, verbose_name='ID', default=uuid.uuid4, editable=False, unique=True) name = models.CharField(max_length=256, blank=True, default='') value_type = models.CharField(max_length=256, blank=True, default='') def __str__(self): return f'{self.name}' I need to filter Products by PropertyVariant , but also need to specify which values exactly the filtering is performed on (Property).. How to do it in django-filter?... Thanx! -
Django combining the names of my two apps, and saying no module named that, with a module not found error
I'm new to django and doing my first project, I have just made a second app for my project, and I had thought that I set everything up properly. But when I try to runserver it comes up with: "ModuleNotFoundError: No module named 'homepagecourses'". My two apps are called homepage and courses respectively. I tried to add "homepagecourses" into my installed apps in settings but then it just said it couldn't find "homepagecourseshomepagecourses". My file directory looks like this -
Passing variables from view to Javascript code in Django
I have a template like the below in Django {% extends 'reports/base.html' %} {% block title %} Report Name {% endblock %} {% block content %} <!-- <div class="container-fluid"> <div class="row"><div class="col"> <ul class="list-group"> {% for r in report_list %} <li class="list-group-item"><a class="link-offset-2 link-underline link-underline-opacity-0" href={% url 'reports' report_id=r.id %}>{{ r.report_name }}</a></a></li> {% endfor %} </ul> </div><div class="col"></div><div class="col"></div></div> </div>--> <div class="demo-container"> <div id="sales"></div> <div id="sales-popup"></div> </div> <script> $(() => { let drillDownDataSource = {}; $('#sales').dxPivotGrid({ allowSortingBySummary: true, allowSorting: true, allowFiltering: true, allowExpandAll: true, showBorders: true, showRowGrandTotals: false, showColumnGrandTotals: false, fieldChooser: { enabled: true, }, export: { enabled:true }, onCellClick(e) { if (e.area === 'data') { const pivotGridDataSource = e.component.getDataSource(); const rowPathLength = e.cell.rowPath.length; const rowPathName = e.cell.rowPath[rowPathLength - 1]; const popupTitle = `${rowPathName || 'Total'} Drill Down Data`; drillDownDataSource = pivotGridDataSource.createDrillDownDataSource(e.cell); salesPopup.option('title', popupTitle); salesPopup.show(); } }, onExporting: function(e) { var workbook = new ExcelJS.Workbook(); var worksheet = workbook.addWorksheet('Main sheet'); DevExpress.excelExporter.exportPivotGrid({ worksheet: worksheet, component: e.component, customizeCell: function(options) { var excelCell = options; excelCell.font = { name: 'Arial', size: 12 }; excelCell.alignment = { horizontal: 'left' }; } }).then(function() { workbook.xlsx.writeBuffer().then(function(buffer) { saveAs(new Blob([buffer], { type: 'application/octet-stream' }), 'PivotGrid.xlsx'); }); }); e.cancel = true; }, dataSource: { fields: [ /*{ caption: … -
Adding custom expensive field on Django model serializer
Normally, in Django, using rest_framework, to add a custom field to a model, you can use SerializerMethodField. From what I understand however, this works great for values that are easy to calculate, but if the value requires database queries to related tables, you're going to be performing these for every item being returned. If I have a ViewSet like this: class ProductViewSet(ModelViewSet): queryset = models.Product.objects.all() serializer_class = serializers.ProductSerializer ... And a Serializer like this: class ProductSerializer(ModelSerializer): class Meta: model = models.Product fields = "__all__" How do I run a bulk query to get some data from a related table for all the products being serialized, and attach it to a new field. Ex: if each product is attached to an Order, maybe I want to add an order_number field. I could do this: class ProductSerializer(ModelSerializer): order_number = SerializerMethodField() @staticmethod def get_order_number(obj): return obj.order.order_number class Meta: model = models.Product fields = "__all__" But if the view is returning 100 products, that will be 100 database queries. Is there a more efficient way to do this? -
wrong email is saved in the database in Django
I am working on a project where users have to signup first to use this application. I attached the signup code below. views.py # Create your views here. def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) # post request is gonna contain data in the message body and validate that form data if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}. You are now able to log in.') return redirect('login') else: form = UserRegisterForm() # display a blank form return render(request, 'users/signup.html', {'form': form}) {% extends 'users/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="container"> <section id="formHolder"> <div class="row"> <!-- Brand Box --> <div class="col-sm-6 brand"> <a href="#" class="logo">Bookstagram <span>.</span></a> <div class="heading"> <h3>Bookstagram</h3> <p>Show Off Your Bookish Aestheics</p> </div> </div> <!-- Form Box --> <div class="col-sm-6 form"> <!-- Signup Form --> <div class="login form-peice"> <form class="login-form" method="POST"> {% csrf_token %} <fieldset class="form-group"> {{ form|crispy }} </fieldset> <div class="CTA"> <input type="submit" value="Signup Now" id="submit"> <a href="{% url 'login' %}">I have an account</a> </div> </form> </div><!-- End Signup Form --> </div> </div> </section> </div> {% endblock content %} if I give a wrong email such as "cindrella@gmail.c" or "cindrella@g.com", the system save the user details in … -
Each time I create superuser, Django saves the user but throws an error that user already exists even if it has never existed
I am fairly new to advanced Django and using Django 4.2 and PostGreSql 9.5 with PgAdmin4. I am trying to create a website, where users can sign in with email and password. I have created the models like so: class Users(AbstractBaseUser): id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) email = models.EmailField(db_index=True, unique=True, max_length=250, blank=True, null=True) is_email_verified = models.BooleanField(default=False, help_text='this designates if the user\' email is verified') is_active = models.BooleanField(default=True, help_text='this designates if the user is active') is_staff = models.BooleanField(default=False, help_text='this designates if the user is staff or not') password = models.CharField(max_length=200, verbose_name='password of user') is_superuser = models.BooleanField(default=False, help_text='this designates if the user is superuser or not') last_login = models.DateTimeField(verbose_name='Last login of user', auto_now_add=True) created_time = models.DateTimeField(auto_now_add=True, verbose_name='Time user was created') USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: unique_together = ['id', 'email'] objects = UserManager() my user manager class is like this: class UserManager(BaseUserManager): def _create_user(self, email, password=None, **kwargs): if not email: raise ValueError('Email must be provided') user = self.model( email = self.normalize_email(email), **kwargs ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **kwargs): kwargs.setdefault('is_active', True) kwargs.setdefault('is_superuser', False) kwargs.setdefault('is_staff', False) user = self.model( email=self.normalize_email(email), password=password, **kwargs ) user.save() return self._create_user(email, password, **kwargs) def create_superuser(self, email, password=None, **kwargs): kwargs.setdefault('is_active', True) kwargs.setdefault('is_staff', True) … -
Reference Django Model Field from iterator in a for loop
I am attempting to create a model record using a for loop and cannot figure out how to reference the model field in a django create() function. I have mirrored response keys to the model fieldnames and want to loop through the response keys and assign the values in the model. Here is a simplified example. r = requests.get(url) r = r.json() ModelOne.objects.create( for field in r: ModelOne.field = r[field] ) I am trying to create the equivalent of ModelOne.Objects.create( fieldone = r[fieldone] ,fieldtwo = r[fieldtwo] ) Model: class ModelOne(models.Model): fieldone = models.IntegerField(blank=True, null=True) fieldtwo = models.IntegerField(blank=True, null=True) What I do not think works is trying to use .field in ModelOne.field as the object attribute. It doesn't return any errors but does not save the record either. I have also tried using raw sql with the django connection library but run into many other hurdles with that method. Is there a way to do this using the QuerySet API or should I be looking into another way? -
How implement a transactions to cashbox report system in Django?
`models.py # Cash Testing Models class Balance(models.Model): date = models.DateTimeField() amount = models.FloatField() detail = models.CharField(max_length=50) class Meta: verbose_name_plural = '8. Balance' def __str__(self): return str(self.amount) #def save(self, *args, **kwargs): #super().save(*args, **kwargs) #cashsystem = Cashsystem.objects.filter(amount=self.balance.amount).order_by('-id').first() class Income(models.Model): amount = models.FloatField() details = models.CharField(max_length=50, blank=True) income_date = models.DateTimeField() class Meta: verbose_name_plural = '9. Income' def save(self, *args, **kwargs): super().save(*args, **kwargs) cashsystem = Cashsystem.objects.filter(amount=self.balance.amount).order_by('-id').first() if cashsystem: ending_cash= cashsystem.amount + self.amount cashsystem.save() else: Cashsystem.objects.create( amount=self.balance.amount, income=self, expenses=None, income_amount=self.amount, expenses_amount=None, ending_cash=self.amount, ) class Expenses(models.Model): amount = models.FloatField() details = models.CharField(max_length=50, blank=False) expenses_date = models.DateTimeField() class Meta: verbose_name_plural = '10. Expenses' def save(self, *args, **kwargs): super().save(*args, **kwargs) cashsystem = Cashsystem.objects.filter(amount=self.balance.amount).order_by('-id').first() if cashsystem: ending_cash=cashsystem.amount - self.amount cashsystem.save() else: Cashsystem.objects.create( amount=self.balance.amount, income=None, expenses=self, income_amount=None, expenses_amount=self.amount, ending_cash=self.amount, ) #super().save(*args, **kwargs) # cash Model Testing class Cashsystem(models.Model): #date=models.DateTimeField(default=Cash.objects.date()) # add default value here amount = models.ForeignKey(Balance, on_delete=models.CASCADE,default=Balance.objects.first()) income = models.ForeignKey(Income, on_delete=models.CASCADE, default=0, null=True) expenses = models.ForeignKey(Expenses, on_delete=models.CASCADE, default=0, null=True) income_amount= models.FloatField(default=0, null=True) expenses_amount= models.FloatField(default=0, null=True) ending_cash = models.FloatField() class Meta: verbose_name_plural = 'Cash Box Entries' #ordering = ('-income__income_date', '-expenses__expenses_date') def income_date(self): if self.income: return self.income.income_date def expenses_date(self):`your text` if self.expenses: return self.expenses.expenses_date - I am building a personal Cash box management system, That will store My opening balance to … -
one .html file not getting logo.png file from the correct location
I'm working on creating a web application running in python3.10 using Django, most pages are working as expected but one page does not display the logo correctly, I get the following error: Not Found: /products/media/logo.png [09/Apr/2023 11:45:03] "GET /products/media/logo.png HTTP/1.1" 404 3536 The issue with this is that all of my .html files are currently using a base.html file and all of the other extend that to maintain the sites formatting using {% extends 'base.html' %} the path to the logo file only exists in the base.html file and only one page doesn't load the image correctly, ALL of the others do. it's also odd because there is no 'products/media' path in my project, in fact there isn't even a products folder so I'm not sure why it's trying to use this path, I've double and triple checked everything I can think of and I can't figure out why this page is attempting to get the logo.png file from a different location than all the other pages, for reference the html for this page is very simple: `{% extends 'base.html' %} {% block content %} <h1>{{ toy.name }}</h1> <p>{{ toy.description }}</p> <p>Price: ${{ toy.price }}</p> <img src="{{ toy.image.url }}" alt="{{ … -
Apache 403 Error - I can't access outside my Virutal Machine
I have built and deployed a Django app on Apache Server 2.4 but when I try to access it outside my host computer; (It's a Windows Server 2019 on VirtualBox). It pops 403 error. This is the error I have granted all the permissions on the firewall and I keep getting this error. -
How to force the www. on heroku
I have my domain on infomaniak and my django application on heroku my application work when i go to https://WWW.{{domain}} but i can't access to https://{{domain}} (without WWW.) thanks -
Users - Change Account Info Using Forms
I was trying to create a site that is responsible for editing profile info: Edit_profile.html file: {% extends 'base.html' %} {% block body %} <div class="container"> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> <br> </div> {% endblock %} and edit_profile is defined by: def edit_profile(request): if request.method =='POST': form = UserChangeForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('/Nornik/profile') else: form = UserChangeForm(instance=request.user) args = {'form': form} return render(request, 'Nornik/edit_profile.html', args) Everything is working fine (system detects no issues.), but what i recive as request is a site with login data, that I can't edit, although I defined it it my file (in urls.py everything is set properly re_path('profile/edit_profile/', views.edit_profile, name='edit_profile')). That's why i think that i should be able to edit that. Other articles on stackoverflow didn't help. Thanks for help. -
Django / Postgres and random Operational Error - Connection closed
We are having a hairy Django issue for a while now that keeps coming and going randomly. Every once in a while we get Operational Error - Connection closed. (see error below). We are running Django 4.2 / Py3.11 - pgbouncer - PostgreSQL 14 (EC2 + RDS in AWS). We have never had anything like this, do nothing but plain-vanilla django create/save stuff and started happening once in a while in Django 4 and forward. Anyone experiencing similar things or have a clue what could be going on??? Error message OperationalError: the connection is closed File "django/db/backends/base/base.py", line 308, in _cursor return self._prepare_cursor(self.create_cursor(name)) File "django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "django/db/backends/postgresql/base.py", line 331, in create_cursor cursor = self.connection.cursor() File "psycopg/connection.py", line 840, in cursor self._check_connection_ok() File "psycopg/connection.py", line 479, in _check_connection_ok raise e.OperationalError("the connection is closed") OperationalError: the connection is closed Django DB settings are: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', ... "DISABLE_SERVER_SIDE_CURSORS": True, "CONN_MAX_AGE": None, "CONN_HEALTH_CHECKS": True }, } [gunicorn] workers = multiprocessing.cpu_count() * 2 + 1 keepalive = 120 timeout = 120 graceful_timeout = 120 worker_connections = 1000 worker_class = 'sync' [pgbouncer] pool_mode = transaction default_pool_size = 100 min_pool_size = 20 reserve_pool_size = 30 …