Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework - Custom serializer field does not appear in attrs dict when using "create" method
I created a ModelSerializer and want to add a custom field which does not belong to my model but is shown as part of serialized data when retrieving it and behave as writeable field when create method is called. I have a problem with validate method used on data passed in POST method. The field that does not belong to my model does not appear in attr dict when passed to validate method. The field I want is teams and when model instance already exists, I want this field to use method to retrieve result data (this works fine) and when the create method is called I want it to be a writeable field. Is this possible in any way? class MatchDaySerializer(serializers.ModelSerializer): #Validate if teams field exists in POST data to avoid creating Matchdays with no Players def validate(self, ): if not "teams" in attrs: raise serializers.ValidationError({"teams": "This field is required"}) return attrs #Serializer Fields matches = serializers.SerializerMethodField() teams = serializers.SerializerMethodField() class Meta: model = MatchDay fields = [ 'id', 'date', 'matches', 'teams', ] #Returns match counter def get_matches(self, obj): if not hasattr(obj, 'id'): return None if not isinstance(obj, MatchDay): return None return obj.match_counter #Return teams with list of players … -
How can I create in Django an custom absolute url for a predefined class
I need to make a blog in Django and I have a blog class declared as follows: models.py class Blog(models.Model): name = models.CharField(max_length=200, help_text='Enter name') author = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) The User class is a predefined Django class. As you can see for Blogger I don't create a class but I use a default one from Django class User. In the template blog-list.html I use the following line to display the blog author with a link to the author page: <a href="/blog/blogger/{{ blog.author.id }}">{{blog.author.first_name}} {{blog.author.last_name}}</a> wiews.py class BlogListView(generic.ListView): model = Blog ordering = ['-date'] paginate_by = 5 class BloggerDetailView(generic.DetailView): model = User urls.py urlpatterns = [ path('', views.index, name='index'), path('blog/<int:pk>', views.BlogDetailView.as_view(), name='blog-detail'), path('blogs/', views.BlogListView.as_view(), name='blogs'), path('blogger/<int:pk>', views.BloggerDetailView.as_view(), name='blogger-detail'), ] My question is how can I declare a get_absolute_url for blog.author to NOT use the manual constructed /blog/blogger/{{ blog.author.id }}? -
Django - "Not found" in log
I've got django app and some problem I can't understand/resolve. So, in my application, there is a view called: MyNotifyURL URLs.py file is ok. The view is called from outside, by payment integration api. When the payment is processed, the view is called, and it does its logic, and everything works fine. But, ... about 10 times per day (random hours), in my log files I can find: 2023-06-30 04:18:47 [WARNING ] (/home/myuser/myDevEnv/lib/python3.9/site-packages/django/utils/log.py:log.log_response 241) Not Found: /djangoapp/MyNotifyURL/ Is there any idea why is it so, or how to track the problem? -
PythonAnywere to connect postgres
**how to use postgres remotely in my pythonanywhere I need to make this kind of connection to postgres database in Anywhere but it is not supported ** ''' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'fontenariaguivala', 'USER': 'postgres', 'PASSWORD': '**********', 'HOST': 'mayhoste.com', 'PORT': '5432', } } ''' -
How'd I create filter feature that works with multiple model on Django?
So I have 2 models : from django.db import models class Profil(models.Model): nik = models.IntegerField() nama = models.CharField(max_length=40) tgl = models.DateField() kelamin = models.CharField(max_length=10) namaibu = models.CharField(max_length=40) nikibu = models.IntegerField() dusun = models.CharField(max_length=30, default='Sumberejo') def __str__(self): return f"{self.nik}, {self.nama}, {self.namaibu}" class Posyandu(models.Model): bulan = models.CharField(max_length=20, default='Januari') nik = models.ForeignKey(Profil, on_delete=models.CASCADE) tb = models.IntegerField() bb = models.IntegerField() ll = models.IntegerField() lk = models.IntegerField() ket = models.CharField(max_length=20,) def __str__(self): return f"{self.nik.nama}, {self.bulan}, {self.tb}, {self.bb}" and display them as a table with this html <table> <thead> <tr> <th>NIK</th> <th>Nama</th> <th>Tanggal Lahir</th> <th>Kelamin</th> <th>Nama Ibu</th> <th>Bulan</th> <th>TB</th> <th>BB</th> <th>LL</th> <th>LK</th> <th>Keterangan</th> </tr> </thead> <tbody> {% for profil in profils %} {% for posyandu in profil.posyandu_set.all %} <tr> <td>{{ profil.nik }}</td> <td>{{ profil.nama }}</td> <td>{{ profil.tgl }}</td> <td>{{ profil.kelamin }}</td> <td>{{ profil.namaibu }}</td> <td>{{ posyandu.bulan }}</td> <td>{{ posyandu.tb }}</td> <td>{{ posyandu.bb }}</td> <td>{{ posyandu.ll }}</td> <td>{{ posyandu.lk }}</td> <td>{{ posyandu.ket }}</td> </tr> {% endfor %} {% empty %} <tr> <td colspan="11">No data available</td> </tr> {% endfor %} </tbody> </table> aside from that I try to build a filter feature that able to filter what's displayed on the table based on months field (bulan field on Posyandu) with this views.py this views.py def riwayat(response): profils = … -
Count .docx pages Python Django
I have an application in DJango. I want to create a tool that will tell you the number of pages each file has. With PDF, excel and PPT files it works fine, but with ".docx" files it doesn't count exactly. I want you to tell me exactly how many pages that file has. I don't know, maybe by commands or by converting it to PDF but I want to have the exact number of pages. I have tried to do it by segments but it does not tell me exactly. This is my function: def count_pages(file_content, filename): file_extension = os.path.splitext(filename)[1] if filename else "" if file_extension.lower() == ".pdf": pdf_reader = PyPDF2.PdfReader(file_content) num_pages = len(pdf_reader.pages) file_type = "PDF" elif file_extension.lower() == ".docx": elif file_extension.lower() == ".pptx": prs = Presentation(file_content) num_pages = len(prs.slides) file_type = "PowerPoint" elif file_extension.lower() == ".xlsx" or file_extension.lower() == ".xlsm": wb = load_workbook(file_content) num_pages = len(wb.sheetnames) file_type = "Excel" else: num_pages = 0 file_type = "Unknown" return num_pages, file_type -
Python: ValueError: source code string cannot contain null bytes
I tried to start server and caught this: python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "C:\Users\Admin\PycharmProjects\web-bd-project\venv\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Admin\PycharmProjects\web-bd-project\venv\Lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\Admin\PycharmProjects\web-bd-project\venv\Lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\Admin\PycharmProjects\web-bd-project\venv\Lib\site-packages\django\core\management\__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "C:\Users\Admin\PycharmProjects\web-bd-project\venv\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Admin\PycharmProjects\web-bd-project\venv\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Admin\PycharmProjects\web-bd-project\venv\Lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "C:\Users\Admin\PycharmProjects\web-bd-project\venv\Lib\site-packages\django\apps\config.py", line 269, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 936, in exec_module File "<frozen importlib._bootstrap_external>", line 1074, in get_code File "<frozen importlib._bootstrap_external>", line 1004, in source_to_code File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed ValueError: source code string cannot contain null bytes Just started learn django and hard to my with error like this, because i can't understand anything from text like this ** … -
Seeking for Faster PDF/A Verification Tool in Django
I am currently working on a Django project that involves PDF file uploading and checking whether the uploaded file is PDF/A compliant. To accomplish this, I have been using an external module, VeraPDF. However, the verification process with VeraPDF takes around 3 seconds, which I find to be quite long. Therefore, I'm reaching out to the community for suggestions on any other free external modules or libraries that could potentially speed up this PDF/A verification process in a Django environment. Any advice would be greatly appreciated. Thank you in advance. Asynchronous Batch Processing for PDF/A Verification in Django -
how to create a modified table in python to download from django site
I have a django website with a database. On the site, you can add, change, delete information from the database. I made a button that, when clicked, downloads a .csv file. I open it in excel and it looks something like this: The data set does not matter, I have a different one, I took this one on the Internet for an example. I want that when I click on the "download report" button, I would create a table at least like in this example: Is it possible? At the moment, my views.py contains the following code to get data from the database and download it to an excel spreadsheet: def export_racks_view(request, id): response = HttpResponse(content_type='text/csv') response.write(u'\ufeff'.encode('utf8')) writer = csv.writer(response, delimiter=';', dialect='excel') writer.writerow([ 'Rack number', 'Name', 'Amount', 'Vendor', 'Model', 'Describe', 'numbering', 'responsible', 'financially responsible person', 'inventory number', 'row', 'place', 'height', 'width', 'depth', 'unit width', 'unit depth', 'rack type', 'place type', 'max load', 'power sockets', 'power sockets UPS', 'external ups', 'cooler', 'updated by', 'updated at', 'room name', 'building name', 'site name', 'department name', 'region name', ]) raw_report = Rack.objects.raw("""select rack.id as id, rack.rack_name, rack.rack_amount, rack.rack_vendor, rack.rack_model, rack.rack_description, rack.numbering_from_bottom_to_top, rack.responsible, rack.rack_financially_responsible_person, rack.rack_inventory_number, rack.row, rack.place, rack.rack_height, rack.rack_width, rack.rack_depth, rack.rack_unit_width, rack.rack_unit_depth, rack.rack_type, rack.rack_place_type, rack.max_load, … -
Django using same APIView for both logged in and non logged in users
How can we use the same Django rest APIView for both logged in and logged out (Public) users. If the authentication token is passed, the view should be able to give the request.user and if the authentication token is not passed, the request.user can be anonymous. Please let me know if this is possible or not? I tried to remove authentication_classes = [] permission_classes = [] from the view, but by default the authentication is applied for all the users. -
How can I get python to understand my commands such as python manage.py shell. Error code: python bash: command not found
What are the details of your problem? I am trying to run the command python manage.py shell. I am in the directory that has manage.py but python is acting like I don't have the file or the command ability for shell. I am using visual studio code and I ran the echo$PATH command and got this output: /Users/andrewstribling/Desktop/mike_mysite/project_env/bin:/Users/andrewstribling/anaconda3/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/andrewstribling/anaconda3/bin:/Library/Frameworks/Python.framework/Versions/3.11/bin i had installed anaconda but went back to visual studio code. is this tied to it? Also, my director has my project env folder inside of my project folder. What did you try and what were you expecting? I have tried deleting the project_env folder for my enviornment and creating another one. I have reached out to the discord community for django and have not gotten a response. I looked up venv errors on stack overflow and I am not understanding the Path Variable really is or how to change it. I have read stack over flow articles but I do not believe their situation applies to me. https://python.land/virtual-environments/virtualenv#How_a_Python_venv_works I expect that there is a way to change how my project is seeing this. -
How to solve Django Rest API Import "drf_yasg" could not be resolved
from drf_yasg.views import get_schema_view from drf_yasg import openapi In the settings.py file, I add 'drf_yasg', Im Using the Vscode... Here I'm trying to add Swagger but I got an unexpected problem Import "drf_yasg.views" could not be resolved Screenshot Image -
Django ImportError at /user/login d doesn't look like a module path
I am trying to create a simple login page using th LoginView from django.contrib.auth. Whenever I try to login a user a receive the following error: ImportError at /user/login d doesn't look like a module path This is my code for activating the view in the url: from django.urls import path from . import views from django.contrib.auth import views as auth_views urlpatterns = [ path("register", views.register_request, name="register"), path("login", auth_views.LoginView.as_view(template_name="user/login.html"), name="login"), path("logout", auth_views.LogoutView.as_view(template_name="user/logout.html"), name="logout") ] This is my html file user.login.html: {% extends "base/base.html" %} {% load crispy_forms_filters %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST" > {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Log In</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Login</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Need An Account? <a class="ml-2" href="{% url 'register' %}">Sign Up Now</a> </small><br> <small class="text-muted"> <a href="/">Forgot password?</a> </small> </div> </div> {% endblock content %} #Just as a comment, the logout view works perfectly fine, the error jusr occurs when I hit submit in the login.html. I have tried adding these lines to the settings.py fileÑ AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend' ) LOGIN_URL = 'user/login' -
Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. Django-rest-auth
I'm doing the Django password reset but this error always happens and I don't know why Here are the urls: from django.urls import path from . import views from django.contrib.auth import views as auth_views app_name = 'accounts' urlpatterns = [ path('login/', views.login, name="login"), path('registrar/', views.registrar, name="registrar"), path('logout/', views.logout, name="logout"), path('reset/password_reset_confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/password_reset/', auth_views.PasswordResetView.as_view(), name='password_reset'), path('reset/password_reset_done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/password_reset_complete/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] Here are my custom pages: my custom pages: And these are the project urls: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('accounts/', include('accounts.urls')), path('admin/', admin.site.urls), path('', include('home.urls')), path('turmas/', include('turmas.urls')), path('calendario/', include('calendario.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
I it possible to integrate python with CSS, Javascript, and HTML?
I have a frontend web application built with JavaScript, HTML, and CSS. I would like to incorporate the output of a Python script into my frontend without using a server or a full backend solution. The Python script is a simple neural network, and I want to display its output in the frontend, such as showing the result as a header or plotting a graph generated by the script. I have already tried printing the output to the console from the Python script, but I need assistance with transferring that output to the frontend. Is it possible to achieve this without a server? I am open to suggestions and starting with a simpler solution, like plotting a graph generated by the Python script in the frontend. I appreciate any guidance or code examples on how to accomplish this. Thank you! I have looked into Django but I feel as if that seems too complex and more server focused for the simple task I require. -
Why does the matching query does not exist error occur?
There is a model: class ProductRating(models.Model): class Meta: indexes = [ UniqueIndex(fields=['user', 'product']), ] user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) grade = models.BooleanField() created_time = models.DateTimeField(auto_now_add=True, verbose_name='created_time') I want to create a row in the database with a post request class PostRatingFromUser(generics.CreateAPIView): queryset = ProductRating.objects.all() permission_classes = [IsAdminOrAuthenticatedUser, ] serializer_class = ProductRatingSerializer def post(self, request, *args, **kwargs): rating_from_db = ProductRating.objects.get(product_id=kwargs['pk'], user=request.user) if rating_from_db: rating_from_db.grade = kwargs['grade'] rating_from_db.save() else: ProductRating.objects.create(product_id=kwargs['pk'], grade=kwargs['grade']).save() return Response(status=200) But before adding, I check if there is such a database, if there is, then I just change the value of 'grade' but it gives me an error: product.models.ProductRating.DoesNotExist: ProductRating matching query does not exist. -
In Django, how can I select an object from the database and pass the parameters not to the url, but in some other better way?
I'm new to Django, in a page i have a combobox which is populated by fields from a database (simply city names). I select an object from the database with parameters which I pass to the url. I know this isn't the cleanest approach and that there is a better way. Is there a better way to populate the combobox without passing database parameters to the url? Then passing the parameters in a different and better way. How could my code take a different approach? models.py from django.db import models class City(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name forms.py from .models import City class SelectCityForm(forms.Form): city = forms.ModelChoiceField(queryset=City.objects.all()) class Meta: model = City fields = ('name') views.py def city_detail(request): form = CitySelectForm() object = None if request.method == "POST": form = CitySelectForm(request.POST) if form.is_valid(): city_id = form.cleaned_data['city'] object = City.objects.get(id=city_id) context = {'form': form, 'object': object} return render(request, 'app1/home.html', context) home.html <form action="/url-to-city_detail-view/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> urls.py from django.urls import path, include from . import views from app1.views import index from app1 import views urlpatterns = [ path('', index, name='index'), #Aggiunto per combobox path('login/', views.sign_in, name='login'), path('logout/', views.sign_out, name='logout'), path('home/', views.home, … -
Django Error: Question matching query does not exist() Updating Questions and Choices to Primary Keys
I am currently attempting the official Django tutorial polls app. It has asked me to create questions for a poll app and than after that create answer choices. I made a mistake creating the questions and somehow made an empty query set which I believe set the primary key to 1 and 2 respectively for the blank questions. I went on to create questions 3, 4, and 5. I realized the blanks were there an I attempted to delete the two questions. After running the delete() command I removed them. I figured that the primary keys would be removed and everything would slide back into place. My question who invented python remained at pk=3. Now I am wondering what to do. Should I create answer choices off of primary key id 3 and run with it? Or should I find a way to reassign the answer choices. Well, I have asked the Django forums website and someone recommended to me that I run the command `[(q.id, q.question_text) for q in Question.objects.all()]' this command output: >>> [(q.id, q.question_text) for q in Question.objects.all()] [(3, 'Who invented python?'), (4, 'This question was changed by dot notation on the object.'), (5, 'Who invented Django?')] … -
django aggregate a list of dictionaries
I have this situation that I have a queryset with complex relation and i need this kind of data: filters: [{ colors: [{ 'black': '#000000' }, { 'white': '#111111' } ] }, { categories: [{ "Digital": [{ "mobile": [{ 'Apple': ['first_phone', 'second_phone'] }, {'Android': ['first_phone', 'second_phone']} ], }] }] } ] basically for categories its a 3 level children-parent situation. and the reason is i don't want to call my queryset multiple times since its a pretty heavy one. overall this is what i have in mind: queryset.aggregate( colors=ArrayAgg( {F('packs__colors__title'): F("packs__colors__hex_code")}, distinct=True, ), categories=ArrayAgg( { F('categories__title'): { F("categories__parent__title"): { F("categories__parent__parent__title") } } }, distinct=True,) ) for first level its working fine. but how can i make this kind of aggregations? -
Host the GOOGLE_CREDENTIALS on google cloud storage not working
What is the best way of accessing the GOOGLE_CREDENTIALS json file ? I tried hosting it on Google cloud storage and the link is public, but can't work in Django . I am using redner.com as my server. -
Error while signing up with Django (Backend) and Angular (Frontend)
I am encountering an error when trying to create a user from my Angular frontend using my Django backend. I have set up CORS in my backend to allow all origins (allow origin all), but I continue to receive the following errors When I send a POST request to the URL 'http://127.0.0.1:8000/api/users/', I get a "400 (Bad Request)" response in the console. If I remove the '/' from the URL and send the request to 'http://127.0.0.1:8000/api/users', I receive the following error: "Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/users' from origin 'http://localhost:4200/' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request." I have already installed and configured the CORS package in my Django backend to allow access from all origins. Despite this, the error persists. Here are some additional details: Django version: v4.1.7 Angular version: v15 CORS configuration in my Django backend (code snippet): enter image description here I am stuck and unsure how to resolve this issue. Any help would be greatly appreciated. Thank you very much! -
Python & MimeTypes: Parsing Email Body & Data in a multipart email
I am working on a python script (with BeautifulSoup) that reads emails through a Gmail service account. I can successfully read through the mailparts for an email sent from Gmail and identify the "data" part to read through and find a keyword in the text or HTML. However, I am having issues reading through any email sent from an apple device. I assume I will encounter other email clients issues too. I'm wondering how apple mail clients structure their email parts. Ultimately, I must find the "data" part in the body of the email. Here is the portion fo the script causing my issue: def parse_parts(self, part): mimeType = part['mimeType'] body = "" if mimeType == "text/plain" or mimeType == "text/html": data = part['body']["data"] data = data.replace("-","+").replace("_","/") decoded_data = base64.b64decode(data) soup = BeautifulSoup(decoded_data , "lxml") body = soup.get_text() return body -
Why is my console shows the coding of my html file?
I was able to use the quantity increment but i accidentally undo my work and it turns out like this someone help me please >:( the console print out my base.html coding and does not increase the quantity (base.html) <!DOCTYPE html> <html lang="en"> {% load static %} <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css"> <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous"> <script type="module" src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.esm.js"></script> <script nomodule src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.js"></script> <title>Python World</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <style> nav{ background-color: white; } .one-edge-shadow { box-shadow: 0 8px 2px -5px rgb(246, 245, 245); } .display-8{ font-weight: 200; font-size: 30px; } .badge { padding-left: 9px; padding-right: 9px; -webkit-border-radius: 9px; -moz-border-radius: 9px; border-radius: 9px; } .label-warning[href], .badge-warning[href] { background-color: #c67605; } #lblCartCount { font-size: 15px; background: #ff0000; color: #fff; padding: 0 5px; vertical-align: top; margin-left: -17px; } .btn-circle.btn-sm { width: 25px; height: 25px; padding: 7px; border-radius: 14px; font-size: 12px; text-align: center; font-weight: bold; } </style> <script> function cartpage() { window.location.href="{% url 'cartpage' %}" } </script> </head> <body> <!-- navbar --> <nav class="one-edge-shadow sticky-top navbar navbar-expand-lg navbar navbar-dark bg-primary"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul … -
How to best model a tree of generic content types in Django?
I have a Django API for managing a bunch of content related to D&D campaigns: characters, locations, factions, quests, etc. Until now the frontend has always displayed these types of content in their own tabs, so a list of characters, another list of locations, and within a tab content can be nested: locations can have sub-locations, but they are all in their own "silo". class Location(models.Model): name = models.CharField(max_length=255) subtitle = models.CharField(max_length=255, blank=True) text = models.TextField(blank=True) icon = models.CharField(max_length=255, default="map-location-dot") parent = models.ForeignKey("self", on_delete=models.SET_NULL, blank=True, null=True) campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE, editable=False) I am thinking about turning the frontend into one nested tree of all content types: so a location could have nested factions, which could have nested characters, and so on, totally free-form. I'm not really sure how to best model this in the database. One idea I have is to create a brand new model that contains the tree, with generic relations to content items via the contenttypes framework from Django. class Tree(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey("content_type", "object_id") parent_content_type = models.ForeignKey(ContentType, null=True, on_delete=models.CASCADE) parent_object_id = models.PositiveIntegerField(null=True) parent_content_object = GenericForeignKey("content_type", "object_id") order = models.PositiveIntegerField() campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE, editable=False) That would work (although I … -
Cannot add <Image> instance is on database "default", value is on database "None"
I'm developing and app in Django, and I'm getting this error when my form y submitted, the problem is given when it try to add images on the relationship ManyToMany. Internal Server Error: /publish_offer/ Traceback (most recent call last): File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapper_view return view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Projects\revenue\management\views.py", line 49, in publish_offer oferta.imagenes.add(*imgs) File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\db\models\fields\related_descriptors.py", line 1137, in add self._add_items( File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\db\models\fields\related_descriptors.py", line 1397, in _add_items target_ids = self._get_target_ids(target_field_name, objs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\db\models\fields\related_descriptors.py", line 1313, in _get_target_ids raise ValueError( ValueError: Cannot add "<ImagenesOferta: ImagenesOferta object (None)>": instance is on database "default", value is on database "None" [29/Jun/2023 16:10:20] "POST /publish_offer/ HTTP/1.1" 500 87580 This is my models: class ImagenesOferta(models.Model): imagen = models.ImageField(verbose_name='Imagen Oferta', blank=False, null=False, upload_to='img_ofertas/') class Meta: verbose_name = 'Imagen de Oferta' verbose_name_plural = 'Imagenes de Ofertas' ordering = ['-id'] class Oferta(models.Model): titulo = models.CharField(verbose_name='Título', max_length=100, null=False, blank=False) descripcion = models.TextField(verbose_name='Descripción', null=True, blank=True) cantidad = models.PositiveSmallIntegerField(verbose_name='Cantidad', null=False, blank=False, default=1) valor = models.DecimalField(verbose_name='Valor', max_digits=4, decimal_places=2, null=False, blank=False) material = models.CharField(verbose_name='Material', max_length=20, null=False, blank=False, choices=MATERIAL_CHOICES) imagenes = models.ManyToManyField(ImagenesOferta, verbose_name='Imagenes de la Oferta', blank=True) usuario = …