I'm trying to use a ManyToManyField to create a model attribute with a set of options (instances of the m2m model). When I go to save the model in my ModelForm, save_m2m() gives an error saying that Field 'id' expected …
I'm getting this error when I'm trying to go to the configuration section of my site. This is my folder structure: [[1]: https://i.stack.imgur.com/DhV7A.png] Here's the code: Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', …
I created custon user model extending AbstractUser. But when making migrations, many tables were added to postgresal, i have only two models. i named my customuser : CustomUser and the other model Offers. These tables were found in postgresql: api_customuser …
I am creating a Django project. The core feature of this project is to create dynamic forms, then to fill these forms and finally to visualize this informations using some BI tools. In addition to creating/storing dynamic forms information, user …
I am a student who is learning web programming. It's just that I added functionality to the program, so it's not saved in DB. Above is saved, but features have not been added, below is added, but not saved to …
I am creating a quiz app and i have some value for every radio Option, and i want to store the question,option the user has selected and the value for that option in database. Below is the model for Questions …
When I run the server it gives this message on console: "You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to …
I am new in Django and now I am working with manipulation of database in django admin panel. While playing with features I am unable to add values in features. There is no key and after saving it leaves empty …
I really don't know how to push on with this, the idea is an investment platform where the user can have multiple investments and each investment has a due date enter image description here this image shows …
Note my question is similar to this one, however that answer recommend not calling the customised user model User, whereas the official docs and this issue do. I created a custom User model …
I am currently creating a website with Django and I came across the following question: I want to store data the user enters (a string, for example a name or the user's age), BUT it must be "deleted" when the …
Here i have attached views.py where add_projectdomain fields are added by importing models, here how can i get the loginid i.e. session key(userid) (as i have got in company_details view by using reuest.session.get method) in Add_domainwise projects form and save …
I am using mysql with Django. I am trying to count the number of visitor_pages for a specific dealer in a certain amount of time. I would share the raw sql query that I have obtained from django debug toolbar. …
Typically I'd set a value in settings.py and then use @override_settings in tests to override it. Is there any similar mechanism that exists for overriding settings in apps.py when using app_config? For instance # apps.py class MyConfig(AppConfig): SOME_VAR = "SOME_VAR" …
I am filtering my data, and also applying paginator, I have found some solution and I used it but it is working only for the next button and not for previous and button numbers in between i.e. for {{i}} (Django, …
Шаблон с кодом наследуются с хедера главной страницы для всех приложений {% extends "mainpage/header.html" %} {% block content %} Но почему-то только на главной странице условие проверки на авторизацию просто не работает, на остальных страницах все отображается корректно {% …
In Django tests, I want to log in and make a request. Here the code def test_something(self): self.client.login(email=EMAIL, password=PASSWORD) response = self.client.get(reverse_lazy("my_releases")) self.assertEqual(response, 200) But the code doesn't work and returns AttributeError: 'AnonymousUser' object has no attribute 'profile' …
When I save() a model that contains an ImageField, the post_save signal of the model base deletes the file that was previously associated with the ImageField which is fair enough because the file has changed to a new value. However, …
Goal is to send the serialized data of the created object of POST Method! Request will come from Android/IOS app built with Flutter/Dart I am trying to use Django Channels Rest Framework. But I am not sure if it is …
I'm building a chat app with Angular and Django using the get stream tutorial. https://getstream.io/blog/realtime-chat-django-angular/ However, I'm trying to run the app to create the chat view but it keeps saying 'messages' does not exist at the …
{% if messages %} <ul class="messages"> {% for message in messages %} <li {% if message.tags %} class="{{message.tags}}" {% endif %}> <i class="bi bi-exclamation-triangle-fill"></i> {{ message }} </li> {% endfor %} </ul> {% endif %} I want to show …
I'm running a unit test in Django but keep getting an error File "C:\****\views.py", line 21, in post s = str(points['string_points']) KeyError: 'string_points' Command Used: python manage.py test The structure of my test code looks as follows: class …
I have the following example: class Profile(models.Model): ... class Person(models.Model): profile = models.ForeignKey(Profile, ...) I have complex Model manager for Profile class and I built a view to list a big amount of Person. I try to compute everything …
I'm working on a project that is still in its early stages using Django and Jquery. I would wish to create a nested table in that team leaders have people assigned to them. So far I have been able to …
Im trying to fill my foreignkey with the user that is logged in, but i have seen alot of way but they havent worked for me, does anyone know what im doing wrong? and how i can fix it? View: …
I have a model which is as follows: class BloodTestType(models.Model): type = models.CharField(max_length=200) def __str__(self): return str(self.type) class BloodParameters(models.Model): type = models.ForeignKey(BloodTestType, on_delete=models.CASCADE) parameter = models.CharField(max_length=200) minimum_value = models.FloatField() maximum_value = models.FloatField() unit = models.CharField(max_length=200) required = models.BooleanField(default=True) GENDER_CHOICES = …
I'm building a webcomic using Django framework. The problem that I have now is to display chapters from different issues with AJAX. Let's say we have issue#1 and issue#2, when user clicks on issue#1 cover, it displays chapters of issue#1. …
I am using pymysql to connect to sql like this: con=pymysql.connect(...) cur=con.cursor() Well I am using flask web framework for some use. I defined the connection object as a single time and pass it to other function …
I get the following error ValueError: Cannot assign "(<UserProfile: testUser>, True)": "Comments.profileInfo" must be a "UserProfile" instance. What I am doing is unit testing : def create_user_profile(user): profile = UserProfile.objects.update_or_create(gender = 'F', defaults={ 'user': user}) return profile def create_comment(profile, …
There seems to be a problem with migrating my models on the Heroku server. I am able to run python manage.py makemigrations and python manage.py migrate just fine and I am able to view my site on my local machine …
У меня появилась проблема, которая видна на скриншотах: Сам проблемный html файл: Там видно и окно отладки и ещё структура проекта. Вот код файла urls.py from django.contrib import admin from django.urls import path from …
I'm trying to write a test for UpdateView of Model which has a title and slug. When I try to test my view I can't recive a response because save method throws an ERROR Reverse for 'books-delete' with arguments '('',)' …
I want to distribute a Django based application to run on customer's intranet. I want to give a simple way to install the application, one script or tgz to install everything needed, including a http server and a database. What …
Как сделать url для товара со своим слагом, и с слагом категории. Например: category/slug категории/slug товара/ from django.db import models from django.contrib.auth.models import User from django.urls import reverse class Profile(models.Model): user = models.ForeignKey(User, unique=True, on_delete=models.CASCADE) wishlist = models.ForeignKey('Product', on_delete=models.CASCADE, blank=True, …
Необходимо создать две таблицы у которых не будут совпадать id в поле primary_key. Например, в таблицу1 мы добавляем новый элемент у которого id будет = 1. Затем в таблицу2 добавляем элемент у которго id будет продолженим последовательности и равен 2. …
Полная ошибка выглядит так File "/usr/local/lib/python3.8/site-packages/django/template/backends/django.py", line 123, in get_package_libraries raise InvalidTemplateLibrary( django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'mptt.templatetags.mptt_tags': cannot import name 'FieldDoesNotExist' from 'django.db.models.fields' (/usr/local/lib/python3.8/site-packages/django/db/models/fields/__init__.py) насколько я понял, мне нужно исправить строчку from …
Мне нужно добавить lastmod для сайтмапы index, сейчас sitemap.xml выглядит так: <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" <sitemap> <loc>localhost:8000/sitemap-pages.xml</loc> </sitemap> </sitemapindex> То есть, необходимо добавить тег <lastmod></lastmod>, вот мой urls.py sitemaps_pages = { 'pages': sitemaps.PageViewSitemap, 'life': sitemaps.LifeViewSitemap, 'lifes': sitemaps.LifesSitemap, 'novosti': sitemaps.NewsViewSitemap, 'novost': sitemaps.NewsSitemap, …
System CheckError: System check identified some issues: ERRORS: ?: (urls.E004) Your URL pattern (<module 'chat.urls' from 'D:\djangoproject\web_ chat\chat\urls.py'>, None, None) is invalid. Ensure that urlpatterns is a list o f path() and/or re_path() instances. HINT: Try using path() instead of …
Хочется найти фундаментальные материалы, возможно книги, по организации архитектуры проектов с django и впринципе python. Существует множество статей которые рассматривают кодстайл в каких-либо локальных моментах, та же самая документация и PEP (например https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/coding-style/). Но хочется посмотреть какой-либо …
Никак не получается передать переменную(user.username) из шаблона во views, выбрал простой вариант передать через запрос, ошибок не выдает, но и переменная не приходит: template: <form action="{% url 'cabinet' %}?user.username={{user.username}}" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="w-50 …