Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Get values as list from annotate queryset
I used annotate to compute the total entry per month. How can I get the values as a list? stats = EntryMonitoring.objects.filter(student_id=user).annotate(month=TruncMonth('date')).values('month').annotate(total=Count('id')) With this line, I got this: <QuerySet [{'month': datetime.date(2024, 3, 1), 'total': 25}, {'month': datetime.date(2024, 4, 1), 'total': 2}]> How can I get the values of 'total' as list like this [25, 2, ...] ? Cause when I tried to get the value using this {% for obj in stats %}{{ obj.total }}{% endfor %} in html, it shows 252. -
What methods are possible to deploy an app that uses Django and Vue?
I have recently started to develop a web application, with Django as my backend and Vue.js as my frontend. In the project folder, the Django backend exists as the app 'api'. Whereas the frontend is simply referred to as 'frontend'. I'm slowly starting to consider deployment, but I seriously have no idea how to go around it. My only guess is to deploy two separate apps on a platform like heroku, where I would be communicating with the API from the frontend. Tutorials really lack the detail in using specific frameworks, which is why I would be so grateful if someone could point me into the best direction for deploying the web-app. I'm inclined to use heroku due to it's simplicity, but I'm also open to suggestions. -
how to add autocomplete on foreign key in django admin?
I try to add autocomplete on foreign key in django admin but unfortunately it doesn't work and I can't do search and filter data for foreign key in django admin panel here is my Participants Model `class Participants(models.Model): title = models.TextField(blank=True, null=True) description = models.TextField(blank=True, null=True) session = models.ForeignKey(Sessions, on_delete=models.CASCADE, related_name='participants', null=True, blank=True) day = models.ForeignKey(Days, on_delete=models.CASCADE, related_name='participants', null=True, blank=True) price = models.IntegerField(blank=True, null=True) datetime = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='participants', blank=True, null=True) startDay = models.ForeignKey(Day, on_delete=models.CASCADE, related_name='participants', blank=True, null=True) endDay = models.ForeignKey(Day, on_delete=models.CASCADE, related_name='end_participants', blank=True, null=True) course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='participants', null=True, blank=True) created = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='participant', blank=True, null=True) authority = models.TextField(unique=True, blank=True, null=True) success = models.BooleanField(blank=True, null=True)` here is my Participants admin. `from django.contrib import admin from .models import * class ParticipantsAdmin(admin.ModelAdmin): autocomplete_fields = ['user',] admin.site.register(Participants, ParticipantsAdmin)` here is my User admin. `from django.contrib import admin from User.models import User class UserAdmin(admin.ModelAdmin): list_display = ('name', 'number') search_fields = ('name', 'number') admin.site.register(User, UserAdmin) ` django admin panel I will be thankful for your help sorry for my bad english. I try this doc https://medium.com/@vigneshun/how-to-create-autocomplete-fields-for-user-selection-in-django-admin-efa12833cab7 but still not working. -
What is the best way to make changes to my django postgres database in production?
I have a django app on heroku with postgres db. If I try to do any changes now locally nothing works because I put environmental variables in. So i need to take all of that out of my settings.py and put the correct values in. Then after I make changes I need to take it all out again before commiting it back. Also i seem to get connection errors with the postgres database when changing it from production back to development. I'd like to be able to make changes to models, views and html templates locally and then just commit it back up. Is it possible to just commit the models.py up to github and then run the migrations on heroku? I see there is a heroku console in my app dashboard. Can this be used to run commands like manage.py? -
django rest framework AttributeError: 'function' object has no attribute 'get_extra_actions' when accessing from react
I seem to be getting the following error, but seemingly only when I access from React. 2024-04-19 18:30:28 File "/app/config/urls.py", line 29, in <module> 2024-04-19 18:30:28 path('api/', include(router.urls)), 2024-04-19 18:30:28 ^^^^^^^^^^^ 2024-04-19 18:30:28 File "/usr/local/lib/python3.12/site-packages/rest_framework/routers.py", line 77, in urls 2024-04-19 18:30:28 self._urls = self.get_urls() 2024-04-19 18:30:28 ^^^^^^^^^^^^^^^ 2024-04-19 18:30:28 File "/usr/local/lib/python3.12/site-packages/rest_framework/routers.py", line 338, in get_urls 2024-04-19 18:30:28 urls = super().get_urls() 2024-04-19 18:30:28 ^^^^^^^^^^^^^^^^^^ 2024-04-19 18:30:28 File "/usr/local/lib/python3.12/site-packages/rest_framework/routers.py", line 236, in get_urls 2024-04-19 18:30:28 routes = self.get_routes(viewset) 2024-04-19 18:30:28 ^^^^^^^^^^^^^^^^^^^^^^^^ 2024-04-19 18:30:28 File "/usr/local/lib/python3.12/site-packages/rest_framework/routers.py", line 152, in get_routes 2024-04-19 18:30:28 extra_actions = viewset.get_extra_actions() 2024-04-19 18:30:28 ^^^^^^^^^^^^^^^^^^^^^^^^^ 2024-04-19 18:30:28 AttributeError: 'function' object has no attribute 'get_extra_actions' urls.py: router.register(r'hello', views.HelloViewSet, 'hello') views.py: @api_view(['GET']) @permission_classes([AllowAny]) class HelloViewSet(viewsets.ModelViewSet): #dummy serializers and queryset for now serializer_class = SomeDummyDetailSerializer queryset = SomeDummyObject.objects.all() permission_classes = [DjangoObjectPermissions] def list(self, request): #get list return Response({'message': 'Hello, worlds!'}) def retrieve(self, request, pk=None): #get detail return Response({'message': 'Hello, worlds!'}) Am I missing something here? Most errors I see with this seem to be using views instead of ViewSets with router. I also seemingly need to set the @api_view to override 401 denied errors, but I assume that's a separate issue with token authentication or soemthing. -
base_profile not creating/migrating to SQLite
I am able to migrate base_post to the database but for some reason I do not get any errors relating to base_profile but it is not a table in the database. migration filemodels.pyviews.pydatabase I tried to makemigrate, migrate, migrate base zero(which gives me the error of no base_profile as well so it wont delete all the migration files). -
Send api key from a django template
I have a backend application with django, hosted in lightsail and using api gateway to manage it. The entire backend application is protected by the API key, this means I need to send an api key on each request, this is only for post opperations, for GET the api key is not necessari. so, in my urls.py i set an index view which serves my template, a simple form with a send button. this send button will actually send a request to the backend application, but as this is a POST, it needs an api key. I cannot load the api key as a context because if I console.log() the api key will be exposed, tearing down all the protection for POST operations. is there a way to send a POST operation with the API key avoiding it to be seen from the index? both the index and the backend operations live in the same django project. I have tried sending it as context api_key = settings.API_KEY context = {'api_key': api_key} return render(request, "index.html", context) but printing it from the browser's console it actually prints the api key, it should be hidden but still able to be sent. -
Unable to send data to the web server. "Not found: /api/posts", 404
I'm new to Django REST framework and I'm still trying to wrap my head around it. I'm trying to develop a desktop app and a forum website, where the desktop app would be able to send data to the forum website, resulting in creation of new posts/threads. Currently, when I try to send data with the desktop app to the website, I get the following message in my cmd: "POST /api/posts HTTP/1.1" 404 4155 Not Found: /api/posts I have this in my urls.py from django.urls import path, include from .views import ThreadListView, ThreadDetailView, CreateThreadView, CreatePostView, PostViewSet from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'posts', PostViewSet) urlpatterns = [ path('', ThreadListView.as_view(), name='thread_list'), path('thread/<int:pk>/', ThreadDetailView.as_view(), name='thread_detail'), path('thread/create/', CreateThreadView.as_view(), name='create_thread'), path('thread/<int:pk>/post/', CreatePostView.as_view(), name='create_post'), path('accounts/', include('accounts.urls')), ] # include the urls generated by the router urlpatterns += router.urls serializers.py: from rest_framework import serializers from .models import Post class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' views.py: class CreatePostView(CreateView): model = Post fields = ['content'] def form_valid(self, form): # Get the thread object base on the url parameter 'pk' thread = Thread.objects.get(pk=self.kwargs['pk']) # Set the thread for the post form.instance.thread = thread form.instance.author = self.request.user # Save the post form.instance.save() # update the … -
Referencing a foreign key field attached to another model in a Django filter
I have a Profile model which is related to the Django User model via a 1:1 relationship. In the profile model is a field "nickname." I am filtering a table with a foreign key to the User model but want to display the nickname in the filter. Is it possible to do this, and if so, how? class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) nickname = models.CharField(max_length=20,blank=False) class MyCourse(models.Model): instructor = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=False) [other stuff] class MyCourseFilter(django_filters.FilterSet): sorted_nicknames = <WHAT GOES HERE?> nickname = django_filters.ModelChoiceFilter(queryset=sorted_nicknames, label='Nickname') -
Django + Frontend Framework: SEO, rendering strategy, user experience and familiarity
I'm a new full-stack developer comfortable with Django and looking to build a few new web applications this year. While Django offers templating, I'm considering using a separate frontend framework like Vue.js for enhanced user experience. However, I'm unsure about the best approach for SEO and rendering strategy, would love to hear from more experienced devs what you think about it I could separate backend from frontend entirely and use Django Rest Framework to implement APIs for my frontend. I'm quite new to Vue.js so I'm also open to other strategies like using Django templating and only integrate Vue.js selectively within my templates for specific functionalities. Would I need DRF then as well? I also want to you Stripe to handle payments and Auth0 for authentication but looks like both should integrate quite well with my backend and frontend Any recommendations, explanations, and best practices related to SEO, SSR, CSR, and integrating Vue.js with Django would be greatly appreciated! Bonus points for mentioning specific libraries or tools that could be helpful for this setup (like Axios) Tech stack: Backend: Python + Django Potential Frontend Framework: Vue.js + Tailwind CSS Database: PostgreSQL -
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.