Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I've been trying to use asyncio to speed up this loop with api requests and dictionary making but it seems to remain so slow, taking over 2 seconds
... over 2 seconds just for a total of 4 data requests to the exchange and dictionary making function. if someone has any suggestions it would be a big help. async_tasks = [] async def sigBuy(count): bot_dict = Bot.to_dict(activeBots[count]) sigSettings_dict = Bot.to_dict(activeBots[count].sigSettings) # Binance API and Secret Keys Bclient = Client(sigSettings_dict['API_key'], sigSettings_dict['API_secret_key']) p = round(float(percentage(7, bot_dict['ct_balance']) / (float(bin_asset_price['price']) / 1)), 8) # Round and Asign the asset_amount asset_amount = round(p, 2) # shouldILog = await makeBuy(market, asset_amount, Bclient, sigSettings_dict['base_currency']) shouldILog = 2 if shouldILog == 2: asset_amount = int(asset_amount) last_trade = Bclient.get_all_orders(symbol=market + sigSettings_dict['base_currency'])[-1] print(last_trade) asset_price = float(last_trade['cummulativeQuoteQty']) / float(last_trade['executedQty']) buyInPrice = float(last_trade['cummulativeQuoteQty']) for otrade in activeBots[count].opentrades.all(): trade = Bot.to_dict(otrade) del trade['id'] otradesUpdate.append(trade) openTrades_dict = {'bot_ID': bot_dict['id'], 'date': date, 'market': market, 'trade_mode': 'Buy', 'price': asset_price, 'amount': asset_amount, 'amount_in_base_currency': buyInPrice, 'result': 0} otradesUpdate.append(openTrades_dict) BotsUpdate.append(bot_dict) SigSettingsUpdate.append(sigSettings_dict) for count, bot in enumerate(activeBots): async_tasks.append(loop.create_task(sigBuy(count))) loop.run_until_complete(asyncio.gather(*async_tasks)) -
link multiple database models in django by unrelated fields
In sql if there are two table which have fields that have data with resemblance but do not have connection together you can links them up like this select tab1.name, tab1.gender, tab1.occupation, tab2.location , tab2.biz_time ,tab3.address from staffdata tab1, sales tab2, address tab3 where tab1.user_id=tab2.user_id and tab3.location_id=tab2.location_id this would link them up to produce results from the 3 tables I have tried subquery, annotate with values but was getting wrong result this is what i have tried code_subquery = SalesRecord.objects.filter(staff__username__iexact=request.user, user_id=OuterRef('user_id')) timetablevalues= StaffData.objects.filter(staff=request.user, user_id=Subquery( code_subquery.values( 'location', 'biz_time', 'item')))\ .values('name','gender', 'location', 'biz_time', 'item') Although this is for 2 tables but I might do that of 3 tables later on Please how can I go about it -
How to filter a list JSONField exactly?
I have a model that essentialy boils down to this: class Model: json_field = ArrayField() Where json_field is essentially a list of strings. So let's say I have two Model objects ModelA and ModelB that have their json_field as ["1","2","3"]and ["1","2","4"] respectively. How can I filter to the json_field exactly? Specifically: What is the search value? What is the query that filters by the search value? value = ["1","2","3"] # Doesn't work value = "1","2","3" # Also doesn't work # Not even sure if this is the correct approach Model.objects.filter(json_field__iexact=value) I'm actually using django-filter to manage this search function for a DRF backend. (e.g. /api/v1/models/?json_field=) Unfortunately, there doesn't seem to be an ArrayFilter or a JSONFilter so this is what I'm working with: class ModelFilter(django_filter.FilterSet): class Meta: model = Model field = "json_field" # Not even sure if this should be a CharFilter json_field = django_filters.CharFilter(method="json_field_filter") def json_field_filter(self, queryset, name, value): return queryset.filter(json_field__iexact=value) # doesn't work where value = ["1","2","3"] # also doesn't work where value = "1","2","3" I can find solutions online (from which I've worked to the above) for dictionaries but nothing for lists. Would appreciate any help/pointers. -
ElasticSearch, FarmHaystack, Django connection Refused
I'm trying to make this https://haystack.deepset.ai/docs/latest/tutorial5md into a Dockerized Django App, the problem is when I impliment the code locally it works but when I make a dockerized version of it it gives me a connection refused, my guess is that the two docker images can't find they'r ways to each other. This is my docker-compose.yaml file version: '3.7' services: es: image: elasticsearch:7.8.1 environment: - xpack.security.enabled=false - "ES_JAVA_OPTS=-Xms512m -Xmx512m -Dlog4j2.disable.jmx=true" - discovery.type=single-node - VIRTUAL_HOST=localhost ports: - "9200:9200" networks: - test-network container_name: es healthcheck: test: ["CMD", "curl", "-s", "-f", "http://localhost:9200"] retries: 6 web: build: . command: bash -c "sleep 1m && python manage.py migrate && python manage.py makemigrations && python manage.py runserver 0.0.0.0:8000" volumes: - .:/app networks: - test-network ports: - "8000:8000" depends_on: - es healthcheck: test: ["CMD", "curl", "-s", "-f", "http://localhost:9200"] retries: 6 networks: test-network: driver: bridge and this is my apps.py from django.apps import AppConfig import logging # from haystack.reader.transformers import TransformersReader from haystack.reader.farm import FARMReader from haystack.preprocessor.utils import convert_files_to_dicts, fetch_archive_from_http from haystack.preprocessor.cleaning import clean_wiki_text from django.core.cache import cache import pickle from haystack.document_store.elasticsearch import ElasticsearchDocumentStore from haystack.retriever.sparse import ElasticsearchRetriever from haystack.document_store.elasticsearch import ElasticsearchDocumentStore class SquadmodelConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'squadModel' def ready(self): document_store = ElasticsearchDocumentStore(host="elasticsearch", username="", password="", index="document") … -
AUTH_USER_MODEL refers to model 'auth_app.AuthAppShopUser' that has not been installed
I am trying to implement shopify authentication via using this library from github: https://github.com/discolabs/django-shopify-auth However, after assigning the following value in "settings" and completing other related steps, getting the following error: AUTH_USER_MODEL refers to model 'auth_app.AuthAppShopUser' that has not been installed views.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'shopify_auth', ] AUTH_USER_MODEL = 'auth_app.AuthAppShopUser' auth_demo/models.py: from django.db import models from shopify_auth.models import AbstractShopUser class AuthAppShopUser(AbstractShopUser): pass -
Login not redirecting to the specified url on django
I want to be redirected to the dashboard page in the website but I'm being redirected to a different url which is not specified in django url and as a result I'm getting page not found error. I don't know why django is not redirecting me to the login_url_redirect that is specified in the settings.py. settings.py AUTH_USER_MODEL = 'account.UserBase' LOGIIN_REDIRECT_URL = '/account/dashboard' LOGIN_URL = '/account/login' urls.py url.py(in the main django app) urlpatterns = [ path('account/', include('account.urls', namespace='account')), ] urls.py (for the given app) urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name='account/registration/login.html', form_class=UserLoginForm), name='login'), path('register/', views.account_register, name='register'), path('dashboard/', views.dashboard, name='dashboard'), ] template <form class="account-form p-4 rounded" action="{% url 'account:login' %}" method="post"> {% csrf_token %} <h3 class="mb-4">Sign In</h3> {% if form.errors %} <div class="alert alert-primary" role="alert"> Error: Username or Password not correct! </div> {% endif %} <label class="form-label">{{ form.username.label}}</label> {{ form.username}} <label class="form-label">{{ form.password.label}}</label> {{ form.password}} <div class="d-grid gap-2"> <input type="hidden" name="next" value="{{ next }}"> <button class="btn btn-primary py-2 mb-4 mt-5 fw-bold" type="submit" value="Log-in">Sign in </button> </div> <p class="text-center pb-3"> <a href="{% url "account:register" %}">Create an account</a> </p> </form> I want someone to help me pinpoint the reason why I'm not redirected to this url specified in settings.py LOGIIN_REDIRECT_URL = '/account/dashboard' -
Python type annotation for list of potential return values
Can a Python function be annotated with a list of potential return values? RAINY = 'rainy' SUNNY = 'sunny' CLOUDY = 'cloudy' SNOWY = 'snowy' TYPES_OF_WEATHER = [RAINY, SUNNY, CLOUDY, SNOWY] def today_is_probably(season) -> OneOf[TYPES_OF_WEATHER]: if season is 'spring': return RAINY if season is 'summer': return SUNNY if season is 'autumn': return CLOUDY if season is 'winter': return SNOWY -
I got 500 server error whenever I try to sign in, sign up.... I think this is someting to do with google social account
I used to have 'https' but my web application went wrong so I had to get new ip address. so now same domain but different ip address. I tried to get 'https' for new ip address and got the new one but 'https' is not working. finally I got message from google cloud, OAuth consent screen on the credential page saying "Changing publishing status from 'Testing' to 'In Production' is restricted to projects using HTTPS URLs only." Now the login and signup by emails is not even working at all. just got server error 500. I went to google page and was told me to be here to ask quesitons and help -
Why am I not getting the Following Records on my page
I am building a followers System on my Django Blog Here is the model: class Followers(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) another_user = models.ManyToManyField(User, related_name='another_user') def __str__(self): return self.user.username Here is my view Method: def profile(request, user_name): user_obj = User.objects.get(username=user_name) session_user = User.objects.get(username=request.session['user']) session_following, create = Followers.objects.get_or_create(user=session_user) following, create = Followers.objects.get_or_create(user=session_user.id) check_user_followers = Followers.objects.filter(another_user=user_obj) is_followed = False if session_following.another_user.filter(username=user_name).exists() or following.another_user.filter(username=user_name).exists(): is_followed=True else: is_followed=False param = {'user_obj': user_obj,'followers':check_user_followers, 'following': following,'is_followed':is_followed} if 'user' in request.session: return render(request, 'users/profile2.html', param) else: return redirect('index') Here is my template: <h1>Followers</h1> <hr> {% if user_obj.username == request.session.user%} <h4>Name: {{user_obj.username}}</h4> <span>Followers: {{followers.count }}</span> <br> <span>Following: {{session_following.another_user.count }}</span> {% else %} <h4>Name: {{user_obj.username}}</h4> <span>Followers: {{followers.count }}</span> <br> <span>Following: {{user_following.another_user.count }}</span> <h4>Profile is Private.</h4> {% endif %} <br><br> {% if user_obj.username != request.session.user%} {% if is_followed %} <a href="{% url 'follow' user_obj.username %}" style="border: 1px solid; background: red; padding:10px; color: white;">Unfollow</a> {% else %} <a href="{% url 'follow' user_obj.username %}" style="border: 1px solid; background: yellow; padding:10px; color: black;">Follow</a> {% endif %} {% endif %} I am not getting the following count on my page I am using the code from following website:https://dev.to/madhubankhatri/follow-unfollow-system-using-django-simple-code-3785 -
Source Code Relation between class-based views and its Models
According to Django official URL, **## models.py** from django.db import models class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) ... **## views.py** from django.views.generic import ListView from books.models import Publisher class PublisherList(ListView): model = Publisher **## urls.py** from django.urls import path from books.views import PublisherList urlpatterns = [ path('publishers/', PublisherList.as_view()), ] In the template, a variable called object_list that contains all the publisher objects. {% extends "base.html" %} {% block content %} <h2>Publishers</h2> <ul> {% for publisher in object_list %} <li>{{ publisher.name }}</li> {% endfor %} </ul> {% endblock %} I have been deep diving into source code of django to find out exactly where Django explicitly put all objects of the Publisher Model into the template context (object_list). But no luck so far, Can anyone share some insights please? -
Optimize a Django query where it uses prefetch_related on a select_related
I'm trying to figure out how to optimize a Django query. I have an queryset that contains a foreign key to exercises. That table makes ManyToMany references to a number of other tables. If selecting exercises, I'd use prefetch_related to include them in the query, but I can't figure out how to do that in this case, since I'm doing it from a different table. Currently, it's being selected as super().get_queryset(request).select_related('exercise') But I can't figure out how to attach prefetch_related to that. Looking at SO, I found a solution that led me to this: return super().get_queryset(request).select_related( Prefetch( 'exercise', queryset=Exercise.objects.prefetch_related('equipments', 'inuries') ) ) But it fails with 'Prefetch' object has no attribute 'split', which I traced through the source, and it looks like select_related can't work with Prefetch. -
Need help making 1000's requests as fast as possible., python, django
I'm deep in the middle of coding a full web application in Django, but am venturing into new territory trying to send 1000's of API Trading Requests to an exchange as fast as possible. I want it so that each time it iterates through the loop ( each bot ), it sends the trading signal to the exchange, collects some data from the exchange and logs all the data in the databse. But since it has to wait each time it sends or receives data to/from the exchange, I am trying to figure out how to make the code asynchronus. So that it would get to each waiting point then start the next loop, and start sending the next signal. Then come back and finish collecting the data and saving it to the databse when it can. Because obviously if it has to wait each time on 1000's of bot's then it will take ages. I'm getting confused trying to figure it out online and wondered if someone could help/answer some things for me. I also wondered that since I'm trying to run the code async and the variable names are the same in each iteration of the loop, would … -
Django static files on AWS S3 Bucket
There are a bunch of questions similar to this one, but after going through some of them, I still can't get it right. I have a Django app and I want to serve static and media files using an AWS S3 Bucket. I can run python manage.py collectstatic and the files are added to the bucket. However, I am getting a 404 not found error for static files on the browser. There was a point in time that my configurations worked because I was able to see the files coming from s3 by inspecting the page, but I can't find what was changed for it not to work now. Here's my settings.py: USES_S3 = os.getenv('USES_S3') == 'True' if USES_S3: AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME') AWS_DEFAULT_ACL = 'public-read' AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=31536000'} AWS_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = 'core.storage_backends.StaticStorage' PUBLIC_MEDIA_LOCATION = 'media' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/' DEFAULT_FILE_STORAGE = 'core.storage_backends.MediaStorage' else: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(CORE_DIR, 'staticfiles') MEDIA_URL = '/mediafiles/' MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles') STATICFILES_DIRS = ( os.path.join(CORE_DIR, 'core/static'), ) storages_backend.py: from django.conf import settings from storages.backends.s3boto3 import S3Boto3Storage class MediaStorage(S3Boto3Storage): location = 'media' default_acl = 'public-read' file_overwrite = False class StaticStorage(S3Boto3Storage): location … -
Adding data to DB via Django Admin panel
I have a new Django project using Python 3.7 and Django 1.8 I’ve made a model, migration, superuser account. But admin panel won’t work when I’m trying to add anything in it. Why this error occurs and how to fix it? Error screenshot -
Django Retrieving data as 5 members groups
when retrieving objects in Django I want it to be divided into a group like for example get all products and the result should be 4 groups each group have 5 objects I don't mean to group by property just random groups each group have five members for example when retrieving products = Product.objects.all() i want the result to be product = [ [ {id:1, price:3}, {id:2, price:3}, {id:5, price:3}], {id:6, price:3}, {id:10, price:3}, {id:1, price:3}], {id:19, price:3}, {id:1, price:3}, {id:1, price:3}] ], so i want to like to get the query a number for example 3 so that it gives me group with 3 members in each -
Django + Bootstrap + Ajax form POSTing a ForeignKey?
I am having trouble with a bootstrap popup modal, and associating a ForeignKey to a POST request. I have a simple Add Note Button, and empty modal which is where the form data will be rendered. In the modal, I have an empty input field which grabs a database object, which will be the ForeignKey in my django view. <div class="container-fluid main-container"> <div class="text-center"> <button type="button" class="btn btn-danger js-create">Add Note</button> </div> </div> <div class="modal fade" id="modal-event"> <input type="hidden" id="eventID" name="event_id" value="{{ event_id }}"> <div class="modal-dialog"> <div class="modal-content"> </div> </div> and the form is as follows... <form method="post" action="{% url 'add_note' %}"> {% csrf_token %} <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h4 class="modal-title">Add Note</h4> </div> <div class="modal-body"> {% for field in form %} <div class="form-group{% if field.errors %} has-error{% endif %}"> <label for="{{ field.id_for_label }}">{{ field.label }}</label> {% render_field field class="form-control" %} {% for error in field.errors %} <p class="help-block">{{ error }}</p> {% endfor %} </div> {% endfor %} </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Save</button> </div> </form> This is the JS function that opens up the modal... $(function () { $(".js-create").click(function () { let event_id = $("input[name='event_id']").val(); console.log(event_id); // Logs the … -
Assign color to text in website based on ID in database
In my forums website, I want to assign a certain color to each role. For example the admin color is blue, so the username of this admin is always blue. In my database, I'm using MySQL, I have a role table that assigns an ID for each role and a users table linked to the role table. How can I assign the color I want to the role ID that I want? Note: I'm using Django for my back-end work Thank you. -
502 Bad Gateway on My Django Site when I click on A link to send message to all users
When clicked on the send sponsored message the site keeps on loading and after some time shows an error - 502 Bad Gateway. I have tried running the site on my localhost but the error does not come I think because my localhost does not contain a big database like the server. The view function called on click - #Send sponsored messages via Commondove user @login_required @user_passes_test(is_staff) @permission_required('send_sponsored_message') def sendSponsoredMessage(request): dictV = {} fromUser = get_object_or_404(UserModel, authUser = request.user) dictV['users'] = UserModel.objects.all().order_by('name') dictV['colleges'] = College.objects.all().order_by('collegeName') dictV['organizations'] = SocialOrganization.objects.all().order_by('organizationName') if request.method == 'POST': allDevices = [] allUserModelObjects = [] heading = request.POST.get('heading') text = request.POST.get('message') userPks = request.POST.getlist('users') image = request.FILES.get('image') if not text and not image: dictV['error'] = 'Message and Image both cannot be empty' else: #Call sendSponsoredMessageHelper with devices of all users sendSponsoredMessageHelper(text, image, userPks, fromUser) dictV['success'] = True return render(request, 'sendSponsoredMessage.html',dictV) sendSponsoredMessageHelper function mentioned above - #Send a sponsored message from dashboard def sendSponsoredMessageHelper(text, image, userPks, fromUser): userModelObjects = UserModel.objects.filter(pk__in = userPks) for user in userModelObjects: Message.objects.create(fromUser = fromUser, toUser = user, message = text, image = image, sponsored = True) #Send notification heading = fromUser.name authUserPks = [ x.authUser.pk for x in userModelObjects ] allDevices = GCMDevice.objects.filter(user__pk__in … -
Connecting to Postgres running on Windows from django running on WSL
I primarily develop on windows but I'm testing my app using WSL since I will push it to a linux server. My current issue is connecting the django app, running on WSL to postgres, running on windows. Many articles explain how to connect to postgres running on WSL but not the other way round. -
How to solve the translation/localisation of JavaScript external files since Django does not allow built-it tags in other files?
I was looking in other questions. I know that Django allows to use built-in tags in the internal JavaScript code on HTML page, but it is a bad practice that a professional developer would not do; I know that Django does not allow to use built-in tags in the external JavaScript files. Differently of it, Go Hugo allows. I considered the question Django translations in Javascript files, but I do not know if it is a bad practice to generate the JavaScript with the same name but with with different language abbreviation, as table-en.js, table-fr.js, table-pt-br.js, table-pt-pt.js, etc. The small code, for example: var preTtitle = 'List of colours and icon in'; const styles = [ { name: 'adwaita-plus', title: ' ' + preTtitle + 'Adwaita++' }, { name: 'suru-plus', title: ' ' + preTtitle + 'Suru++' }, { name: 'suru-plus-ubuntu', title: ' ' + preTtitle + 'Ubuntu++' }, { name: 'yaru-plus', title: ' ' + preTtitle + 'Yaru++' } ]; I also need to translate the table columns: firstHeader.textContent = 'Name of colour'; secondHeader.textContent = 'Preview of icons'; trHeader.appendChild(firstHeader); trHeader.appendChild(secondHeader); thead.appendChild(trHeader); I want to translate 'List of colours and icon in', 'Name of colour' and 'Preview of icons'. As … -
503 Service Temporarily Unavailable using Kubernetes
I am having some issue with creating ingress for a nginx service that I deployed in a kubernetes cluster. I am able to open the web page using port forwarding, so I think the service should work.The issue might be with configuring the ingress.I checked for selector, different ports, but still could not find where goes wrong. Anyone could help ? Thank you in advance. # Source: django/templates/configmap.yaml apiVersion: v1 kind: ConfigMap metadata: name: vehement-horse-django-config labels: app.kubernetes.io/name: django helm.sh/chart: django-0.0.1 app.kubernetes.io/instance: vehement-horse app.kubernetes.io/managed-by: Tiller enter code here data: --- # Source: django/templates/service.yaml apiVersion: v1 kind: Service metadata: name: vehement-horse-django labels: app.kubernetes.io/name: django helm.sh/chart: django-0.0.1 app.kubernetes.io/instance: vehement-horse app.kubernetes.io/managed-by: Tiller spec: type: ClusterIP ports: - port: 80 targetPort: 8080 protocol: TCP name: selector: app.kubernetes.io/name: django app.kubernetes.io/instance: vehement-horse --- # Source: django/templates/deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: vehement-horse-django labels: app.kubernetes.io/name: django helm.sh/chart: django-0.0.1 app.kubernetes.io/instance: vehement-horse app.kubernetes.io/managed-by: Tiller spec: replicas: selector: matchLabels: app.kubernetes.io/name: django app.kubernetes.io/instance: vehement-horse template: metadata: labels: app.kubernetes.io/name: django app.kubernetes.io/instance: vehement-horse spec: containers: - name: django image: "website:72cf09525f2da01706cdb4c6131e8bf1802ea6a3" imagePullPolicy: Always envFrom: - configMapRef: name: vehement-horse-django-config ports: - name: http containerPort: 8080 protocol: TCP resources: limits: cpu: 1 memory: 1Gi requests: cpu: 1 memory: 512Mi imagePullSecrets: - name: some-secret --- # Source: … -
"django.db.utils.OperationalError: no such table" when adding in new app
I recently added the mycase app to my larger django project but since then I have been getting all kinds of database errors. If any more information would be helpful just reply with a comment, I don't know exactly what would be helpful in this case. Thanks! Traceback: File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/opt/anaconda3/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/opt/anaconda3/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/anaconda3/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/opt/anaconda3/lib/python3.8/site-packages/django/core/management/base.py", line 368, in execute self.check() File "/opt/anaconda3/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = checks.run_checks( File "/opt/anaconda3/lib/python3.8/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/opt/anaconda3/lib/python3.8/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/opt/anaconda3/lib/python3.8/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/opt/anaconda3/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/opt/anaconda3/lib/python3.8/site-packages/django/urls/resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/opt/anaconda3/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/opt/anaconda3/lib/python3.8/site-packages/django/urls/resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "/opt/anaconda3/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, … -
The empty path didn’t match any of these. Django
I'm a total beginer at Django. Please help me to solve it, I've been trying to do so for 2 days. Essentially I created a model, defined a class there but when I open the page I get the error Using the URLconf defined in reports_proj.urls, Django tried these URL patterns, in this order: admin/ ^static/(?P<path>.*)$ ^media/(?P<path>.*)$ The empty path didn’t match any of these. urls.py 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('admin/', admin.site.urls), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) admin.py from django.contrib import admin from .models import Profile admin.site.register(Profile) settigs.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #our apps 'customers', 'products', 'profiles', 'reports', 'sales', #3rd party 'crispy_forms' ] When I put path('login/', admin.site.urls), it works but shows me Please enter the correct username and password for a staff account. whenever I try to log in as admin. It seems like I should write some methods in views.py, because it has only from django.shortcuts import render line. If it's true, which ones? -
how to create Django preferences (Site dashboard)
Hi I have ready Django project and I want to create a control panel for it, for example I want to add a field with the name of the site, a field with a description of the site, and a field with the logo of the site, and I call them in the templates instead of changing them manually through the editor every time. I upload the website logo to the static file and want to add an option to change it from the control panel instead of manually replacing it from the server. I have attached an illustration of what I want to reach. Thank you -
DJANGO - Admin Action
I'd like to create a website with for car dealer with admin and allow dealers to add, edit, delete car. My problem is that on Django Admin, when I login with any account I see all the cars and I'd like to show only cars attched to connected dealer. I create a model from django.db import models from django.contrib.auth.models import User import datetime from brand.models import Brands from django.urls import reverse class Car(models.Model): dealer = models.ForeignKey(User, on_delete=models.DO_NOTHING) brand = models.ForeignKey(Brands, on_delete=models.DO_NOTHING) carname = models.CharField(max_length=100) def __str__(self): return '%s %s' % (self.brand, self.carname) Also, when I create a car the dealer's list show all dealers in database, but me I'd like to display only connected account name. Thanks for your help