Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add link previews in django?
I'm doing a chat app in python Django and I Want to implement Link preview while typing that ink in chat box. Anybody familiar with this please help. -
Django - is_valid returns false for authentication built-in login form
Can anyone figure out why when I fill out the form it returns False for is_valid? forms.py class LoginForm(AuthenticationForm): class Meta: model = User fields = '__all__' views.py class LoginView(FormView): form_class = LoginForm template_name = 'login.html' def post(self, request, *args, **kwargs): form = LoginForm(self.request.POST) if form.is_valid(): return HttpResponse('valid') else: return HttpResponse('not valid') login.html <form action "" method = "POST"> {% csrf_token %} {{form|materializecss}} <button type = "submit">Login</button> </form> As an extra, the following change to views.py returns the username and password so I know it has been passed to the POST request: class LoginView(FormView): form_class = LoginForm template_name = 'login.html' def post(self, request, *args, **kwargs): form = LoginForm(self.request.POST) return HttpResponse (self.request.POST.get('username')+ ' ' +self.request.POST.get('password')) -
413 Error in django and nginx image on Docker Container
I'm doing on small project for web clothing flea market. My project was built with django DRF (backend) and React JS (frontend). To deploy it, I made the docker image of my project and pull it with other images like nginx, letsencrypt-nginx-proxy, and docker-gen image in cloud platform server which has centos7. (please see the figures I attached) Based on my other services, there are no problem for uploading image files regardless of the file size but, In this service, I cannot upload image files above 1mb. below one is my docker-compose.yml in /home/docker directory on cloud server. [root@flea docker]# cat docker-compose.yml version: '3' services: nginx-web: image: nginx labels: com.github.jrcs.letsencrypt_nginx_proxy_companion.nginx_proxy: "true" container_name: ${NGINX_WEB:-nginx-web} restart: always ports: - "${IP:-0.0.0.0}:${DOCKER_HTTP:-80}:80" - "${IP:-0.0.0.0}:${DOCKER_HTTPS:-443}:443" volumes: - ${NGINX_FILES_PATH:-./data}/conf.d:/etc/nginx/conf.d - ${NGINX_FILES_PATH:-./data}/vhost.d:/etc/nginx/vhost.d - ${NGINX_FILES_PATH:-./data}/html:/usr/share/nginx/html - ${NGINX_FILES_PATH:-./data}/certs:/etc/nginx/certs:ro - ${NGINX_FILES_PATH:-./data}/htpasswd:/etc/nginx/htpasswd:ro logging: driver: ${NGINX_WEB_LOG_DRIVER:-json-file} options: max-size: ${NGINX_WEB_LOG_MAX_SIZE:-4m} max-file: ${NGINX_WEB_LOG_MAX_FILE:-10} nginx-gen: image: jwilder/docker-gen command: -notify-sighup ${NGINX_WEB:-nginx-web} -watch -wait 5s:30s /etc/docker-gen/templates/nginx.tmpl /etc/nginx/conf.d/default.conf container_name: ${DOCKER_GEN:-nginx-gen} restart: always environment: SSL_POLICY: ${SSL_POLICY:-Mozilla-Intermediate} volumes: - ${NGINX_FILES_PATH:-./data}/conf.d:/etc/nginx/conf.d - ${NGINX_FILES_PATH:-./data}/vhost.d:/etc/nginx/vhost.d - ${NGINX_FILES_PATH:-./data}/html:/usr/share/nginx/html - ${NGINX_FILES_PATH:-./data}/certs:/etc/nginx/certs:ro - ${NGINX_FILES_PATH:-./data}/htpasswd:/etc/nginx/htpasswd:ro - /var/run/docker.sock:/tmp/docker.sock:ro - ./nginx.tmpl:/etc/docker-gen/templates/nginx.tmpl:ro logging: driver: ${NGINX_GEN_LOG_DRIVER:-json-file} options: max-size: ${NGINX_GEN_LOG_MAX_SIZE:-2m} max-file: ${NGINX_GEN_LOG_MAX_FILE:-10} nginx-letsencrypt: image: jrcs/letsencrypt-nginx-proxy-companion container_name: ${LETS_ENCRYPT:-nginx-letsencrypt} restart: always volumes: - ${NGINX_FILES_PATH:-./data}/conf.d:/etc/nginx/conf.d - ${NGINX_FILES_PATH:-./data}/vhost.d:/etc/nginx/vhost.d - ${NGINX_FILES_PATH:-./data}/html:/usr/share/nginx/html - ${NGINX_FILES_PATH:-./data}/certs:/etc/nginx/certs:rw - /var/run/docker.sock:/var/run/docker.sock:ro environment: NGINX_DOCKER_GEN_CONTAINER: … -
Add User Functionality at custom admin side - Django
I am working on a project in Python Djnago 3.1.2, and developing a custom admin side, where admin can perform different functionalities. At the admin site I want to add functionality to add user and I have created a function but there is some error but I could not get it. Here is My models. models.py class User(AbstractUser): GENDER = ( (True, 'Male'), (False, 'Female'), ) USER_TYPE = ( ('Admin', 'Admin'), ('Designer', 'Designer'), ('Customer', 'Customer'), ) user_id = models.AutoField("User ID", primary_key=True, auto_created=True) avatar = models.ImageField("User Avatar", null=True, blank=True) gender = models.BooleanField("Gender", choices=GENDER, default=True) role = models.CharField("User Type", max_length=10, choices=USER_TYPE, default='Customer') def __str__(self): return "{}".format(self.user_id) This is the function I have created and I think error is in my views. views.py def addUser(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('/admin1/addUser') else: addUser_show = User.objects.all() # start paginator logic paginator = Paginator(addUser_show, 3) page = request.GET.get('page') try: addUser_show = paginator.page(page) except PageNotAnInteger: addUser_show = paginator.page(1) except EmptyPage: addUser_show = paginator.page(paginator.num_pages) # end paginator logic return render(request, 'admin1/addUser.html', {'addUser_show': addUser_show, "form":form}) urls.py path('addUser/', views.addUser, name="admin-add-user"), Form I am using to get the create user form. forms.py class CreateUserForm(UserCreationForm): class Meta: model = User fields … -
Where can i execute celery commands after deploying a django application on google app engine standard environment
I am a django developer. One of my clients asked me to deploy the application on google app engine standard environment. I am new to this approach. Redis is used as a task broker for celery in my application. As i have learnt there is no cli for GAE, so where can i run commands such as celery -A project worker --loglevel=info celery -A project beat -
Django DB Design and API Guidance
This is my first Django app, and also my first time building an app, and I am seeking some DB and API guidance. I have an app that functions as an online directory and marketplace. What I aim to do is to provide the app to many different organizations such that the organizations have their own online directory's and marketplace's where they can manage it fully on their own, but that their data is still linked to my database so that I can then operate on the data for machine learning purposes. This is a pretty standard/routine practice, I realize, but I am trying to wrap my head around how best to make it work. For each organization, would there just be an instance of the app which would then be a separate app or interface that connects to the original? From my newbie understanding, that is essentially what an API is, correct? -
Python Django Graphql all possible query variant generation
Is there a tool that would generate all possible query variants based on a Django Graphql based project source code? I am evaluating a product with limited documentation and I am wondering if there is something that could help me to automate the discovery process. -
Django and modifying models to reflect a specific ERD
I have the following Django Model: from django.db import models from django.utils.text import slugify class Project(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True, blank=True) budget = models.IntegerField() def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Project, self).save(*args, **kwargs) @property def budget_left(self): expense_list = Expense.objects.filter(project=self) total_expense_amount = 0 for expense in expense_list: total_expense_amount += expense.amount # temporary solution, because the form currently only allows integer amounts total_expense_amount = int(total_expense_amount) return self.budget - total_expense_amount @property def total_transactions(self): expense_list = Expense.objects.filter(project=self) return len(expense_list) class Category(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) name = models.CharField(max_length=50) def __str__(self): return self.name class Expense(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='expenses') title = models.CharField(max_length=100) amount = models.DecimalField(max_digits=8, decimal_places=2) category = models.ForeignKey(Category, on_delete=models.CASCADE) class Meta: ordering = ('-amount',) I don't like the current setup, it seems to unnecessarily bind and expense category to a project, instead of to a given expense. So, I want to start working towards the following ERD, starting with the category side of things: When I try to modify the models so that category is no longer a Foreign key of Project: class Category(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name but rather expense, I get the following error: category_list = Category.objects.filter(project=project) This comes out … -
Preventing Users from reaching developer tools > Sources in Chrome for a Django Project
I have deployed a Django project for production but now I am found that the media files are reachable when I select Inspect the page and go to Sources I can see all the Static Files and Media what should I do to prevent reaching them. Noting that in my project settings: if DEBUG: STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] else: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' #STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static' )] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') My question: How to prevent reaching the static files and media files in my project for anyone from the browser? -
DatabaseError: value too long for type character varying(20)
I am not sure why i get a varying(20) error even when the max_length I've set is 200 for a CharField I looked at all the other posts and all of them had an issue with the length of the value. However, even if i enter "abc" in the name field it gives me this error. Any help is appreciated. Thanks! Django Version: 3.1.5 Python Version: 3.8.5 from django.db import models from django.contrib.gis.db import models from django.db.models import Manager as GeoManager # Create your models here. class Incidences(models.Model): name = models.CharField(max_length=200) location = models.PointField(srid=4326) objects = GeoManager() def _str_(self): return self.name Traceback (most recent call last): File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) The above exception (value too long for type character varying(20) ) was the direct cause of the following exception: File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\contrib\admin\options.py", line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\contrib\admin\sites.py", line 233, in inner return view(request, *args, **kwargs) File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\contrib\admin\options.py", line 1653, in … -
css on the relevant position of two components
I am super new to css, so apologize if the question is stupid. I have two components on a page, one is called .sub-list , which is a side bar that contains the names of all the groups available, the other main component is post-list, which has all the posts listing. I am really confused about all the positions option outhere. I've tried aboslute position for the two components and relative positions, but with screen decrease or increase, the display just completely falls apart. Here is the base.html: {% load static %} <html> <head> <meta content="width=device-width, initial-scale=1" name="viewport" /> <title>Nat's flower</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="{% static 'css/reddit.css' %}"> </head> <body> <div class="page-header"> <h1><a href="/">Nat's Flower</a></h1> {% if user.is_authenticated %} <!--<a href="{% url 'post_new' %}" class="top-menu"><span class="glyphicon glyphicon-plus"></span></a> <a href="{% url 'subreddit_new' %}" class="top-menu"><span class="glyphicon glyphicon-plus"></span></a>--> <!--<a href="{% url 'logout' %}" class="top-menu">{{ user.username }} Sign Out</a>--> <a href="{% url 'post_new' %}" class="top-menu">New Post</a> <a href="{% url 'subreddit_new' %}" class="top-menu">New Group</a> <a href="{% url 'logout' %}" class="top-menu"><span class="glyphicon glyphicon-off"></span></a> {% else %} <a href="{% url 'login' %}" class="top-menu"><span class="glyphicon glyphicon-lock"></span></a> {% endif %} </div> <div class="content-container"> <div class="row"> <div class="col-md-8"> {% block content %} {% endblock %} … -
Custom functions in __init__.py cause Django Apps Aren't Installed Yet Error
I have a setup like the following Tasks |__ __init__.py |__ a.py |__ b.py |__ c.py ... Inside the __init__.py file, from .a import custom1, custom2 from .b import custom3, custom4 I wrote a function within Tasks which requires Tasks to be added as an INSTALLED_APP. The custom functions however raise django.core.exceptions.AppRegistryNotReady: "Apps aren't loaded yet.". Why does this happen, and is there a way to fix this error WITHOUT moving the custom functions out of the init.py file? -
Django dynamically display a list but ignore some items
I am trying to show a list of groups on the sidebar on my html using Django. The first item will always be "all". so when I tranverse through all the groups/subreddits, I would first display "all" and then display the rest. however, when I display the rest and when it hits "all" again, instead of doing nothing, it seems to be printing a empty line because later when I display it in forms, I notice that I have a blank cell. I wonder how do I make sure that it just ignores "all" and goes on to display the next group without the empty space. Here is the code: <div class="post" id="title"><h4>Groups </h4></div> {% for sub in subreddits %} {% if sub.name == 'all' %} <div class="post"> <a href="{% url 'sub_detail' pk=sub.pk %}">{{ sub.name }}</a></div> {% endif %} {% endfor %} {% for sub in subreddits %} <div class="post"> {% if sub.name != 'all' %} <a href="{% url 'sub_detail' pk=sub.pk %}">{{ sub.name }}</a> {% endif %} </div> {% endfor %} -
Django Rest Framework action when request comes in
I'm creating a Django project that uses Django REST Framework for the API. Other projects will be making POST, PUT, and DELETE requests to this project. When one of those requests comes in, I want to send a message to a websocket group using channels. For some reason I am struggling to do this. I am using ThreadViewSet, which extends ModelViewSet, for a model named Thread. class ThreadViewSet(ModelViewSet): queryset = Thread.objects.all() serializer_class = ThreadSerializer I have tried adding the channels call to this class but it doesn't seem to be run: class ThreadViewSet(ModelViewSet): queryset = Thread.objects.all() serializer_class = ThreadSerializer channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)("group", {'type': 'new_message', 'message': "New Thread"}) The next thing I tried was overriding create(), update(), and destroy() and this worked, but it seemed like so much work for one simple task. Am I missing something? There has to be an easier way to do this. -
Django how to load statics inside a python file
I'm trying to load a an image from static to a from element I tried to load it inside my forms.py as a style attribute widget=forms.Select(attrs={ 'style': 'background: url("{% static \'/img/Arrow_bottom.png\' %}") 2rem / 2rem no-repeat #eee;' }) but it's interpreted in the browser as a text "background: url("{% static '/img/Arrow_bottom.png' %}") I want "background: url("static_dir/img/Arrow_bottom.png") how can I load statics to my forms.py file or to the css file -
Using Vue with Django: How to separate publicPath from static file prefix
I'm trying to convert my existing and sprawling Django project, which currently uses Vue from a CDN in individual pages on the frontend, to an SPA via NPM with the backend and frontend now separate (except for Django handling some URL routes and loading the Vue initially). I'm running into a problem with static files and URL routing. In vue.config.js, I was originally advised to set values as follows: const pages = { index: "src/main.js" }; module.exports = { runtimeCompiler: true, publicPath: "/static/vue/", outputDir: "./dist/static/vue/", indexPath: "../../templates/vue_index.html", pages: pages }; so that when combined with the way Django looks for static files: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'frontend/dist/templates')], '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', ], }, }, ] STATICFILES_DIRS = [os.path.join(BASE_DIR, 'frontend/dist/static')] STATIC_URL = '/static/' the page will be able to load. Unfortunately, if I try to load the page, rather than loading at the website root /, it loads at /static/vue/ (i.e. localhost:8000/static/vue/). If I try to directly access localhost:8000, it immediately redirects to localhost:8000/static/vue/, which I suppose is vue-router's doing. Django is able to find the Vue entry point template just fine, but it seems to need publicPath: "/static/vue/" in order … -
Celery tasks running every 20 seconds is overlapping and starting before the last can finish
I have a celery task running every 20 seconds. The problem is handler is firing off twice sometimes the tasks overlap. Seems like the filtered items are not updating while the tasks overlap: @periodic_task(run_every=timedelta(seconds=20)) def process_webhook_transactions(): """Process webhook transactions""" transactions = WebhookTransaction.objects.filter(status=WebhookTransaction.UNPROCESSED) for transaction in transactions: data = transaction.body event = data.get('event_category') if event is None: transaction.status = WebhookTransaction.ERROR transaction.save() continue handler = WEBHOOK_HANDLERS.get(event, default_handler) success = handler(data) if success: transaction.status = WebhookTransaction.PROCESSED else: transaction.status = WebhookTransaction.ERROR transaction.save() What is the best way to avoid this? -
Many to Many Field en Django
soy nueva trabajando con Django. Tengo un campo ManytoMany y al hacer el post desde la App, en algunas ocasiones no va ese dato porque no tiene asociada esa clave foranea. Mi pregunta es ¿Hay forma de permitir que el Django reciba ese dato en None? He probado con blank=True y siempre sale el error que esa clave primaria no existe ¿Alguna sugerencia? -
Create django model with as many fields as an integer in other field
I have the following model in django class params(models.Model): name = models.CharField(max_length=30, default = 'no_name') cs_n = models.IntegerField(default=16) alt_n = models.IntegerField(default=2) opt_out = models.BooleanField(default=1) at_n = models.IntegerField(default=4) I want to create a new model with as many fields as at_n. For example, if the user enter "4" in at_n, I want this to create automatically: class params(models.Model): at_1 = models.IntegerField(default=2) at_2 = models.IntegerField(default=2) at_3 = models.IntegerField(default=2) at_4 = models.IntegerField(default=2) Thanks -
I can't get AWS S3 to serve media files on my Django/Heroku App
Been stuck on this for a while. In my django site's admin page, I can upload a photo along with my blog post. The photo will appear in my S3 bucket, but the photo won't render on the blog post. Just a little photo icon. Followed the simpleisbetterthancomplex tutorial, and have read through every relevant stackoverflow question I can find. Can anyone see what it is that I'm missing? Thanks. Here is my settings.py: AWS_ACCESS_KEY_ID = '**********' AWS_SECRET_ACCESS_KEY = '*********' AWS_STORAGE_BUCKET_NAME = 'matt-george-portfolio' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_LOCATION = 'static' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_URL = '/static/' MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) import django_heroku django_heroku.settings(locals()) I added this to my AWS S3 permissions: [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "GET", "PUT", "POST", "HEAD", "DELETE" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [], "MaxAgeSeconds": 3000 } ] -
Im new in django I'm using gitpod workspace and trying to set up an authentication system with django-allauth
Im trying to set up an authentication system with django-allauth and to customize the allauth login templates I need to make copies of them in my own templates/allauth directory, I'm using gitpod. this is the command I'm using to copy cp -r ../.pip.modules/lib/python3.8/site-packages/allauth/templates/* ./templates/allauth/ but Im getting this error message cp: cannot stat '../.pip.modules/lib/python3.8/site-packages/allauth/templates/*': No such file or directory this are the installed apps in setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', ] -
I am facing issue while writing records to google cloud postgresql using apace beam and beam-nuggets
TypeError: expected bytes, str found [while running 'Writing to DB/ParDo(_WriteToRelationalDBFn)-ptransform-186378'] Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/apache_beam/runners/worker/sdk_worker.py", line 289, in _execute response = task() File "/usr/local/lib/python3.7/site-packages/apache_beam/runners/worker/sdk_worker.py", line 362, in lambda: self.create_worker().do_instruction(request), request) File "/usr/local/lib/python3.7/site-packages/apache_beam/runners/worker/sdk_worker.py", line 607, in do_instruction getattr(request, request_type), request.instruction_id) File "/usr/local/lib/python3.7/site-packages/apache_beam/runners/worker/sdk_worker.py", line 644, in process_bundle bundle_processor.process_bundle(instruction_id)) File "/usr/local/lib/python3.7/site-packages/apache_beam/runners/worker/bundle_processor.py", line 957, in process_bundle op.start() File "apache_beam/runners/worker/operations.py", line 710, in apache_beam.runners.worker.operations.DoOperation.start File "apache_beam/runners/worker/operations.py", line 712, in apache_beam.runners.worker.operations.DoOperation.start File "apache_beam/runners/worker/operations.py", line 714, in apache_beam.runners.worker.operations.DoOperation.start File "apache_beam/runners/common.py", line 1290, in apache_beam.runners.common.DoFnRunner.start File "apache_beam/runners/common.py", line 1275, in apache_beam.runners.common.DoFnRunner._invoke_bundle_method File "apache_beam/runners/common.py", line 1321, in apache_beam.runners.common.DoFnRunner._reraise_augmented File "/usr/local/lib/python3.7/site-packages/future/utils/init.py", line 446, in raise_with_traceback raise exc.with_traceback(traceback) File "apache_beam/runners/common.py", line 1273, in apache_beam.runners.common.DoFnRunner._invoke_bundle_method File "apache_beam/runners/common.py", line 518, in apache_beam.runners.common.DoFnInvoker.invoke_start_bundle File "apache_beam/runners/common.py", line 524, in apache_beam.runners.common.DoFnInvoker.invoke_start_bundle File "/usr/local/lib/python3.7/site-packages/beam_nuggets/io/relational_db.py", line 178, in start_bundle self._db.start_session() File "/usr/local/lib/python3.7/site-packages/beam_nuggets/io/relational_db_api.py", line 255, in start_session if create_if_missing and is_database_missing(): File "/usr/local/lib/python3.7/site-packages/beam_nuggets/io/relational_db_api.py", line 254, in is_database_missing = lambda: not database_exists(self._source.url) File "/usr/local/lib/python3.7/site-packages/sqlalchemy_utils/functions/database.py", line 481, in database_exists return bool(get_scalar_result(engine, text)) File "/usr/local/lib/python3.7/site-packages/sqlalchemy_utils/functions/database.py", line 455, in get_scalar_result result_proxy = engine.execute(sql) File "/usr/local/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2234, in execute connection = self._contextual_connect(close_with_result=True) File "/usr/local/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2302, in _contextual_connect self._wrap_pool_connect(self.pool.connect, None), File "/usr/local/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2336, in _wrap_pool_connect return fn() File "/usr/local/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 364, in connect return _ConnectionFairy._checkout(self) File "/usr/local/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 778, in … -
i work django and me working on entering the display screen control admin but cannot access to get page admin
i work django and me working on entering the display screen control admin but cannot access to get page admin Blank information is displayed on the request path to: http://127.0.0.1:8000/admin/login/?next=codeviaew/admin/ This problem occurs when I am working on a fake environment Pipfile inside Pipfile: [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] django = "*" django-crispy-forms = "*" pillow = "*" [dev-packages] [requires] python_version = "3.8" I deleted the database, recreated it and created a user, but the problem still exists -
i want to host django server by apache server but a saw the admin/index.html template doesn't exist?
enter image description here [1]enter image description here: https://i.stack.imgur.com/NfKkp.png -
Unexpected error: replace() takes 2 positional arguments but 3 were given
In settings.py I have: BASE_DIR = Path(__file__).resolve().parent.parent Then In some view: from django.http import HttpResponse from django.conf import settings def(request): return HttpResponse( settings.BASE_DIR.replace("src", "") ) This gives error: replace() takes 2 positional arguments but 3 were given Bit confused because if do: return HttpResponse( settings.BASE_DIR ) this returns full path, something like: /home/full/path/to/project/src also this works return HttpResponse( "/home/full/path/to/project/src".replace("src", "") ) Can you help me and tell what is wrong with this line: return HttpResponse( settings.BASE_DIR.replace("src", "") ) ?