Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why i can't get variable name from Django
I have a Django project that i'm working on. I need to print something to CLI to make it easier to debug. This is what i need print('============================================') print('VARIABLE_NAME_IN_CAPS') print(variable) print(f'LENGTH : {len(variable)}') print('============================================') this is my function to get variable name. This is where i got the snippet def get_variable_name(variable): globals_dict = globals() return [var_name for var_name in globals_dict if globals_dict[var_name] is variable] But when i called the function i get empty array []. I've tried to do it without function and do a separate test in another file and it worked. Is there anything that prevent this to happen in Django ? -
ValueError at / The 'image' attribute has no file associated with it
How can i solve this error??i cannot see uploaded picture from users.it give ValueError at / The 'image' attribute has no file associated with it. error everytime. The job was to display user uploaded post in the social media site. I first created a model named “uploade” and added fields such name, location, number and profile picture. It worked excellent until I tested imageField associated with profile picture. [i cant understand whts wrong here,for this error][1] [1]: https://i.stack.imgur.com/yvffJ.png **---HTML---** {% for post in posts reversed %} <div class="bg-white shadow rounded-md -mx-2 lg:mx-0"> <!-- post header--> <div class="flex justify-between items-center px-4 py-3"> <div class="flex flex-1 items-center space-x-4"> <!-- <a href="#"> <div class="bg-gradient-to-tr from-yellow-600 to-pink-600 p-0.5 rounded-full"> <img src="{% static 'assets/images/avatars/avatar-2.jpg' %}" class="bg-gray-200 border border-white rounded-full w-8 h-8"> </div> </a> --> <span class="block font-semibold "><a href="/profile/{{post.user}}">@{{post.user}}</a></span> </div> <div> <a href="#"> <i class="icon-feather-more-horizontal text-2xl hover:bg-gray-200 rounded-full p-2 transition -mr-1 "></i> </a> <div class="bg-white w-56 shadow-md mx-auto p-2 mt-12 rounded-md text-gray-500 hidden text-base border border-gray-100 " uk-drop="mode: hover;pos: top-right"> <ul class="space-y-1"> <!-- <li> <a href="#" class="flex items-center px-3 py-2 hover:bg-gray-200 hover:text-gray-800 rounded-md "> <i class="uil-share-alt mr-1"></i> Share </a> </li> --> <!-- <li> <a href="#" class="flex items-center px-3 py-2 hover:bg-gray-200 hover:text-gray-800 rounded-md "> <i class="uil-edit-alt … -
The content published by wagtail using the RichTextField field does not support spaces and indents
I am a beginner and use the blog developed by wagtail to take notes. After the record code part is saved, the blank space and indentation disappear. This problem is stuck. Help me. Thank you! class BlogPage(Page): body = RichTextField(blank=True) saved e.g: class BlogPage(Page): body = RichTextField(blank=True) -
MongoDB with Django: TypeError: Model instances without primary key value are unhashable
I'm trying to connect MongoDB with Django. settings.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': '<name>', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': f'mongodb+srv://{mongodb_username}:{mongodb_password}@{mongodb_cluster}/?retryWrites=true', 'uuidRepresentation': 'standard', 'waitQueueTimeoutMS': 30000 } } } models.py import uuid from django.db import models # Create your models here. class ModernConnectUsers(models.Model): user_id = models.UUIDField(primary_key=True, default=uuid.uuid4()) user_name = models.CharField(max_length=30, null=False) The model has not been used anywhere for now. python manage.py makemigrations && python manage.py migrate outputs: Migrations for 'modern_connect': modern_connect/migrations/0003_alter_modernconnectusers_user_id.py - Alter field user_id on modernconnectusers Operations to perform: Apply all migrations: admin, auth, contenttypes, modern_connect, sessions Running migrations: No migrations to apply. Your models in app(s): 'modern_connect' have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/core/management/base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 317, in handle emit_post_migrate_signal( File … -
Python Jsonschema validation returning error on correct input
I am quite new to Python, and trying to validate a json file in the following way with jsonschema validation: carsSchema = {"type": "object", "properties" : { "model_year": {"type" : "string"}, "make": {"type" : "string"}, "model": {"type" : "string"}, "rejection_percentage": {"type" : "string"}, "reason_1": {"type" : "string"}, "reason_2": {"type": "string"}, "reason_3": {"type" : "string"}} then reading a json file with inputs: file = json.loads(request.FILES['file'].read()) for instance in file: print(validate(instance, carsSchema)) the file inputs looks like this: [ { "model_year": "2013", "make": "Mercedes-Benz", "model": "CLS", "rejection_percentage": "0,0", "reason_1": "", "reason_2": "", "reason_3": "" } ] I am receiving None on all the file inputs even though they are in correct format. Thanks in advance :) -
If statement in Django template always runs the code no matter the condition is True or False
I'm using a Key-Value model to make static template's data dynamic. This is my model's code: class SiteDataKeyValue(models.Model): key = models.CharField(max_length=200, verbose_name="Text title") value = models.TextField(verbose_name="Text") def __str__(self): return self.key For each static page, e.g. About us or Contact us, first I've created the texts in the admin panel. Then, I've written the views below: class ContactUsPageView(ListView): """ In this view we are fetching site data from database, in a function named get_context_data. In this function, we filter the model for objects that contains the word 'contact', therefore fetching data referring to the about page only. After that the context list is sent to the template, and there with a for loop and an if statement, each key, value set is chosen for the proper place. """ model = SiteDataKeyValue template_name: str = "core/contact-us.html" def get_context_data(self, **kwargs): context = super(ContactUsPageView, self).get_context_data(**kwargs) context["contact_page_data"] = self.model.objects.filter(key__contains="contact") return context Finally, in the template, I'm trying to use these data with a for loop and an if statement as shown below: {% for text in contact_page_data %} {% if text.key == "contact us factory address" %} <p class="card-text"><i class="bi bi-geo-alt me-2"> {{ text.value }} </p> {% endif %} {% endfor %} I have just … -
OSError: [Errno 63] File name too long: db.sqlite3 when doing collectstatic on django
I already have done collectstatic before, and it went well. Now I tried to deploy the app to Heroku, and got the error. It reproduces locally as well. OSError: [Errno 63] File name too long: '/Users/admin/Desktop/Programming/Python/UkranianFunds/src/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/db.sqlite3' Here is my project structure: https://monosnap.com/file/Jkom9ug3DJFMDcwOz4UkY3OUfS1bUY I have my db.sqlite3 in gitignore if that matters. Here is my settings: PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR), 'static' ] -
CANT_FIND_SAVED_IMPORT, Can't import CSV file
I have got an error every time, this is because the mappingId is wrong, where I need to create/get mappingId? any solution. {"type":"error.SuiteScriptError","name":"CANT_FIND_SAVED_IMPORT","message":"No saved import with internalId 123","stack":["createError(N/error.js)","<anonymous>(adhoc$-1$debugger.user:13)","<anonymous>(adhoc$-1$debugger.user:1)"],"cause":{"type":"internal error","code":"CANT_FIND_SAVED_IMPORT","details":"No saved import with internalId 123","userEvent":null,"stackTrace":["createError(N/error.js)","<anonymous>(adhoc$-1$debugger.user:13)","<anonymous>(adhoc$-1$debugger.user:1)"],"notifyOff":false},"id":"","notifyOff":false,"userFacing":false} require(["N/task","N/file"],function(task,file){ var fileObj = file.create({ name:"temporary.csv", fileType:file.Type.CSV, contents: "1,1" }); var obj = task.create({taskType: task.TaskType.CSV_IMPORT}); obj.mappingId = 123; obj.importFile = fileObj; obj.name = "TestingCSV"; var objId = obj.submit(); log.debug(objId); }); -
How to use reporting and statistics capabilities for blog post using django
models.py from django.db import models from django.contrib.auth.models import User STATUS = ( (0,"Draft"), (1,"Publish") ) class BlogModel(models.Model): id = models.AutoField(primary_key=True) blog_title = models.CharField(max_length=200) blog = models.TextField() status = models.IntegerField(choices=STATUS, default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['-created_at'] def __str__(self): return f"Blog: {self.blog_title}" class CommentModel(models.Model): your_name = models.CharField(max_length=20) comment_text = models.TextField() created_at = models.DateTimeField(auto_now_add=True) blog = models.ForeignKey('BlogModel', on_delete=models.CASCADE) class Meta: ordering = ['-created_at'] def __str__(self): return f"Comment by Name: {self.your_name}" admin.py from django.contrib import admin from blog.models import BlogModel,CommentModel class PostAdmin(admin.ModelAdmin): list_display = ('blog_title', 'status','created_at','updated_at') list_filter = ('status',) search_fields = ('blog_title', 'content',) admin.site.register(BlogModel, PostAdmin) admin.site.register(CommentModel) I created a simple blog post website with comments and I want to create reports and on the admin panel I have to see how to achieve this. Like how many posts are created and how many have comments and how many post are draft and published -
how to return 5 top names per month, truncMonth
I've these models: class City(models.Model): name = models.CharField(max_length=150) class Hospital(models.Model): name = models.CharField(max_length=150) city = models.ForeignKey(City, on_delete=models.CASCADE, related_name="hospital") class Patient(models.Model): name = models.CharField(max_length=150) city = models.ForeignKey(City, on_delete=models.CASCADE, related_name="patients") hospital = models.ForeignKey(Hospital, on_delete=models.CASCADE, related_name="patients", blank=True, null=True) date_visited = models.DateTimeField(auto_now_add=True) i want to return top 5 hospitals per month which has most patients visited for example: month : 10/1/2022 hospital A : 100 patient hospital B : 95 patient hospital C : 80 patient hospital D : 60 patient hospital E : 55 patient and so on. my views.py from django.db.models.functions import TruncMonth Patient.objects.annotate(month=TruncMonth('date_visited')) #im not sure how to complete it! I appreciate your helps Thank you -
How to save html tags with text to database? django & react
I am using CKEditor to enter text and saving into database. When I retrieve it description, it also shows the html p tags which i dont want. How can I save it into database such that the p tags don't show but tags like are still applied. Essentially I want to save it as html itself and not text. Is there a way I can do that? Currently I am using TextField to store the description. -
Django Guardian with Data Migration (adding Anonymous user to public group)
I'm trying to perform a data migration in an app. I would like to add the anonymous user (the django-guardian AnonymousUser) to a public group. Somehow the user does not exist when i'm running test. It does work with my develop. Thanks in advance. As it seems that the anonymous user is created on management init, I tried to import the module in apply_migration without success. # Generated by Django 4.1 on 2022-10-19 12:11 from django.db import migrations from guardian.utils import get_anonymous_user from recipebook.settings import PUBLIC_GROUP_NAME from django.contrib.auth.models import Group def apply_migration(apps, schema_editor): import guardian.management.__init__ public_group = Group.objects.get( name=PUBLIC_GROUP_NAME ) user = get_anonymous_user() user.groups.add(public_group) def revert_migration(apps, schema_editor): public_group = Group.objects.get( name=PUBLIC_GROUP_NAME ) user = get_anonymous_user() user.groups.remove(public_group) class Migration(migrations.Migration): dependencies = [ ('recipebook', '0031_recipenutrition_vitamine_b3'), ('guardian', '0001_initial'), ] operations = [ migrations.RunPython(apply_migration, revert_migration) ] -
Error "mysqlclient‑1.4.6‑cp39‑cp39‑win_amd64.whl" is not a supported wheel on this platform
I am trying to create Django backend and and I am getting this error while installing MySQL client how can I solve this issue? -
Django admin Cannot Submit Form
I face some trouble while accessing django admin. It turns out that cannot create new objects from Django Admin. Here is how it looks if I want to create new user: I got the error Blocked form submission to '' because the form's frame is sandboxed and the 'allow-forms' permission is not set. Is there something that I should add in my settings file to resolve this error ? -
Django bulk load
I want to load my page faster in my Django project, so I know there has the "Bulk" option. views.py: class HRListView(Budgetlevel2Mixin, BudgetMixin, LoginRequiredMixin, ListView): model = HR template_name = "budget/hr_list.html" models.py: class HR(models.Model): year_scenario_version = models.ForeignKey( measure_name = models.ForeignKey( employee_type = models.ForeignKey( employee_level = models.ForeignKey( subsidiary = models.ForeignKey( department = models.ForeignKey( currency = models.ForeignKey( hr_list.html: {% block thead %} <tr> <th>ID</th> <th>HR Year Scenario</th> <th>Measure Name</th> <th>Employee Type</th> <th>Employee Level</th> <th>Subsidiary</th> <th>Department</th> </tr> {% endblock %} {% block tbody %} {% for q in object_list %} <tr> <td>{{ q.id }}</td> <td>{{ q.year_scenario_version }}</td> <td>{{ q.measure_name }}</td> <td>{{ q.employee_type }}</td> <td>{{ q.employee_level }}</td> <td>{{ q.subsidiary }}</td> <td>{{ q.department }}</td> </tr> {% endfor %} {% endblock %} How can I improve the page loading time? It takes almost 10 sec for full loading, something around 1200 records. Thanks a lot! -
Django url mapping error - URL doesn't match error
HI I got an error when calling an endpoint from django url Here is my piece of javascript window.location.assign(`customer/?id=1`} My urls.py path('customer/(?P<int:id>\d+)', views.get_customer, name="get_customer") Here is how it is called in the views.py def get_customer(request, id): print(f"the id {id}") # # customer = get_object_or_404(Customer, pk=id) # # print(f"customer {customer}") The Idea is to get the customer record filtered by id passed as query paramas But I got an error Using the URLconf defined in inventorymanagement.urls, Django tried these URL patterns, in this order: admin/ [name='home'] customer/(?P<int:id>\d+) [name='get_customer'] The current path, customer/, didn’t match any of these. Any idea on how to solve this? -
Accordion makes whole div move in the page
When opening a long text accordion, the whole page (or the whole div) moves slightly. I attach a little video to show the problem visually here. I have the accordions displaying information from a django template engine loop, here's the template code: <div class="accordion accordion-borderless" id="accordion_{{ forloop.counter }}"> <div class="accordion-item"> <h2 class="accordion-header" id="heading_{{ forloop.counter }}"> <button class="accordion-button collapsed" type="button" data-mdb-toggle="collapse" data-mdb-target="#collapse_{{ forloop.counter }}" aria-expanded="false" aria-controls="collapse_{{ forloop.counter }}" > {{event.title}} </button> <div id="collapse_{{ forloop.counter }}" class="accordion-collapse collapse" aria-labelledby="heading_{{ forloop.counter }}" data-mdb-parent="#accordion_{{ forloop.counter }}"> <div class="accordion-body"> {{event.description|safe}} </div> </div> </div> </div> What is causing that movement and how can it be solved? -
djongo + mongodb, Array Data Insert Problem
I have a problem. Stack: Django-Rest-Framework + Djongo + Mongodb. Problem: Insert error array data //models.py from django.db import models from djongo import models as djongoModels class House(models.Model): house_id = models.CharField(max_length=256) class Meta: abstract = True class Users(models.Model): _id = djongoModels.ObjectIdField() email = djongoModels.CharField(max_length=256) name = djongoModels.CharField(max_length=256) house = djongoModels.ArrayField( model_container=House ) class Meta: db_table = "drf_users" //serializers.py from .models import Users, Houses from rest_framework import serializers class InsertUserSerializers(serializers.ModelSerializer): email = serializers.CharField(required=True) name = serializers.CharField(required=True) house = serializers.ListField(child=serializers.CharField()) class Meta: model = Users fields = ('email', 'name', 'house') //views.py from .models import Users from .serializers import InsertUserSerializers class UsersViewSet(viewsets.ModelViewSet): queryset = Users.objects.all() serializer_class = InsertUserSerializers permission_classes = [AllowAny] //request.http POST http://<domain>/drf/house/ HTTP/1.1 Content-Type: application/json { "email": "test6@stay.co.kr", "name": "test6", "house": ["SEOU-2023-1023-0002","GYOU-2023-1022-0001"] } //pip freeze asgiref==3.5.2 backports.zoneinfo==0.2.1 certifi==2022.9.24 cffi==1.15.1 charset-normalizer==2.1.1 cryptography==38.0.1 Deprecated==1.2.13 Django==4.1 django-cors-headers==3.13.0 django-filter==22.1 django-oauth-toolkit==2.1.0 django-rest-framework==0.1.0 django-rest-framework-mongoengine==3.4.1 djangorestframework==3.13.1 djongo==1.3.6 dnspython==2.2.1 idna==3.4 jwcrypto==1.4.2 mongoengine==0.24.2 oauthlib==3.2.1 Pillow==9.2.0 pycparser==2.21 pymongo==3.12.3 pytz==2022.2.1 requests==2.28.1 sqlparse==0.2.4 urllib3==1.26.12 wrapt==1.14.1 I want a final db values. enter image description here Is this serializers problem? Or Djongo problem. If remove a serializers house array field, there is no error. What's wrong with my source code. Please help me. -
Object of type set is not JSON serializable while using api
Traceback (most recent call last): File "c:\Kunal\Project\Django Projects\Celery\separate.py", line 12, in <module> resp = json.dumps(client.send_message( File "C:\Users\i7tuf\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\models.py", line 319, in prepare self.prepare_body(data, files, json) File "C:\Users\i7tuf\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\models.py", line 471, in prepare_body body = complexjson.dumps(json, allow_nan=False) File "C:\Users\i7tuf\AppData\Local\Programs\Python\Python39\lib\site-packages\simplejson\__init__.py", line 398, in dumps return cls( File "C:\Users\i7tuf\AppData\Local\Programs\Python\Python39\lib\site-packages\simplejson\encoder.py", line 298, in encode chunks = list(chunks) File "C:\Users\i7tuf\AppData\Local\Programs\Python\Python39\lib\site-packages\simplejson\encoder.py", line 696, in _iterencode for chunk in _iterencode_dict(o, _current_indent_level): File "C:\Users\i7tuf\AppData\Local\Programs\Python\Python39\lib\site-packages\simplejson\encoder.py", line 652, in _iterencode_dict for chunk in chunks: File "C:\Users\i7tuf\AppData\Local\Programs\Python\Python39\lib\site-packages\simplejson\encoder.py", line 652, in _iterencode_dict for chunk in chunks: File "C:\Users\i7tuf\AppData\Local\Programs\Python\Python39\lib\site-packages\simplejson\encoder.py", line 716, in _iterencode o = _default(o) File "C:\Users\i7tuf\AppData\Local\Programs\Python\Python39\lib\site-packages\simplejson\encoder.py", line 272, in default raise TypeError('Object of type %s is not JSON serializable' % TypeError: Object of type set is not JSON serializable Code Image -
Django Create a copy of a Model upon trigger
I'm wondering if the following is possible in Django. As I start my the project, I will create a Model with 'x' fields called BASEMODEL. I will then create another Model called PROJECT with just 1 CharField. I will be creating both these in the usual way models.py, makemigrations, migrate etc. Then as the admin when I add a record to PROJECT with a value 'PROJECT1', is it possible for Django to create a copy of the BASEMODEL called BASEMODEL_PROJECT1 ? I'm not looking for the exact code, just looking for any ideas or links as to how I could possibly do so. Thanks. -
Django authentication always return none
My authentication doesn't seem to work. I got registration and everything, its just the log in and authenticate aspect that doesnt work. I'm not sure why. I'm not sure as to why my django auth returns none. I have this in my settings: AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'UniLinkedApp.auth.MyAuthBackEnd', ) I have my models as: class Register(models.Model): username = models.CharField(max_length = 200) email = models.EmailField(max_length = 200) password = models.CharField(max_length = 200) university = models.CharField(max_length=50) major = models.CharField(max_length = 200) def __str__(self): return self.user class MyAccountManager(BaseUserManager): def create_user(self, username, email, password, university, major): if not email: raise ValueError("Users must have an email address") if not username: raise ValueError("Users must have an username") user = self.model( username=username, email=self.normalize_email(email), password = password, university = university, major = major, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( username=username, email=self.normalize_email(email), password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): username = models.CharField(max_length = 200) email = models.EmailField(max_length = 200) password = models.CharField(max_length = 200) university = models.CharField(max_length=50) major = models.CharField(max_length = 200) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = … -
How to set PIPENV_IGNORE_VIRTUALENVS=1?
While trying to create a venv for a django project while beeing in the projects dir using pipenv, I noticed that after installing django with pipenv (pipenv install django), pipenv sent a message: Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project. You can set PIPENV_IGNORE_VIRTUALENVS=1 to force pipenv to ignore that environment and create its own instead. You can set PIPENV_VERBOSITY=-1 to suppress this warning. Creating a Pipfile for this project... Installing django... [= ] Installing django...[packages]... Installation Succeeded Pipfile.lock not found, creating... Locking [packages] dependencies... Building requirements... Resolving dependencies... Success! Locking [dev-packages] dependencies... Updated Pipfile.lock (99c4b9ec1b8891ff787677276760beb6d6d4919c55660da1c713682156a6086c)! Installing dependencies from Pipfile.lock (a6086c)... To activate this project's virtualenv, run pipenv shell. Alternatively, run a command inside the virtualenv with pipenv run. After this I ran the command (pipenv --venv) and got this message: Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project. You can set PIPENV_IGNORE_VIRTUALENVS=1 to force pipenv to ignore that environment and create its own instead. You can set PIPENV_VERBOSITY=-1 to suppress this warning. C:\Users\User7G\OneDrive\Desktop\My code\My … -
How to split django 'models.py', 'views.py', 'serializers.py' files into multiple files
Hello, For educational purposes, I am building a django app with multiple models and relationships. According to the official tutorial and many implementations I found online, the database models and serializers as well as views are all defined in single files: "models.py", "serializers.py", and "views.py". So, the project directory looks as follows: > my_app > migrations > __init__.py > admin.py > models.py > apps.py > serializers.py > tests.py > urls.py > views.py Depending on how many models are included in the app, those files may grow to hundreds or even thousands lines of code. As a result, developing and maintaining the application becomes extremely challenging. I would like to split these files so that every model (and coresponding serializer and view) will be defined in a separate per-model files. as follows: > my_app > migrations > models > __init__.py > model1.py > model2.py > model3.py > model4.py > serializers > __init__.py > model1_serializers.py > model2_serializers.py > model3_serializers.py > model4_serializers.py > views > __init__.py > model1_views.py > model2_views.py > model3_views.py > model4_views.py > __init__.py > admin.py > apps.py > tests.py > urls.py I encountered some difficulties in splitting these files and have not yet found an optimal solution. The Problem In … -
How to concatenate the values of a subquery that returns more than one row into a single row in Django
I have this query: forms = forms.annotate( transaction_id=F('id'), program=F('program__name'), action_plan=Subquery(Action.objects.using('db').filter( mid_id=OuterRef('transaction_id'), ).values('plan')) But it returns "django.db.utils.ProgrammingError: more than one row returned by a subquery used as an expression" How can i concatenate all values returned in one row separated by ","? -
Use Javascript to call function in models.py and update model field
I am developing an ecommerce website. I want my customers to view updated total_price field on the sidebar located alongside the order form. My model.py looks as follows: class Order(models.Model): Customer = models.ForeignKey(User, on_delete=models.CASCADE) no_of_pages = models.PositiveIntegerField(default=1) def total_price(self): price_per_page = 20 return no_of_pages * price_per_page Now I have my views.py and forms.py. I have also rendered a html template to display the form and allow the user to place the order by indicating the number of pages. My views.py is as follows: def OrderView(request): order_list = Order.objects.all() if request.POST: form = OrderingForm(request.POST) if form.is_valid(): form.save() return redirect('home') return render(request, 'orderingsystem/ordercreate.html', {"form": OrderingForm}) My aim is to display a the total price on the side of the order page as soon as the customer selects number of pages without any HttpResponse because the form is not yet submitted at this stage. For example: If the Customer selects one page, the total price to be displayed = 1 * 20 = 20; if the customer selects 2 pages, the sidebar widget that displays total price updates automatically to 2 * 20 = 40, without any Http call. In other words, I want something like JavasScript to call def total_price() in my …