Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I upload a picture to my blog using the Django administration
I'm a complete beginner in Django, now after reading some articles I've managed to build a blog in Django where I can post (all through the Django administration). However, I also wanted to be able to add an image to my post, so I created an image field in my model, now it is also possible to upload images through the Django administration, these are then stored in the media/images folder. However, until now (after reading some articles) I haven't managed to display these pictures in my blog posts. Please excuse the probably a little stupid question and thanks a lot for the help Bennet My models.py file from django.db import models # Create your models here. class Post(models.Model): title = models.CharField(max_length= 255) slug = models.SlugField() intro = models.TextField() body = models.TextField() image = models.ImageField(upload_to='images/') date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Meta: ordering = ['-date_added'] the page where I want to display the image {% block content %} <div class="section title is-size-5 has-text-centered"> <div class="title">{{post.title}}</div> <div class="subtitle">{{post.date_added}}</div> </div> <div class="container"> <div class="columns"> <div class="column is-8 is-offset-2"> <div class="blob"> <img src="{{post.image}}" alt=""> {{post.body}} </div> </div> </div> </div> {% endblock content %} -
Integrity Error on Django ForeignKey relations
I have three django models related by Foreign keys as shown below class Table1(models.Model): ... class Table2(models.Model): table1 = models.ForeignKey("Table1", on_delete=models.CASCADE, related_name="rel_table2") class Table3(models.Model): table2 = models.ForeignKey("Table2", on_delete=models.CASCADE, null=True, default=None, related_name="rel_table3") So in essence, each Table1 object has one or more Table2 objects and each table 2 object also has one or more Table3 objects. When I delete a Table1 object, I expect the related Table2 and Table 3 to be cascade-deleted. But instead I get an Integrity error IntegrityError: FOREIGN KEY constraint failed unless I first delete in order the related Table3 and Table2 objects. (Same for when I delete a Table2 object -I'm only able to delete it when I delete manually all the related Table3 objects) Am I doing something wrong? (I am using Django 3.2) I changed the Table3 model by removing the options null=True and default=None as shown below class Table3(models.Model): table2 = models.ForeignKey("Table2", on_delete=models.CASCADE, related_name="rel_table3") and the cascading delete works for this. But that is unexpected. Why does it work? -
Django templating to wrap code in separate html syntax
I've picked up an older application that uses Bootstrap3 on Django. With Django templating I want to wrap a block of code in it's own template file which would sit outside of the bootstrap container. It's for a step menu that has two buttons "Back" and "Next" and at each step it has unique logic so I want to keep that in the file but just wrap the buttons in a new template that allows me to break out of the page container and stick the nav to the bottom of the page. Does Django have a template tag for this? -
What is `@stringfilter` in Django?
I sometimes see @stringfilter with @register.filter. So, I created test filter with @stringfilter as shown below: # "templatetags/custom_tags.py" from django.template import Library from django.template.defaultfilters import stringfilter register = Library() @register.filter(name="test") @stringfilter # Here def test_filter(num1, num2): return But, it accepted int type values without error as shown below: # "templates/index.html" {% load custom_tags %} {{ 3|test:7 }} # Here I thought that @stringfilter only accepts str type values giving error for the other types. So, what is @stringfilter in Django? -
Line graphs overlap in JavaScript used with Django
I am using Google Chart JS lib for chart display with Django. I am sending the data to be shown in the graph as an array by packing it piece by piece in python. Everything is fine, including the processing of the data. But while it normally needs to plot 3 different graphs, it uses the data of 3 graphs in all 3 graphs and overlaps them. My Code: {% for graph_index in 1|custom_range:all_graph_data %} var graphId = 'curve_' + '{{ graph_index }}' var data_{{ graph_index }} = new google.visualization.DataTable(); data_{{ graph_index }}.addColumn('number', 'Time'); data_{{ graph_index }}.addColumn('number', 'Current'); data_{{ graph_index }}.addColumn('number', 'Voltage'); {% for graph_values in all_graph_data|index:graph_index %} data_{{ graph_index }}.addRow([{{ graph_values|index:2 }}, {{ graph_values|index:0 }}, {{ graph_values|index:1 }}]); {% endfor %} var chart = new google.visualization.LineChart(document.getElementById(graphId)); chart.draw(data_{{ graph_index }}, options); {% endfor %} // add graph {% for graph_index in 1|custom_range:all_graph_data %} <div class="container" id="curve_{{ graph_index }}"></div> {% endfor %} Normally a graph should look like this: https://prnt.sc/nEQv6-eTk1lw But my graph:https://prnt.sc/gOaN_08yDulN Version: Python: 3.9.0 Django: 4.2.2 I sent my data packaged in several different ways. Same problem. -
How would end-to-end encryption work in a file transfer website? [closed]
With Django, I'm doing a file transfer website. One use will upload a file and then the recipient will download the file. I want to encrypt this file securely so that the encryption key is not stored on the server. I understand how end-to-end encryption works, but I can't achieve this with a Django website since you need to store a private key on a device (websites can't do this, unless you know a way to do this). How can I encrypt a file when it is uploaded to the server, then somehow decrypt the same file in the recipients end without having to store the encryption key. -
How to display duplicates objects in a queryset
I have a model Stock and I'm trying to find duplicates in db. When I do the filter Stock.objects.filter(component__in=components), I expect to see duplicates, but this filter excludes dups, but I need to display all of them. For example: my list of components is: 1 2 3 1 (this ones are subcomponents of components but I can convert it to component objects) 2 (this ones are subcomponents of components but I can convert it to component objects) 3 (this ones are subcomponents of components but I can convert it to component objects) 4 5 6 etc. Here comes my problem, in the filter, it deletes the 1, 2 and 3 objects under the first 3 object because it has the same ID, but I want to display them all. def get_custom_queryset(self): params = {} reference = False for param in iter(self.request.GET): if param.startswith('Search_'): search = param[7:] if search == 'inventory': try: inventory = self.request.GET[param] if inventory == 'on': components, stock_codes = [], [] stock = Stock.objects.filter(is_inventory=True) # Cannot be first() because in self.table it requires a queryset instead of a list for s in stock: stock_codes.append(s.component.code) components_on_inventory = Component.objects.filter(code__in=stock_codes) for coi in components_on_inventory: if coi.has_subcomponents(): qs_sc = [] components.append(coi) for … -
AttributeError: 'function' object has no attribute 'register_battery'
I have been getting this error in my views.py file.: AttributeError: 'function' object has no attribute 'register_battery' [26/Jun/2023 21:39:53] "POST /fontriden/fontriden/manufacturer/battery/registration/ HTTP/1.1" 500 69541 views.py def battery_registration(request): if request.method == 'POST': form = BatteryRegistrationForm(request.POST) if form.is_valid(): manufacturer = request.user.manufacturer # Process form data and register battery battery_id = interact_with_smart_contract.register_battery( form.cleaned_data['product_name'], form.cleaned_data['certification_mark'], form.cleaned_data['serial_number'], form.cleaned_data['watt_hours'], ) request.session['battery_id'] = battery_id return redirect('battery_registration_success') else: form = BatteryRegistrationForm() return render(request, 'battery_registration.html', {'form': form}) blockchain.py # Define the functions for interacting with the smart contract def register_battery(w3, contract, product_name, certification_mark, serial_number, watt_hours): tx_hash = contract.functions.registerBattery( product_name, certification_mark, serial_number, watt_hours ).transact() receipt = w3.eth.waitForTransactionReceipt(tx_hash) # Process the transaction receipt or handle any events emitted by the contract # ... models.py from django.db import models from django.contrib.auth.models import User class Manufacturer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company_name = models.CharField(max_length=100) # Add any additional fields for the Manufacturer model def __str__(self): return self.user.username class Battery(models.Model): manufacturer = models.ForeignKey(to='fontriden.Manufacturer', on_delete=models.CASCADE, null=True) product_name = models.CharField(max_length=100) certification_mark = models.CharField(max_length=100) serial_number = models.CharField(max_length=100) watt_hours = models.IntegerField() qr_code_url = models.URLField(blank=True) qr_code_filepath = models.CharField(max_length=255) def __str__(self): return self.product_name I had tried placing the functions from the blockchain.py in the views.py but it just gave me more error. I am not sure what to do. This is … -
How to display tasks based on condition and user in a view
I want to check each task that is stored in the model and is supposed to be displayed based on the value stored in the condition field. When I am checking each task during display, if the value inside the condition is equal to True, I want that task to be displayed for all users except users with usernames [‘Electric_Motor_Winding’, ‘Electrical_Panels’, ‘Seller’] until three months after being saved. If the condition is equal to False, I want that task to be displayed only to the user who saved it and only on the day it was saved. So for displaying tasks, tasks must be checked for the date and user they were saved by and then checked for the value of the condition. If the value of the condition is equal to True, that task should be displayed for all users except users with usernames [‘Electric_Motor_Winding’, ‘Electrical_Panels’, ‘Seller’] until three months after being saved. If the value of the condition is equal to False, that task should only be displayed on the day it was saved and only to the user who saved it. class TaskList(LoginRequiredMixin, ListView): model = Task context_object_name = 'tasks' ordering = ['-posted_time'] def get_shamsi_time(self): timezone.activate('Asia/Tehran') now … -
How to use a SASS in a Django Framework?
How to compile a SASS ( Syntactically Awesome Style Sheets) using Django Framework? I can't compile the sass file in django. SASS is a one of the framework of CSS (Cascade style sheet). Using sass in django, 1st need to compile the sass ( to convert into css) and again run the manage.py files . How to rectify that in single compilation? -
Custom user level throttling with Django rest framework
I am trying to set API call limits by tier group. Basically a free tier, a paid tier and another paid tier with more limits. I am using Django rest framework and the issue I keep running into is regardless of what tier the user is set at, I still get throttled at the default rate which in this case is 3/minute. Also wondering if there is a way to have a custom response for each tier level rather than the default throttle response. These are dummy numbers I'm using for testing. Herre is my code throttling.py from rest_framework.throttling import UserRateThrottle class TierBasedRateThrottle(UserRateThrottle): def allow_request(self, request, view): user = request.user if user.is_authenticated: if user.tier_level == 'tier_1': self.rate = '4/minute' # Rate limit for tier 1 users elif user.tier_level == 'tier_2': self.rate = '6/minute' # Rate limit for tier 2 users elif user.tier_level == 'tier_3': self.rate = '10/minute' # Rate limit for tier 3 users return super().allow_request(request, view) settings.py REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',), # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly', 'rest_framework.permissions.IsAuthenticated' ], 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ], 'DEFAULT_PARSER_CLASSES': [ 'rest_framework.parsers.JSONParser', 'rest_framework.parsers.FormParser', 'rest_framework.parsers.MultiPartParser' ], 'DEFAULT_AUTHENTICATION_CLASSES':[ 'knox.auth.TokenAuthentication', ], 'DEFAULT_THROTTLE_CLASSES': [ 'accounts.throttling.TierBasedRateThrottle', ], … -
'Error 404 Page not found' api REST-FRAMEWORK
I've just started using rest-framework and I can't get my page to display.I have a 404 error the page was not found but when I arrive on the home page it knows the destination url . I've added my app in setting.py, I've done my serializer in serializer.py. I've tried all the solutions I've found on stack overflow but nothing works. I'll take any advice and solution you can offer, thank you in advance for your time. (this is my first question on a forum if there are things that are not correct do not hesitate to point them out to me ) lesite/ |--urls.py | |--recup_fichier_api/ | |---urls.py |---views.py lesite\urls.py urlpatterns = [ path("backend_recup_fichier/", include("backend_recup_fichier.urls")), path("admin/", admin.site.urls), path("page_accueil/",include("page_accueil.url")), path('table_config/', include('recup_fichier_api.urls')) ] lesite\recup_fichier_api\views.py class table_configVisewset(viewsets.ModelViewSet) : queryset = table_config.objects.all() serializer_class = config_serializer lesite\recup_fichier_api\urls.py urlpatterns = [ ] router = routers.DefaultRouter router.register = ('table_config', table_configVisewset ) -
how to import all products with a same feature in django import-export
I need to import all products with the same brand. I understand that they need to be selected together, but other than manually, I don't know how to do it. How to select automatically all items with the same characteristics or maybe there is another way. -
django project - problem because the sql server database has column names with spaces, i got how to use it in models.py but not in the template file
the sql server I'm connecting to has column name with spaces in between I changed the models.py but I don't know what to do in the templates file. Code for the template file: <div id="CPU Utilization" class="tabcontent"> <h1>CPU Utilization</h1> <center> <table border = "1"> <tr> <th>SQL Server Process CPU Utilization</th> <th>System Idle Process</th> <th>Other Process CPU Utilization</th> <th>Event Time</th> </tr> {% for datadisplay in sqlserverconn2 %} <tr> <td>{{datadisplay.SQL Server Process CPU Utilization}}</td> <td>{{datadisplay.System Idle Process}}</td> <td>{{datadisplay.Other Process CPU Utilization}}</td> <td>{{datadisplay.Event Time}}</td> </tr> {% endfor %} </table> </center> </div> I tried the using the custom filters and defining attribute but it said it is not a registered tag library. -
pip install -r requirements_dev.txt
I am trying to install requirements for python django using command "pip install -r requirements_dev.txt" but I am getting the following error: × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [2 lines of output] <string>:8: DeprecationWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html proj executable not found. Please set the PROJ_DIR variable.For more information see: https://pyproj4.github.io/pyproj/stable/installation.html [end of output] anyone can help with that ? I tried to install "pyproj" and "proj" but with no hope, and try to set "PROJ_DIR" as mentioned in the error to "venv/bin/proj" but getting: subprocess.CalledProcessError: Command '/Users/../venv/bin/proj' returned non-zero exit status 1. -
I get error 404 on all URLs (when I click on a menu item on home page) in production. Everything works on localhost. What am I missing please?
I have deployed a django app on a shared hosting server using cpanel. The home page loads fine (I see only 1 error - 404 on favicon on developer's console). All the pictures and styling are showing as expected on the home page. I have placed my images on a google cloud bucket and I am referencing CSS/js from CDNs. My problem is that when I click on menu items, none of the the URLs are working. 'File not found' is displayed. On the dev console/Network I see error 404. There are no errors in the logfile. This exact question was asked previously but there was no resolution as far as I can tell: URL working on localhost but not in production I have tried so many things including: Setting DEBUG=True in settings, TEMPLATE_DEBUG=True, specifying default django template loaders one by one then together in TEMPLATES. I have made sure that all my apps are listed in INSTALLED_APPS. I even ran collectstatic and tried pointing DIRS to this static folder. After every change I restart the Python App in Cpanel and clear the browser cache Initially I had installed whitenoise to serve static files but I commented it out in … -
How to check in real time that a email is already registered in django if not then the user should get a cross sign while he is typing the email
How to check in real time that a email is already registered in django if not then the user should get a cross sign while he is typing the email -
What is the free web hosting platform for Django applications? [closed]
I want to host a Django application which is a small application. could anyone suggest to me the free web hosting platform for hosting that Django Application? I need a better web hosting platform for the Django application where the Traffic may get increased -
Django save one image two times in model
I am seeking for solution on how to upload one picture to a two ImageField fields for gallery. Fore this moment I need two upload two pictures. Then do resizing of first "image" to "image300" for gallery. models.py from django.db import models import PIL from PIL import Image from django.db.models.signals import pre_save from django.dispatch import receiver # Create your models here. class Images(models.Model): PICTURES = "PIC" MAPS = "MPS" YOUR_PICTURE = "YOP" GALLERY = [ (PICTURES, "Picture"), (MAPS, "Map"), (YOUR_PICTURE, "Your picture"), ] gallery = models.CharField( max_length=3, choices=GALLERY, default=YOUR_PICTURE, ) name = models.CharField(max_length=200, null=True, blank=True, default='picture') image = models.ImageField(upload_to="images1080/%Y/%m/%d/") image300 = models.ImageField(upload_to="images300/%Y/%m/%d/", null=True, blank=True) def save(self, *args, **kwargs): super().save(*args, **kwargs) def __str__(self): return self.gallery def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) widthCheck = img.width - img.height if img.width > 1080: baseWidth = 1080 wPercent = (baseWidth/float(img.size[0])) hSize = int((float(img.size[1])*float(wPercent))) img = img.resize((baseWidth,hSize), Image.Resampling.LANCZOS) img.save(self.image.path) if widthCheck >= 0: baseWidth = 300 wPercent = (baseWidth/float(img.size[0])) hSize = int((float(img.size[1])*float(wPercent))) img = img.resize((baseWidth,hSize), Image.Resampling.LANCZOS) img.save(self.image300.path) else: new_height = 300 new_width = int(new_height * img.width / img.height) img = img.resize((new_width, new_height), Image.Resampling.LANCZOS) img.save(self.image300.path) I tried to save only image field, but can't resize empty image300 field so it need's some picture link … -
Need to Implement Click Payment Gateway - Uzbekistan
I need to create payment gateway Click which based on Uzbekistan PG. this Doc link :https://docs.click.uz/en/click-api-request/ Here don't understand the implementation flow for Marchant API there is 2 main api : 1. Prepare 2. Complete. I need to implement Marchant API, first I created create invoice API but now I don't understand the flow which api need to create first Prepare/ Complete or only merchant APIS. From when we can get the testing data for Click PG? here is attachment of API which implement. from flask import Flask, request, jsonify import hashlib import time import requests app = Flask(__name__) class ClickPay: def __init__(self): self.baseurl = "https://api.click.uz/v2/merchant/" self.secret_key = 'AAAAAA' self.merchant_id = 1111 self.service_id = 11111 self.merchant_trans_id = 11111 self.timestamp = str(int(time.time())) self.digest = hashlib.sha1((self.timestamp + self.secret_key).encode()).hexdigest() self.auth = f"{self.merchant_trans_id}:{self.digest}:{self.timestamp}" self.accept = "application/json" self.content_type = "application/json" self.headers = { "Accept" : self.accept, "Content-Type" : self.content_type, "Auth" : self.auth } def CreateInvoice(self, amount, phone_number): url = f"{self.baseurl}/invoice/create" request_body = { "service_id" : self.service_id, "amount" : amount, "phone_number" : phone_number, "merchant_trans_id" : self.merchant_trans_id } response = requests.post(url, headers=self.headers, data=request_body) return response def CheckInvoiceStatus(self, invoice_id): url = f"{self.baseurl}/invoice/status/:{self.service_id}/:{invoice_id}" response = requests.get(url, headers=self.headers) return response def CheckPaymentStatus(self, payment_id): url = f"{self.baseurl}/payment/status/:{self.service_id}/:{payment_id}" response = requests.get(url, headers=self.headers) … -
Django: Populate a model field from another model's field and make both amendable by admin
I want to create a database where an admin user can add products via the admin portal. The products will have a category field. I want the admin to also be able to add/remove category types. However I'm relatively new to django and can't work out how to do this. I feel like I need to use a ForeignKey but I'm getting confused about how I link it to the specific category name. I created a Category model and a Product model: class Category(models.Model): created_on = models.DateTimeField(auto_now_add=True) category_image = CloudinaryField('image', default='placeholder') category_name = models.CharField(max_length=50, unique=True) def __str__(self): return self.category_name class Product(models.Model): created_on = models.DateTimeField(auto_now_add=True) main_image = CloudinaryField('image', default='placeholder') item_name = models.CharField(max_length=50, unique=True) slug = models.SlugField(default="", null=False) price = models.DecimalField(max_digits=8, decimal_places=2) style = models.ForeignKey(Category, related_name='category_name', on_delete=models.CASCADE) likes = models.ManyToManyField(User, related_name='product', blank=True) def __str__(self): return self.item_name I've tried to link the style field in the Product model so that it pulls it's data from the category_name field in the Category model. Is this possible? Can I get it to appear as a dropdown on the admin portal somehow? Any help much appreciated! -
multiple django projects in one server using gunicorn and nginx with only ip and ports
I want to ask about deploying multiple django projects in one remote server using gunicorn and nginx. I've learnt that for each project I should create .socket and .service files and also configure nginx. All tutorials and videos I've seen showed project with domains, like (project1.example.com, project2.example.com). I did it once it works perfectly for domains. But what if I want to deploy them just using IP address and port for now, like (project1 in 12.34.56.78:8000, project2 in 12.34.56.78:8001.) I don't have domain and let's say I don't want it right now. Thanks in advance -
Initial form field doesn't set in Django
I have following set up. Model: class Feedbacks(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE, null=True) feedback = models.TextField() rating = models.IntegerField() Form: class FeedbackModelForm(ModelForm): class Meta: model = Feedbacks exclude = ['user_id'] View: @login_required def feedbackPage(request): username = request.user.id if request.method == 'POST': form = FeedbackModelForm(request.POST, initial={'user_id': username}) if form.is_valid(): form.save() return redirect('feedback_success') else: form = FeedbackModelForm() context = {'form': form} return render(request, 'feedback.html', context) Print(username) shows current current authenticated user ID. During the save procedure it doesn't save user_id field (it's NULL). I need that user_id field saved from authenticated user. -
Save data when changing DataBase in Django
I was wondering, if it is possible to move data from one to other database in django? Especially if something happens to the first database. For example: I have this DataBase DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "DataBase", "USER": "user", "PASSWORD": "password", "HOST": "127.0.0.1", "PORT": "5432", } } But something happens to the database. Maybe the entire server falls down! Is it possible, to move the data of my models into a new DataBase? Maybe by presaving or something? DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "NewDataBase", "USER": "new-user", "PASSWORD": "new-password", "HOST": "127.0.0.1", "PORT": "5432", } } -
Django model, How to not read data from an existing database when running my app in test mode
I have a django app that uses two databases, the default db and another readonly db called 'logs'. I create a model called alters (code below) that reads data from a table called logs in a db called logsdb, the alert model is not managed by django except on test mode. myapp/models/alert.py: class Alert(models.Model): class Meta: db_table = "logs" managed = getattr(settings, "MANAGE_ALERT_TABLE", False) id = models.IntegerField(db_column="event_id", primary_key=True) date = models.DateTimeField(db_column="record_time", null=True) label = models.CharField(db_column="name", max_length=64) settings.py: MANAGE_ALERT_TABLE=False # I set this to True when I run django in test mode DATABASES = { "default": { "ENGINE": "django.db.backends." + os.environ.get("DB_DEFAULT_ENGINE", "sqlite3"), "NAME": os.path.join(DB_DIR, DB_NAME), "TEST": {"NAME": os.path.join(BASE_DIR, "test_db.db")}, }, "logsdb": { "ENGINE": "django.db.backends." + os.environ.get("DB_DEFAULT_ENGINE", "sqlite3"), "NAME": os.path.join(DB_DIR, "logsdb.db"), } } I've also created a db router to read from the logs db: from api.models.alert import Alert class DBRouter(object): def db_for_read(self, model, **hints): if model == Alert: return 'logsdb' return None def db_for_write(self, model, **hints): if model == Alert: return 'logsdb' return None def allow_relation(self, obj1, obj2, **hints): return None def allow_migrate(self, db, app_label, model_name=None, **hints): if db == 'default': return True if db == 'logsdb': return False return None The app is working fine except when I run it …