Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to to make Django default id (pk) to random and bigger in length
I am creating an where in my model Profile i am getting the default id with the name id, but the issue it is generating ids from 0 to onwards like 1,2,. What I want is a random id which should also be longer length like 343347 etc. -
Django/wagtail admin page links pointing to invalid address
I have a wagtail site and have a problem with the ‘users’ section of the admin page My users/admin.py is : from django.contrib import admin from django.contrib.auth import admin as auth_admin from django.contrib.auth import get_user_model from psymatik.users.forms import ( UserChangeForm, UserCreationForm, ) User = get_user_model() admin.site.register(User) class UserAdmin(auth_admin.UserAdmin): form = UserChangeForm add_form = UserCreationForm fieldsets = ( ("User", {"fields": ("username",)}), ) + auth_admin.UserAdmin.fieldsets list_display = ["username", "is_superuser"] search_fields = ["username"] And my users/wagtail_hooks.py is: from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register from .models import User class UserAdmin(ModelAdmin): model = User menu_label = "Users" menu_icon = "pick" menu_order = 200 add_to_settings_menu = False exclude_from_explorer = False list_display = ( "name") list_filter = ("name") search_fields = ("name") modeladmin_register(UserAdmin) The issues I have is that when I am at admin/users and I click on the Users link in the sidebar I am taken to admin/users/user and get the error “ValueError at /admin/users/user/ Field 'id' expected a number but got 'user’.” Why is the sidebar link pointing to admin/users/user rather than just admin/users (which does work)? What is the best way to set this up? -
Why Django ignores the order of conditions in filter()?
When filtering multiple conditions with Django queryset filter(), the order of conditions in filter() is not guaranteed. Especially when I filter date/datetime fields, they're filtered at the last in the WHERE clause. These two querysets generate the same SQL with the same WHERE clause. dt = datetime(2022, 1, 1) User.objects.filter(joined_at__lt=dt, is_active=True) User.objects.filter(is_active=True, joined_at__lt=dt) SELECT * FROM `user` WHERE (`user`.`is_active` = 1 AND `user`.`joined_at` < '2022-01-01 00:00:00') I know I can fix this problem with chaining filters. But I'm wondering why Django ignores the order of conditions in filter(). And what is the rule for Django to decide the order in the filter()? -
Filter in the template if the product is in wishlist or no. Django ecommerce website
I had a question about django-templates. I was wondering about if we can add a filter in django template. I want to know if the product is in wishlist or no while rendering it. So, how can we know if it's in the wishlist or no? views.py def store(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] categories = Category.objects.all() products = Product.objects.all() if request.user.is_authenticated: user=request.user wishedProducts = Wishlist.objects.filter(user=user) else: wishedProducts = {} """popularnye = Product.objects.filter(popularnye=True)""" context = {'products':products, 'cartItems':cartItems, 'order':order, 'items':items, 'categories':categories,'wishedProducts':wishedProducts} return render(request, 'store/store.html', context) models.py class Wishlist(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, verbose_name="Название товара",null=True) user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: unique_together = ( ('user', 'product'), ) verbose_name = 'Избранные' verbose_name_plural = "Избранные" def __str__(self): return str(self.product) template {% for product in products %} <div class="store col-lg-3 col-6"> <div class="single-product"> <div class="single-product"> <div class="header-single-product"> <p style="margin-top:-10px;margin-bottom:-10px" class="code">Код: 51265</p> {% if product in wishedProducts.products %} <i class="bi bi-heart-fill addWishlist" style="color: red" data-product="{{product.id}}" data-action="add"></i> {% else %} <i class="bi bi-heart addWishlist" data-product="{{product.id}}" data-action="add"></i> {% endif %} <i class="fa fa-balance-scale" style="margin-right:5px;"></i> ........ -
Serializer gets null for columns in a table in a foreign key’s reverse direction
In a scenario of transaction processing, we have: table order to record incoming transactions, and table order_log to log updates on a recorded order, with a foreign key to table order. A recorded order may have zero to multiple updates on the log. We want to make a flattened view of the two tables like a SQL query selecting from order left outer join order_log, with the following behaviour: if the order has no update, list the order in joint with null values; if the order has one update, list the order in joint with the update log; if the order has multiple updates, list the order multiple times in joint with each update log. As the sample source code below, we used .prefetch_related('orderlog_set'), and it gets the wanted flattening effect, and the Django backend log shows a left-outer-join SQL query sent to the database as expected. So, the mutual relation works correctly for all the three conditions above. However, we cannot retrieve columns in order_item, as the table is in a foreign key's reverse direction. The serializer FlatOrderLogSerializer bases its meta-model on the table order, so it refers to table order_log by a foreign key's reverse or backward direction. … -
No matching distribution found for django-modeltranslation==0.17.3
I want to install an existing Django project which has dependencies. The project dependencies can be installed with pipenv install command. Running pipenv install resulting: pipenv install /home/mahdi/anaconda3/lib/python3.9/site-packages/pkg_resources/__init__.py:122: PkgResourcesDeprecationWarning: 4.0.0-unsupported is an invalid version and will not be supported in a future release warnings.warn( Pipfile.lock (6ab9a1) out of date, updating to (5b3760)... Locking [dev-packages] dependencies... Building requirements... Resolving dependencies... ✔ Success! Locking [packages] dependencies... Building requirements... Resolving dependencies... ✘ Locking Failed! ERROR:pip.subprocessor:Command errored out with exit status 1: command: /home/mahdi/.local/share/virtualenvs/WeSync-UUOFIsQX/bin/python /tmp/pip-standalone-pip-qah9wd89/__env_pip__.zip/pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-gm4__bne/overlay --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'setuptools>=40.8.0' wheel cwd: None Complete output (17 lines): Traceback (most recent call last): File "/home/mahdi/anaconda3/lib/python3.9/runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "/home/mahdi/anaconda3/lib/python3.9/runpy.py", line 87, in _run_code exec(code, run_globals) File "/tmp/pip-standalone-pip-qah9wd89/__env_pip__.zip/pip/__main__.py", line 16, in <module> File "<frozen zipimport>", line 259, in load_module File "/tmp/pip-standalone-pip-qah9wd89/__env_pip__.zip/pip/_internal/cli/main.py", line 10, in <module> File "<frozen zipimport>", line 259, in load_module File "/tmp/pip-standalone-pip-qah9wd89/__env_pip__.zip/pip/_internal/cli/autocompletion.py", line 9, in <module> File "<frozen zipimport>", line 259, in load_module File "/tmp/pip-standalone-pip-qah9wd89/__env_pip__.zip/pip/_internal/cli/main_parser.py", line 7, in <module> File "<frozen zipimport>", line 259, in load_module File "/tmp/pip-standalone-pip-qah9wd89/__env_pip__.zip/pip/_internal/cli/cmdoptions.py", line 24, in <module> File "<frozen zipimport>", line 259, in load_module File "/tmp/pip-standalone-pip-qah9wd89/__env_pip__.zip/pip/_internal/exceptions.py", line 10, in <module> ModuleNotFoundError: No module named … -
Validate form data and query params in one serializer in APIView in django rest framework
I am using django rest framework for my web API. In my post API I need both the form data and the query params from the request and pass it to serializer for validation. To achieve this I am doing this: version = request.query_params.get('version', 'v1') serializer = MySerializer( data=request.data, context={'version': version}) and in the serializer I am accessing it like this: version = serializers.CharField(required=False, default='v1') and then accessing it in my APIView as: if serializer.is_valid(): data = serializer.validated_data print("version: ", data['version']) Even if I pass v2 as the query params it always prints v1. What am I doing wrong here? -
Best way to get chatroom from a consumer - Django channels
I want to store messages sent through a django-channels websocket connection to be stored in the db. This interaction would happen in the recieve function of the consumer(I would think). I need the chatroom model which this chat is happening in. I can get the pk of the chatroom(its in the url) but it seems like a bad idea to make a query for the room every time that a message is sent. Anyone got better ideas? -
Django - Cannot find URL "Using the URLconf defined in contactform.urls, Django tried these URL patterns, in this order"
I am able to successfully compile my program, but when I go to the localhost address, it gives me an error. I have searched other forums about the same problem, but I couldn't find a solution for mine. Am I missing something here? I'm new to Django, so any is appreciated. Using the URLconf defined in contactform.urls, Django tried these URL patterns, in this order: admin/ showform The empty path didn’t match any of these. settings.py: INSTALLED_APPS = [ 'contact.apps.ContactConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'contactform.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'contactform.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'userInfo', 'USER': 'root', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '3306', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" } } } apps.py from django.apps import AppConfig class ContactConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'contact' manage.py #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys import pymysql pymysql.install_as_MySQLdb() def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'contactform.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: … -
problem setting up django cant run " manage.py runserver"
my situation : i have windows 10 ppython 3 on the pycharm terminal i type pip install django success Then I create a folder named "pycal". On the command prompt I went to the folder "pycal". Then django-admin.py startproject newproject. This is successful. Then I run python manage.py runserver. It tells me "The system cannot execute the specified program" any feedback would be really appreciated -
OPT delete after verification in database
I am working with Django and I verified my user with email OTP, and OTP saved in the database. After verification, I want to delete OTP in the database. Otherwise, the user does not verify the account within two minutes, so I want to delete OTP from the database views.py class MyTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): data = super().validate(attrs) serializer = UserSerializer(self.user).data for k, v in serializer.items(): data[k] = v return data class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer class RegisterView(APIView): permission_classes = [AllowAny] def post(self, request): try: data = request.data serializer = UserSerializer(data=data) if serializer.is_valid(): serializer.save() send_otp_via_email(serializer.data['email']) return Response({ 'status': '200', 'message': 'User registered successfully Please Check your email for verification', 'data': serializer.data }) return Response({ 'status': '400', 'message': 'User registration failed', 'data': serializer.errors }) except Exception as e: return Response({ 'status': '400', 'message': 'User registration failed', 'data': str(e) }) class VerifyOTP(APIView): permission_classes = [AllowAny] def post(self, request): try: data = request.data serializer = VerifyAccountSerializer(data=data) if serializer.is_valid(): email = serializer.data['email'] otp = serializer.data['otp'] user = User.objects.filter(email=email) if not user.exists(): return Response({ 'status': '400', 'message': 'email, user not exists', 'data': 'invalid email' }) if user[0].otp != otp: return Response({ 'status': '400', 'message': 'something went wrong', 'data': 'invalid OTP' }) user = user.first() user.is_valid … -
django.db.utils.IntegrityError: UNIQUE constraint failed: store_wishlist.user_id
I am working on ecommerce website. I wanted to implement wishlist function on my website. And, it is working if its the first time for user that is adding to the list. In the second time giving an error. What's the problem? Can someone please help me? views.py def addWishlistView(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('Action:', action) print('Product:', productId) user = request.user product = Product.objects.get(id=productId) if (Wishlist.objects.filter(user=user) and Wishlist.objects.filter(product=product)).exists(): print("Item is exists") else: Wishlist.objects.create(user=user,product=product) return JsonResponse('Item was added', safe=False) models.py class Wishlist(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, verbose_name="Название товара") user = models.OneToOneField(User, on_delete=models.CASCADE,null=True, blank=True) script js for (i = 0; i < wishlist.length; i++) { wishlist[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action if (user == 'AnonymousUser'){ Console.log("Not logged in"); }else{ addToWishlist(productId, action) } }) } function addToWishlist(productId, action){ console.log('User is authenticated, sending data...') var url = '/add_wishlist/' fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'productId':productId, 'action':action}) }) .then((data) => { location.reload() }) } -
Django: How to make a progress bar for a function in views.py which is taking time to complete?
I am working with django to develop a UI. In the backend one function is running some ML scripts hence its taking time to return the render template. The code is as below: home.html <a href="engine-s"> <button type="button" class="btn btn-primary btn-sm" title="Insight Engine" id="{{file}}"><i class="fas fa-solid fa-eye"></i></button> </a> views.py path('engine-s', views.engine_s, name='engine-s') manage.py def engine_s(request): text=get_text_from_pdf("demo_pdf_file\demo_file.pdf") file_to_analyze(text) return render(request, 'engine-s.html' ) So initialy my home page is home.html where there is a button which is initiating engine_s(request) and returning engine-s.html. But it is taking time as get_text_from_pdf function is there. So how to show a progress bar in my home.html for my engine_s function progress until it returns new page (engine-s.html)? Thanks. -
Unable redis cluster in django
I ran django on docker, but I found I couldn't use redis cluster. when I blocked all about redis cluster settings in settings.py, it works. python 3.10 django 3.2 plz help me -
Calling ngrok url(my localhost to ngrok) in python requests going infinite
I want to integrate a webhook in my Django application that supports only HTTPS requests. I want to test in my local machine so here I am using ngrok to make my localhost HTTPS i.e. https://c71e-2415-201-138f-ad9d-3005-825a-23c9-c788.ngrok.io/ and my local URL is http://localhost:8000 I created a URL in my application named call_webhook_internally and related views.py function is @csrf_exempt def call_webhook_internally(request): try: ng_rok_url = https://c71e-2415-201-138f-ad9d-3005-825a-23c9-c788.ngrok.io/ url = ng_rok_url + "call_webhook/" headers = { "Timestamp": str(datetime.utcnow()), } payload = json.loads(request.body) response = requests.request("POST", url, headers=headers, data=payload) return HttpResponse("success") except Exception as e: return HttpResponse("Error") the upper function is calling and when my request is called to call webhook using python it blocks the main thread and postman goes in an infinite loop, in ngrok terminal I am getting that request is received but in function, my print statement is not printing. I want to call my internal webhook in my existing app views.py function is call_webhook i.e. def call_webhook_internally(request): print(request) return HttpResponse("webhook_called") After 10-15 minutes getting error i.e. webhook failed. Error HTTPSConnectionPool(host='c10e-2105-215-138f-ad9d-3005-825a-23c9-c788.ngrok.io', port=443): Max retries exceeded with url: /call_webhook/ (Caused by SSLError(SSLError("read error: Error([('SSL routines', 'ssl3_get_record', 'decryption failed or bad record mac')],)",),)) so pls suggest to me some way to do this is … -
wagtail error on upload image in richtext field
when I try to upload image using richtext field in wagtail I'm getting a json respons html "\n\n\n\n\n<header class=\" \">\n \n <div class=\"row nice-padding\">\n <div class=\"left\">\n <div class=\"col header-title\">\n <h1>\n Choose a format</h1>\n </div>\n \n </div>\n <div class=\"right\">\n \n \n \n </div>\n </div>\n</header>\n\n\n<div class=\"row row-flush nice-padding\">\n <div class=\"col6\">\n <img alt=\"icon-check\" class=\"show-transparency\" height=\"512\" src=\"/media/images/3334352_01.max-800x600.png\" width=\"512\">\n </div>\n <div class=\"col6\">\n <form action=\"/cms/images/chooser/1/select_format/\" method=\"POST\" novalidate>\n <input type=\"hidden\" name=\"csrfmiddlewaretoken\" value=\"ih7zcLhxbo71c0TupgUmboJ8syIolZWshK6yfECc2zzHz0wqk009wKNyDXGHt4mX\">\n <ul class=\"fields\">\n \n \n<li class=\"required \">\n \n<div class=\"field choice_field radio_select \">\n <label for=\"id_image-chooser-insertion-format_0\">Format:</label>\n <div class=\"field-content\">\n <div class=\"input \">\n \n <ul id=\"id_image-chooser-insertion-format\">\n <li><label for=\"id_image-chooser-insertion-format_0\"><input type=\"radio\" name=\"image-chooser-insertion-format\" value=\"fullwidth\" required id=\"id_image-chooser-insertion-format_0\">\n Full width</label>\n\n</li>\n <li><label for=\"id_image-chooser-insertion-format_1\"><input type=\"radio\" name=\"image-chooser-insertion-format\" value=\"left\" required id=\"id_image-chooser-insertion-format_1\">\n Left-aligned</label>\n\n</li>\n <li><label for=\"id_image-chooser-insertion-format_2\"><input type=\"radio\" name=\"image-chooser-insertion-format\" value=\"right\" required id=\"id_image-chooser-insertion-format_2\">\n Right-aligned</label>\n\n</li>\n</ul>\n \n \n \n <span></span>\n </div>\n \n\n \n </div>\n</div>\n\n</li>\n \n \n<li class=\"required \">\n \n<div class=\"field char_field text_input \">\n <label for=\"id_image-chooser-insertion-alt_text\">Alt text:</label>\n <div class=\"field-content\">\n <div class=\"input \">\n \n <input type=\"text\" name=\"image-chooser-insertion-alt_text\" value=\"icon-check\" required id=\"id_image-chooser-insertion-alt_text\">\n \n \n \n <span></span>\n </div>\n \n\n \n </div>\n</div>\n\n</li>\n \n <li><input type=\"submit\" value=\"Insert image\" class=\"button\" /></li>\n </ul>\n </form>\n </div>\n</div>\n" step "select_format" I'm using wagtail 2.14.2 pip show wagtail Name: wagtail Version: 2.14.2 Summary: A Django content management system. and my django is Django==3.1.7 and the image chooser not working always return : Uncaught ReferenceError: createImageChooser is not defined -
int() argument must be a string, a bytes-like object or a number, not 'dict'
The function not entering into if condition, because round is dict and match_round is int, so showing error, how solve this? my modelviewset def destroy(self, request, *args, **kwargs): gameevent = self.get_object().gameevent match_round = self.get_object().match_round print(gameevent) print(match_round) round = Matchscore.objects.filter(gameevent=gameevent, match_round=match_round).values_list("match_round",flat=True).aggregate(Max("match_round")) print(round) if round == match_round: Matchscore.objects.get(match_round=round).delete() response = {"result": "successfully removed"} else: response = {"result": "can't delete this round"} return Response(response) -
Extending Models Django
How to change the model fields of an existing model which is in a package? (pip install fcm-django - FCMDevices), I need to add extra columns to that model and rename some of the fields. like column registration_id in (package model) need to rename as fcm_id -
VS code's launch.json arguments inserting quotes, causing Django extensions to fail
I am having trouble getting the "Run" option in VS Code working with Django Extensions. Django Extensions is an add-on which allows you to quickly spin up a TLS (SSL) endpoint. The way I typically start django is ./manage.py runserver_plus --cert /tmp/ 8000. I am attempting to replicate the same command by using the following fields in launch.json: "program": "${workspaceFolder}/manage.py", "args": [ "runserver_plus", "--cert /tmp/", "8000" ], However, the execution in the terminal is as follows: $ /home/farhan/src/axial/manage.py runserver_plus "--cert-file /tmp/abc123" 8000 usage: manage.py runserver_plus [-h] [--ipv6] [--noreload] [--browser] [--nothreading] [--threaded] [--output OUTPUT_FILE] [--print-sql] [--truncate-sql TRUNCATE_SQL] [--print-sql-location] [--cert CERT_PATH | --cert-file CERT_PATH] [--key-file KEY_FILE_PATH] [--extra-file EXTRA_FILES] [--reloader-interval RELOADER_INTERVAL] [--reloader-type RELOADER_TYPE] [--pdb] [--ipdb] [--pm] [--startup-messages STARTUP_MESSAGES] [--keep-meta-shutdown] [--nopin] [--nostatic] [--insecure] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color] [addrport] manage.py runserver_plus: error: unrecognized arguments: 8000 It seems that inserting is causing a problem. I have tried rearranging the second two arguments, but the result is no different. Any insights? Thanks! -
Django: django.db.migrations.exceptions.NodeNotFoundError
I was making new project and app. Then when I have typed 'python3 manage.py runserver' django.db.migrations.exceptions.NodeNotFoundError: Migration auth.0013_auto_20210902_0542 dependencies reference nonexistent parent node ('auth', '0012_alter_user_first_name_max_length') This error come to me. And even if I delete 'all' of my app's migrations forder It's still hapening This error is hapening to all of my projects and apps Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread Thread-1: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/kimhaju/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/kimhaju/.local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check_migrations() File "/home/kimhaju/.local/lib/python3.6/site-packages/django/core/management/base.py", line 453, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/home/kimhaju/.local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/home/kimhaju/.local/lib/python3.6/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/home/kimhaju/.local/lib/python3.6/site-packages/django/db/migrations/loader.py", line 274, in build_graph raise exc File "/home/kimhaju/.local/lib/python3.6/site-packages/django/db/migrations/loader.py", line 248, in build_graph self.graph.validate_consistency() File "/home/kimhaju/.local/lib/python3.6/site-packages/django/db/migrations/graph.py", line 195, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/home/kimhaju/.local/lib/python3.6/site-packages/django/db/migrations/graph.py", line 195, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/home/kimhaju/.local/lib/python3.6/site-packages/django/db/migrations/graph.py", line 58, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration auth.0013_auto_20210902_0542 dependencies reference nonexistent parent node ('auth', '0012_alter_user_first_name_max_length') -
Django graphql auth not showing all user fields in mutation
I have followed below tutorial to introduce user authentication in my django app. https://django-graphql-auth.readthedocs.io/en/latest/quickstart/ It has created the user mutations as below, Graphql user mutation The mutation to update user shows only two fields, first name and last name. However my user model has other fields as well like is_staff, is_superuser, gender. I would like to get control on updating those fields as well. Please advise how can I get that done? -
having issued running python3 manage.py runserver
(venv) C:\Users\USER\PycharmProjects\pyshop\pycal> python3 manage.py runserver The system cannot execute the specified program. -
import and use views from views.py to django admin
I have the below view in the view.py file and I want to use this view in Django admin. How can I impoert this view and use in django admin? def index(request): context = { 'customer': Customer.objects.filter(count__gt=0), } return render(request, "view-customer/index.html", context=context) -
Improperly configured at . error in Django REST framework
When I access the base URL of http://127.0.0.1:8000/ I get the following error ImproperlyConfigured at / Could not resolve URL for hyperlinked relationship using view name "wallet-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. When I try to access the admin URL it works fine but when I access my data URL which is http://127.0.0.1:8000/wallets I get a 404 error page not found? This is my serializers.py file from rest_framework import serializers from .models import Wallet class WalletSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Wallet fields = ('__all__') My views.py file is the following from django.shortcuts import render from rest_framework import viewsets from rest_framework.response import Response from rest_framework.decorators import api_view from .serializers import WalletSerializer from .models import Wallet @api_view(['GET']) def getData(request): queryset = Wallet.objects.all() serializer = WalletSerializer(queryset, many=True, context={'request': request}) return Response(serializer.data) I was using a simple class in my views.py file instead of 'GET' functions which I am doing now and I was also using routers in my urls.py file but I removed all that so I could create CRUD functions but I face this problem now -
How to sort and filter queryset based on select_related in Django ORM
I have two tables in my models as show below: class Coin(models.Model): coin_id = models.CharField(max_length=100, primary_key=True, unique=True) name = models.CharField(max_length=100, null=True, blank=True) class Fundamental(models.Model): coin_id = models.OneToOneField(Coin, to_field="coin_id", db_column="coin_id", on_delete=models.CASCADE) market_cap = models.BigIntegerField(null=True, blank=True) price = models.FloatField(null=True, blank=True) Now I want to get the top 1000 coins sorted by market cap, or market cap range is between 1000-1000000. coins = Coin.objects.select_related('fundamental').order_by('ticker__market_cap')[:1000] I'm writing my query like this, but it is working for some of the coins, but if any coin doesnot exists, it shows the exception like screener.models.Coin.fundamental.RelatedObjectDoesNotExist: Coin has no fundamental. Does anyone will help me to filter a query in a good way