Yesterday I switched to Ubuntu 24.04 LTS from windows and having an issue with my django project and tried every suggestion on the web but no luck. I'm getting below issue: django.core.exceptions.ImproperlyConfigured: 'django.db.backends.postgresql' isn't an available database backend or couldn't …
У меня есть функция добавляющая данные в localstorage ключ: cart; поля: name, price, image, quantity и есть страница с оформлением заказа: пользователь заполняет форму где указывает имя, фамилию, номер телефона и адрес электронной почты. Я хочу чтобы после нажатия кнопки …
My django application receives data from an API. It's very unlikely the API will send incorrect information, but I am trying to cover the possibility the API may send data that would return ObjectDoesNotExist from malicious attempts. Below is my …
I have started to learn Python, then Django in practice by way of executing tutorial codes in Python IDLE. Indeed as maybe the code is of old versions the code running not always works well. Especially I am stacked upon …
I create a library to get backup to Google Drive using with Google Drive api in python. Actually its work well but when I use with celery my library, celery do not wait for compress my media folder(I guess). Its …
I have a m-2-m rel and i want to update the rel B after any rel A is added via the admin page. Here the details: I have 2 models, Match (rel A) and Player (rel B). I want to …
I am currently working on a django project which I deployed to a digitalocean droplet with nginx. The website works, including the staticfiles. After looking at my error.log i saw that it was a permission problem: 2024/04/27 18:58:19 [error] 130139#130139: …
From django.test import TestCase class DefTests(TestCase): def setUp(self): # first made the label UserType(label="mylabel").save() ## UserType is model object, and I made the first row , the id is supposed to be 1 def test_my(self): u = UserType.objects.get(id=1) # UserType.DoesNotExis …
I have one view with my basics config class base_view(LoginRequiredMixin, PermissionRequiredMixin): filter_backends = [SearchFilter] pagination_class = generic_pagination permission_required = '' # assigned at each final view (children) raise_exception = True # avoid redirecting to backend login fields = '__all__'# by …
I customized AppConfig in django to start some processes needed for the main application as described in the django documentation. In the usual initialization process, the ready method is only called once by Django. But in some corner cases, …
It takes a while to load all the data into the new df_with_ṕredictions, my problem is how can I render the new table with those predictions in a template : def home(request): df = None df_with_predictions = None …
If you enable the cache: @cache_page(20, key_prefix='index_page') def index(request): post_list = Post.objects.order_by('-pub_date').all() paginator = Paginator(post_list, 10) page_number = request.GET.get('page') page = paginator.get_page(page_number) return render(request, "index.html", {'page': page, 'paginator': paginator}) When I create a new post, I can no longer …
I am not able to migrate my changes. when i run python manage.py runserver - Full Traceback Traceback (most recent call last): File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\manage.py", line 22, in main() File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\env\Lib\site-packages\django\core\management_init_.py", line 442, in …
I'm working on a project using Django. I imported HTML files and created a Base HTML. I placed CSS and images in a folder named 'static' and imported them, but the CSS is not appearing on the site, only the …
I have a simple form with two HiddenInputs. Submitted form does not save initial values for hidden fields. What am I missing? forms.py class TestForm(forms.Form): foo = forms.CharField(required=False, initial="Foo") bar = forms.CharField(required=False, initial="Bar", widget=forms.HiddenInput()) is_true = forms.BooleanField(required=False, initial=True, widget=forms.HiddenInput()) …
I am facing an issue while deploying my Django app on apache2 sever. Project ID is required to access Cloud Messaging service. Either set the projectId option, or use service account credentials. Alternatively, set the GOOGLE_CLOUD_PROJECT environment variable. I have …
Im trying to create a view where we create an order through razorpay, but continuously getting 401 error despite the keyId and KeySecret being correct. Even postman and curl gives the same error. I have tried removing the authentication, adding …
I'm trying to load my home page according to the geolocation given by the browser, if the coordinates are ok, I load a list of airports around these coordinates, otherwise I load all airports. However, I can't manage this between …
I have setup a backend JWT authentication system using django, dj-rest-auth and simpleJWT. Currently, the dj-rest-auth is setting default JWT in the response cookies. To use custom cookies, I have to use simpleJWT's /token and /token/refresh urls. So, while testing …
STATIC_URL = '/static/' STATICFILES_DIRS = ((os.path.join(BASE_DIR, 'static')), ) STATIC_ROOT = os.path.join(BASE_DIR, 'files') STATIC FILES_FINDERS = [ > > "django.contrib.staticfiles.finders.FileSystemFinder", > > "django.contrib.staticfiles.finders.AppDirectoriesFinder", > > ] urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('paintings/', views.paintings, name='paintings'), path('sculptures/', views.sculptures, name='sculptures'), path('engravings/', …
I am writing tests for my Django application using asyncio and running into a database access issue. Here is minimal code that reproduces the error: import pytest from authentication.models import User @pytest.mark.django_db(transaction=True) @pytest.mark.asyncio class TestDatabaseAccess: @pytest.fixture(autouse=True) def _fixture(self): User.objects.create(username='username') async …
I want to create registration as a patient and as a doctor such that when user login my website they get two options(as patient or as doctor).How to achieve this using Django? Registration form has different fields for Doctor and …
I'm working on Django and connecting to a remote SQL Server database. I managed to make the connection to the database using the MSSQL engine, but when I run inspectdb, the generated file contains errors due to the character "Ñ", …
Making a website that has a forum for text posts and a greenhouse page for images, when I try to post on the forum page it posts it to the greenhouse page, and when i try to add a comment …
Я неопытный кодер и впервые пишу большой сайт на django, возникла проблема, я динамически загружаю контент в различные блоки/секции (одна страница, контент меняется), и при любом действии дублируется запрос, нажал на кнопку которая выводит в консоль 1 сообщение выводится 2, …
I'm trying to develop a multiplayer web game using Django. I understand that in Django's MTV Pattern, the view part takes on the role of the controller. But the view part needs a user in the frontend who accesses the …
UPDATE: Оставляю изначальное сообщение без изменений, дополнение ниже после "UPDATE" Пишу свое первое Джанго-приложение, появилась необходимость получить данные о транзакции в сети BSC по ее хэшу. Как водится, спросил совет у ChatGPT, он надоумил на следующее: checker.py (это я создал …
I want to call my local package utility by its name like in Django django-admin. It has structure like: utility-name [command] I've found the method of calling utility using __ main __.py. Structure of using this method is: python -m …
If you enable the cache: @cache_page(20, key_prefix='index_page') def index(request): post_list = Post.objects.order_by('-pub_date').all() paginator = Paginator(post_list, 10) page_number = request.GET.get('page') page = paginator.get_page(page_number) return render(request, "index.html", {'page': page, 'paginator': paginator}) When I create a new post, I can no longer …
I am having issues while learning about SQLite databases in Django. I am trying to check if a specific url is already in the database, but I keep getting a Integrity Error. this is the code that is supposed to …
Hi i have a filed i cannot make it in database although i make makemigrations and migrte this is models.py class Display(models.Model) : url=models.URLField(unique=True) text = models.CharField(max_length=150) class Display_Data(models.Model) : displays = models.ManyToManyField(Display,related_name='display_data') users= models.ForeignKey(UserProfile,on_delete=models.CASCADE,default="1") choosenum=models.IntegerField() puplish_date =models.DateTimeField(default=datetime.now) and …
I am a beginner and trying to create a basic college portal. I am getting NoReverseMatch at /admin/api/student/add/ error when adding students data in django-admin panel. urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/',admin.site.urls), path('api/',include('api.urls')), …
У меня есть таблица, как показано ниже Таблица A ID name score 1 aaa 100 2 bbb 200 3 ccc 300 4 bbb 100 5 kkk 600 6 ccc 300 Теперь имена bbb и ccc дублируются, …
Я пытаюсь передать данные из моего представления в класс формы с помощью WizardView. Без WizardView я делаю это с помощью get_forms_kwargs(), как показано ниже: def get_form_kwargs(self): kwargs = super(MenuAdd, self).get_form_kwargs() kwargs.update({'month': self.kwargs['month']}) return kwargs А в классе …
''' from django.core.management.base import BaseCommand from myapp2.models import Client class Command(BaseCommand): help = "Create user." def handle(self, *args, **kwargs): client = Client(name='John', email='john@example.com', phone_number="893242", address='secret12', registration_date='25.05.2002') client.save() self.stdout.write(f'{client}') ''' …
Я пытаюсь изучить Django на python, и сегодня я наткнулся на эту ошибку: "NoReverseMatch at /downloader/ Reverse for 'login' not found. 'login' не является правильной функцией представления или именем шаблона." Я не уверен, почему это происходит, но вот …
Правильно, давайте попробуем еще раз. Мои изображения Django не отображаются в моем шаблоне. Несмотря на правильную настройку. Вот моя установка - полностью воспроизводимая установка - выглядит следующим образом: # settings.py MEDIA_URL = '/media/' MEDIA_ROOT …
Я хочу, чтобы уникальное поле генерировалось на уровне базы данных. Способ, которым работает unique=True, заключается в том, что он выдает ошибку, если видит дублирующееся значение в базе данных. Но мне это не нужно, я хочу, чтобы вместо ошибки просто генерировалось …
У меня есть приложение django со страницей, которая показывает таблицу данных с текстовыми строками, заполненными из модели. Каждая строка - это url сайта. Мне нужно иметь возможность нажать на любую из этих строк и записать строку url в текстовый …
Я создал простой, локально работающий сервер django, который предоставляет кнопки для запуска некоторых команд bash на сервере (в настоящее время это мой MacBook Pro). Вывод этих команд затем отображается на сайте. В общем: Веб-сайт работает нормально, пока я …