Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to properly use TailwindCSS with Django forms
I'm trying to use TailwindCSS in my Django project and can't find a way to cleanly style forms. There are a ton of ways on the internet, but all of them seem a little bit dirty. The way styling is implemented in Django docs is through widgets, but adding custom attrs to each field of each form doesn't look great, especially with large Tailwind classes. Or maybe I misunderstood how it supposed to be done? And about crispy-tailwind, it's great, but I wanted a little bit more control over styles than it gives. -
Django save override only if anything other than a single field is updated?
I realize a version of this has been asked and answered, but I believe my question is slightly different enough where I could not find an answer. I have a model with a version that I want to increment by 1 any time the object is updated/saved. But I only want to increment the version if any field values were changed other than the program. Put another way, a training's version should not be incremented if the only change was adding or removing a program. There are times where the program will be changed along with other fields, in which case it should increment. models.py class Training(BaseTeamModel): title = models.CharField("Title",max_length=254) description = models.TextField("Description", blank=True) program = models.ManyToManyField(Program,related_name='programs') version = models.IntegerField(default=0) def save(self, *args, **kwargs): # How to increment the version only if fields were changed # other than program. self.version = self.version + 1 super(Training, self).save(*args, **kwargs) I could compare each value with the previous value for each field, but that is not scalable and would result in some messy models. -
request.user.is_authenticated does not work in templates
when using {%if request.user.is_authenticated%} or {%if user.is_authenticated%}, nothing happens because of what it can be? And for some reason, the check for user.is_admin or user.is_staff does not work. footer.html: {% if request.user.is_authenticated %} <li class="footer__widget--menu__list"><a class="footer__widget-- menu__text" href="#">My Account</a></li> {% else %} <li class="footer__widget--menu__list"><a class="footer__widget-- menu__text" href="{% url "users:login" %}">Login</a></li> {% endif %} {% if user.is_admin or user.is_staff %} <li class="footer__widget--menu__list"><a class="footer__widget- -menu__text" href="{% url "admin:index" %}">Admin Panel</a></li> {% endif %} it is used in main.html: {% include "includes/footer_section.html" %} Maybe because of this I redefined the usermodel to my own usermodel? I found a similar question, but it didn't help -
how can I render tag set in my django template
I'm trying to render tags from a many to many relationship but I'm missing something These are my models: class Post(models.Model): date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='posts', null=True, blank=True) title = models.CharField(max_length=200) content = models.TextField(null=True, blank=True) image = models.ImageField(upload_to='post/images/', null=True, blank=True) slug = models.SlugField(max_length=200, unique=True, null=True, blank=True) tag = models.ManyToManyField('Tag', related_name='posts', blank=True) def save(self, *args, **kwargs): if self.image: ext = os.path.splitext(self.image.name)[1] filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}{ext}" self.image.name = filename if not self.slug: self.slug = slugify(self.title) return super().save(*args, **kwargs) class Tag(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True, blank=True) post = models.ManyToManyField(Post, related_name='tags', blank=True) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) return super().save(*args, **kwargs) def __str__(self): return self.name This is my template snippet {% for post in posts %} <div class="news-card"> <img src="{{post.image.url}}" class="news-img" alt="News" /> <div class="news-listing"> <ul class="tags"> {% for tag in post.tag.all %} <li class="tag">{{tag.name}}</li> {% endfor %} </ul> <h3 class="news-title"> <a href="{{post.slug}}" >{{post.title}}</a this is my view and context I'm passing form = MessageForm() context = { 'posts': posts, 'events': events, 'introductorys': introductory, 'products': products, 'form': form, 'authors': 'authors', } return render(request, 'app/index.html', context) I expect a list of tags to generate but the template is not generating any tags -
Uploading a python file in a django admin dashboard to excecute an excel file
i'm a beginner working on a django project, django admin dashboard, using mysql database, one of the tasks is uploading an excel file and execute it with a python file then showing the result. there are 3 types of python files and 3 types of excel files. i should use type1 of python file to execute type1 of excel file, type2 of python file to execute type2 of excel file and type3 of python file to execute type3 of excel file. as it showsenter image description here the images uploading the files is easy butthe main problem is in the executing part it always shows a lot of errors and i'm just a beginner and this is my graduation year i need your help please ! -
Django Autocomplete Light Foreign Key not rendering
I believe I have tried everything but still my field is not rendering. My objective is to be able to find products writing their names. I tried to followed this tutorial: https://django-autocomplete-light.readthedocs.io/en/master/tutorial.html#tutorial My diferent files are like this: models.py: # Product class class Product(models.Model): name = models.CharField(max_length=100) sku = models.CharField(max_length=50, unique=True) category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT, default=get_default_category) availability = models.CharField(max_length=20, choices=[('E', 'Existent'), ('O', 'On demand')]) price = models.IntegerField(default=0) def __str__(self): return self.name # Sales orders class class SaleID(models.Model): date = models.DateTimeField() class Sale(models.Model): ID = models.ForeignKey(SaleID, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() total_price = models.PositiveIntegerField() def __str__(self): return f"Sale of {self.quantity} {self.product.name} for {self.total_price}" forms.py: from dal import autocomplete # Add Product Form to add products class SaleForm(forms.ModelForm): product = forms.ModelChoiceField(queryset=Product.objects.all(), widget=autocomplete.ModelSelect2(url='product-autocomplete')) quantity = forms.IntegerField(required=True, widget=forms.NumberInput(attrs={"placeholder":"Enter quantity", "class":"form-control"}), label="") class Meta: model = Sale fields = ("product", "quantity") # Define the fields to include from the Product model exclude = ("user", "ID", "total_price") SaleModelFormSet = modelformset_factory(Sale, form=SaleForm, extra=1, can_delete=False) views.py: # SALES ADD def add_sale(request): if request.user.is_authenticated: if request.method == "POST": saleid_instance = SaleID.objects.create(date=timezone.now()) sale_formset = SaleModelFormSet(request.POST) # Create instance of SaleFormSet if sale_formset.is_valid(): saleid_instance.date=timezone.now() for sale_form in sale_formset: if sale_form.cleaned_data.get('product') and sale_form.cleaned_data.get('quantity'): # Check it has product and … -
Django - Unit test RuntimeError model class doesn't declare an explicit app_label
Heyo all. I'm having an issue running unit tests in my new Django project. Whenever I try running them inside PyCharm, I am getting the error: ImportError: Failed to import test module: backend.dtva_app.models Traceback (most recent call last): File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/unittest/loader.py", line 470, in _find_test_path package = self._get_module_from_name(name) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/unittest/loader.py", line 377, in _get_module_from_name __import__(name) File "/Users/tumpa/PycharmProjects/appon_dtva/backend/../backend/dtva_app/models/__init__.py", line 1, in <module> from .user import CustomUser File "/Users/tumpa/PycharmProjects/appon_dtva/backend/../backend/dtva_app/models/user.py", line 7, in <module> class CustomUser(AbstractUser): File "/Users/tumpa/PycharmProjects/appon_dtva/backend/.venv/lib/python3.9/site-packages/django/db/models/base.py", line 134, in __new__ raise RuntimeError( RuntimeError: Model class backend.dtva_app.models.user.CustomUser doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Some other files that might be useful are: The INSTALLED_APPS: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework_simplejwt', 'corsheaders', 'dtva_app', 'drf_spectacular', ] My app is called dtva_app and this is the apps.py config: class DtvaAppConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'dtva_app' This is the CustomUser model being mentioned: class CustomUser(AbstractUser): username = None email = models.EmailField("email address", unique=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email @property def full_name(self): return f"{self.first_name} {self.last_name}" Additionally, all the tests are being recognized, the rest of the app works normally, the endpoints, models, migrations, views, etc.. Everything is fine except … -
Internal server error in Elasticbeanstalk after deployed my Django webapplication
/var/log/web.stdout.log Apr 19 15:05:21 ip-172-31-85-0 web: File "", line 219, in _call_with_frames_removed Apr 19 15:05:21 ip-172-31-85-0 web: File "/var/app/current/Cloud/urls.py", line 22, in Apr 19 15:05:21 ip-172-31-85-0 web: path('', include('CloudApp.urls')), Apr 19 15:05:21 ip-172-31-85-0 web: File "/var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages/django/urls/conf.py", line 34, in include Apr 19 15:05:21 ip-172-31-85-0 web: urlconf_module = import_module(urlconf_module) Apr 19 15:05:21 ip-172-31-85-0 web: File "/usr/lib64/python3.8/importlib/init.py", line 127, in import_module Apr 19 15:05:21 ip-172-31-85-0 web: return _bootstrap._gcd_import(name[level:], package, level) Apr 19 15:05:21 ip-172-31-85-0 web: File "", line 1014, in _gcd_import Apr 19 15:05:21 ip-172-31-85-0 web: File "", line 991, in _find_and_load Apr 19 15:05:21 ip-172-31-85-0 web: File "", line 975, in _find_and_load_unlocked Apr 19 15:05:21 ip-172-31-85-0 web: File "", line 671, in _load_unlocked Apr 19 15:05:21 ip-172-31-85-0 web: File "", line 843, in exec_module Apr 19 15:05:21 ip-172-31-85-0 web: File "", line 219, in _call_with_frames_removed Apr 19 15:05:21 ip-172-31-85-0 web: File "/var/app/current/CloudApp/urls.py", line 3, in Apr 19 15:05:21 ip-172-31-85-0 web: from . import views Apr 19 15:05:21 ip-172-31-85-0 web: File "/var/app/current/CloudApp/views.py", line 9, in Apr 19 15:05:21 ip-172-31-85-0 web: import cv2 Apr 19 15:05:21 ip-172-31-85-0 web: ImportError: libGL.so.1: cannot open shared object file: No such file or directory Apr 19 15:05:27 ip-172-31-85-0 web: Internal Server Error: / Apr 19 15:05:27 ip-172-31-85-0 … -
docxtpl duplicate render data in for loop
I have an API in Django Rest Framework and encountered an issue with docxtpl. I'm using a template to be filled by a single render with a global context, converting the file to PDF, and sending it to my frontend to download the file. However, if I try to use the function more than once, the initially filled file has its data duplicated within the for loop of the template document. In other words, a table that is filled with a for loop in the template, which initially has one filled row, ends up with two duplicate rows. I think it has something to do with the render function. At some point, I thought I had solved it by setting the is_rendered flag to false before using the render function. It worked when I tested it, but I had tried so many things before that I have no idea what really solved it. When I shut down the Django server, it returns to normal. This means that the filled document works well when I try to download it for the first time, but it still doesn't work on the second attempt. with io.BytesIO() as temp_docx_buffer: with open("myapp/doc/Modelo_RADOC.docx", 'rb') as file: … -
How to retrieve the GeoDjango Point model lat and lon coordinates in Django values_list of objects
Would like to retrieve the GeoDjango Point model lat and lon coordinates from a values_list of objects. I'm only able to retrieve a full descriptive string such as "SRID=4326;POINT (1 1)". I need to just retrieve the lat and long numbers, ideally separately, but something such as "(1.000 1.000)" I can live with. Thank you. Models.py point = models.PointField(srid=4326,default='SRID=4326;POINT(0.0 0.0)',null=True,blank=True) Views.py Model.objects.all().values_list('point') returns for example "SRID=4326;POINT (1.000 1.000)" but... Model.objects.all().values_list('point__x') or Model.objects.all().values_list('point__coords__x') do not work, and returns a "join on the field not permitted" error -
Modal button click function not defined - Uncaught ReferenceError
Question Description: I have a modal that should open when clicking on a "Share!" button on my webpage. However, I'm encountering an "Uncaught ReferenceError: openShareModal is not defined" error. Below are the relevant parts of my code: Modal Code: {% load static %} <div id="shareModal" class="modal"> <!-- Modal content --> <div class="modal-content" id="{{ modal_id }}"> <span class="close">&times;</span> <p class="centered-text form-labels">Broadcast the {{ modal_card_title }} Card</p> <div class="social-media-button-container"> <!-- Social media buttons --> </div> <input type="text" value="https://www.example.com/system_page" id="shareLink" style="display: none;"> </div> </div> <script defer> var modal = document.getElementById("shareModal"); var span = document.getElementsByClassName("close")[0]; function openShareModal(event) { event.stopPropagation(); modal.style.display = "block"; } span.onclick = function() { modal.style.display = "none"; } window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } function shareOnFacebook(shareUrl) { // Share on Facebook code } function shareOnX(shareUrl) { // Share on X code } function shareOnInstagram(shareUrl) { // Share on Instagram code } function shareOnLinkedIn(shareUrl) { // Share on LinkedIn code } </script> Individual Page Code: {% extends 'home1/base.html' %} {% load static %} {% block body %} <body id="background_image_mohadino"> <!-- Page content --> <div class="container-fluid text-center"> <!-- Content details --> <div class="container-fluid text-center"> <!-- Share button --> <button class="mohadino_button btn btn-custom btn-lg w-75" type="button" … -
In Django, Update a different table at the time of saving a record from one table
My tables are: models.py class Warehouse(models.Model): site_name = models.CharField(max_length=100) class Item(models.Model): item = models.CharField(max_length=100) class WarehouseStockStatus(models.Model): site_name = models.ForeignKey(Warehouse, on_delete=models.CASCADE) item = models.ForeignKey(Item,on_delete=models.CASCADE,editable = False) class Meta: unique_together = (("site_name", "item")) stock_opening_quantity = models.PositiveBigIntegerField( default = 0, editable = False ) stock_consumption_quantity = models.PositiveBigIntegerField( default = 0, editable = False ) current_inventory_level = models.PositiveBigIntegerField( default = 0, editable = False ) class InventoryOpenings(models.Model): site_name = models.ForeignKey(Warehouse, on_delete=models.CASCADE,related_name='openings') transaction_number = models.BigAutoField(primary_key = True, serialize = False) class InventoryOpeningsDetails(models.Model): transaction_number = models.ForeignKey(InventoryOpenings, on_delete=models.CASCADE) item = models.ForeignKey(Item,on_delete=models.CASCADE) opening_quantity = models.PositiveBigIntegerField( default = 0, editable = True ) There is one Warehouse table, with one to many records in WarehouseStockStatus. There is one products or Items table for inventory control. Then there InventoryOpenings and InventoryOpeningsDetails table, where we select the warehouse, and then an item, add the opening_quantity field. I want to update WarehouseStockStatus for this warehouse and item combination, updating the stock_opening_quantity and current_inventory_level fields in that table, with the opening value we are inputting for InventoryOpeningsDetails. I am trying to place the code for it in admin.py, in InventoryOpeningsAdmin. Need help. Tried this code in admin class InventoryOpeningsAdmin(admin.ModelAdmin): def after_saving_model_and_related_inlines(self, obj): mysite = InventoryOpenings.objects.values_list('site_name',flat=True)[0] myitem = InventoryOpeningsDetails.objects.values_list('item', flat=True)[0] try: warehouse_item = WarehouseStockStatus.objects.filter(Q(site_name=mysite, … -
Invalid HTTP_HOST on Django (EC2 Aws Ubuntu)
I'm having trouble deploying my Django application. I'm running it using nohup on port 8000 and using nginx with SSL certificate configuration, masking the domain to port 80. Here are my default Nginx settings: server { listen 80; listen 443 ssl; server_name fmartns.dev; ssl_certificate /etc/letsencrypt/live/fmartns.dev/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/fmartns.dev/privkey.pem; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/fmartns.dev; } location / { include proxy_params; proxy_pass http://3.82.145.23:8000; # Port where Django is running proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } Django's settings.py configuration: # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['fmartns.dev', '*'] SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_SSL_REDIRECT = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') CSRF_TRUSTED_ORIGINS = ['http://fmartns.dev'] Error log: DisallowedHost at / Invalid HTTP_HOST header: 'fmartns.dev,fmartns.dev'. The domain name provided is not valid according to RFC 1034/1035. Any ideas on how I can resolve this? I've tried various tutorials and configurations both in my settings.py and in the default nginx settings. -
Running a Celery server and Django server individually on the same AWS EC2 instance?
I can successfully run a django server on my EC2 instance with Ubuntu on AWS, as well as the celery server. However, unlike in my Visual Studio Code editor where I can create multiple terminals and have each one run a different server without any issue, I can't seem to do it for my EC2 instance in AWS. I tried making different tabs connecting the same instance, and while one managed to connect to the Django server, when trying to make the other one connect to the Celery server, it all just freezes. This is the Django server running. This is the Celery server running on the same instance but i had to close the Django server just for it to be able to run. Basically, I ust want to run both at the same time on the same EC2 instance, if it's possible. I have read somewhere that using this code ssh -i your_key.pem ubuntu@your_ec2_public_ip could help but i'd have to launch another instance with a paired key. I wanted to make sure if this actually helps or if there another way to do it. -
django djfernet "TypeError: string argument without an encoding" [closed]
I am experiencing the error only in a few environments with the same version of the libraries, as follows: djfernet 0.8.1 django 4.2.11 Python 3.9.18 I'm reading data from a form in Django and I'm getting in the console: File ".../django/db/models/sql/compiler.py", line 1500, in apply_converters value = converter(value, expression, connection) File ".../fernet_fields/fields.py", line 79, in from_db_value value = bytes(value) TypeError: string argument without an encoding It seems to crash when trying to decrypt the data from the database. -
Custom primary keys break Django admin inlines logic
I have a model with self relation in models.py: from uuid import uuid4 from django.db import models class Example(models.Model): uid = models.UUIDField(primary_key=True, default=uuid4) title = models.CharField(max_length=128) parent = models.ForeignKey("self", related_name="subexamples", blank=True, null=True) and Django admin models: from .models import Example from django.contrib import admin class ExampleInline(admin.TabularInline): model = Example exclude = ("uid",) extra = 1 verbose_name = "Subexample" show_change_link = True class ExampleAdmin(admin.ModelAdmin): search_fields = ("title", ) exclude = ("uid",) inlines = [ExampleInline,] admin.site.register(Example, ExampleAdmin) On the admin site I can see the main model and inline like in any other cases. The problem start after adding first Inline object. After it's added I can no longer delete or change it. The only mistake I see is "Please correct the error below." without any problems below. Also no any problems in Django logs. I'm using Django==5.0.2 After reading about similar problems I found that customized PK breaks logic but actually didn't find any workarounds for this problem. -
Django/Heroku - Custom 500 template
I have a template defined and loaded on S3. The template has been granted public access. The template is referred in Heroku as variable ERROR_PAGE_URL and the S3 link is attached against this variable. Somehow the template is not displaying and I still get the basic 500 error generated: 500 Internal Server Error Exception inside application. Daphne I have (I think) applied the same approach as the custom maintenance template, which is rendered perfectly fine. Am I reading the documentation wrong? (https://devcenter.heroku.com/articles/error-pages) Am I using the correct variable? Or is it actually not somehting Heroku generates and I should code this in django? -
Exception Value: User matching query does not exist
DoesNotExist at /profile/username User matching query does not exist. Request Method: GET Request URL: http://127.0.0.1:8000/profile/username Django Version: 5.0.4 Exception Type: DoesNotExist Exception Value: User matching query does not exist. Exception Location: D:\Django projects\social media app\social_media_app_env\Lib\site-packages\django\db\models\query.py, line 649, in get Raised during: core.views.profile Python Executable: D:\Django projects\social media app\social_media_app_env\Scripts\python.exe Python Version: 3.11.9 Python Path: ['D:\Django projects\social media app\social_media', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\python311.zip', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\DLLs', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\Lib', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0', 'D:\Django projects\social media app\social_media_app_env', 'D:\Django projects\social media ' 'app\social_media_app_env\Lib\site-packages'] Server time: Fri, 19 Apr 2024 10:53:11 +0000 -
Django populating a form on a modal
I have a problem with populating a form on a modal pop up. I can get a form added to the modal, but I want it to be based on the line a user clicks on. My view: class SalesQuotationDetailView(LoginRequiredMixin, View): template_name = 'Sales/quotation_details.html' def get(self, request, quoteid): quotation = Quotation.objects.get(id=quoteid) quotationlines = QuotationLine.objects.filter(quotation=quotation, deleted=False) company = quotation.customer quotationform = QuotationForm(initial=model_to_dict(quotation), companyid=company.id) newquotationlineform = NewQuotationLineForm() context = { 'quotation':quotation, 'quotationform':quotationform, 'quotationlines':quotationlines, 'new_quotation_line':newquotationlineform, 'table_title':"Quotation Lines", 'table_heading_1':"Article", 'table_heading_2':"Amount", 'table_heading_3':"Price per Piece", 'table_heading_4':"Lead Time", 'table_heading_5':"Line total" } return render(request, self.template_name, context) def post(self, request, quoteid): quotation = Quotation.objects.get(id=quoteid) quotationlines = QuotationLine.objects.filter(quotation=quotation, deleted=False) company = quotation.customer quotationform = QuotationForm(data=request.POST, files=request.FILES, instance=quotation, companyid=company.id) if quotationform.has_changed and quotationform.is_valid(): qform = quotationform.save(commit=False) qform.updated_by = request.user qform.updated_date = timezone.now() quotationform.save() messages.success(request, f'{quotation.number} has been saved correctly') return redirect('sales-quote-details', quoteid=quotation.id) else: messages.warning(request, f'{quotationform.errors}') newquotationlineform = NewQuotationLineForm(data=request.POST) if newquotationlineform.has_changed and newquotationlineform.is_valid(): newquotationline = newquotationlineform.save(commit=False) newquotationline.quotation = quotation newquotationline.total_line_price = newquotationline.amount * newquotationline.price newquotationline = newquotationlineform.save() messages.success(request, f'The new quotation line was added succesfully') return redirect('sales-quote-details', quoteid=quotation.id) context = { 'quotation':quotation, 'quotationform':quotationform, 'quotationlines':quotationlines, 'new_quotation_line':newquotationlineform, 'table_title':"Quotation Lines", 'table_heading_1':"Article", 'table_heading_2':"Amount", 'table_heading_3':"Price per Piece", 'table_heading_4':"Lead Time", 'table_heading_5':"Line total" } return redirect('sales-quotations') And my template: {% extends "start/parent.html" %} {% block body %} <!-- Content … -
HEROKU (Dockerfile that does not exist)
tried hosting my django website on Heroku, but keeps getting dockfile does not exist which is from the heroku.yml file Waiting on build... Waiting on build... (elapsed: 6s) Waiting on build... (elapsed: 9s) === Fetching app code =!= There were problems parsing your heroku.yml. We've detected the following issues: build.docker.web references a Dockerfile that does not exist below is a screenshoot of my vscode explorer and heroku.yml fileVScode Screenshot -
Two detail tabels with a foreign key to the same master table, how to limit a ManyToManyField to see only the subset of the other detail tabel
In Django I have an Order and Contact table that both have a foreignKeyField to the User table, in the Order table I want a ManyToManyField to see only the subset of Contact table records that belong to the same User, instead of the ManyToManyField seeing all of the records of the contact table. class Contact(models.Model): cnt_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=30, blank=False, null=True) class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='order_set') ref_code = models.CharField(max_length=20, blank=True, null=True) ### ManyToManyField should only see subset of contacts that have same user. contacts = models.ManyToManyField(Contact, blank=True, limit_choices_to={'cnt_user': user}) I cannot figure out how to set the limit_choices_to parameter or how to use a callable in this case. In this example ({'cnt_user': user}) django sees user as a "foreignKey object" not a "user object" this results in the following error: Field 'id' expected a number but got <django.db.models.fields.related.ForeignKey: user>. To me, "this problem" does not seem to be an uncommon scenario, I am hoping there is a straightforward solution. Can anybody show me an example of how to this, either by a callable or a Q object or any other way (proxy model maybe)? Thanks in advance. -
Django Project CORS error after deployment
I got Pyton Django project and my project work on local server but when i deploy on server i got this error.I used IIS Manager for deployment.Other DB connection must be work because i can reach other APIs.By the way my user is superuser. Access to XMLHttpRequest at 'https://website.websites.com:8000/integration/sync' from origin 'https://website.website.com' has been blocked by CORS policy: No 'Access-Control- Allow-Origin'header is present on the requested resource. And here is my API;POST https://website.website..com:8000/integration/sync net::ERR_FAILED 500 (Internal Server Error) By the way OTher API are working without problem I search about error and they suggest me to change setting.py but under below is my settings; ALLOWED_HOSTS = ['*'] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', I use for deployment IIS may be its about it. So they said that its about Autontication IIS I tried every combination but it still doesnt work, -
I have a Category model and a subCategory model and a product model which has foreign key with category and sub category
I have a Category model and a subCategory model and a product model which has foreign key with category and sub category . Whenever a client will add a product then he will select a category and according to that the related subcategory should shown or change without submitting the form in django admin panel. Please tell me how to do this. The value should change on "onChange event" of the category. -
Django Channels on IIS using FASTCGI
I am deploying a Django app using an IIS server. In this Django app, I have implemented Django Channels to use websockets. Locally, everything is working fine with websocket connections, and I am able to send messages. However, the issue arises when I deploy the Django app. The HTTPS works perfectly fine, but the WSS (WebSocket Secure) is not working. I encounter a 404 not found error. the url in which I am trying is wss://my_domain/ws/start-quiz/ also note that i am using memurai instead of redis to use channel_layers CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6370)], }, }, } -
How to set default value of a model field to another field of same mode in django
I've created a Student model in django project with has a field named "enrollmentdate" and "paymentdate" now i need to save "paymentdate" as default value in "enrollmentdate" my model code is as under, > ``` class Student(models.Model): fname = models.CharField(max_length=100) lname = models.CharField(max_length=100) email = models.CharField(max_length=100) password=models.CharField(max_length=100) contactno = models.CharField(max_length=100) address = models.TextField() grade=models.CharField(max_length=100) enrollmentstartdate=models.DateField() enrollmentenddate=models.DateField() daysremaining=models.IntegerField() feespaid=models.DecimalField(max_digits=6, decimal_places=2) paymentdate=models.DateField() > ``` how can i do this? thanks in advance I have tried entrollmentdate=models.DateField(default=paymentdate) but not works