Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Generating models from Database with FastAPI and SQLAlchemy
I have a Django project running on production with PostgreSQL. I want to spin a separate FastAPI microservice to do a specific task, and I want it to communicate directly with the database I have hooked up with Django. I do not want to rewrite all the models in FastAPI using pydantic, and at the same time I don't want to make a mistake. In Django, there is python manage.py inspectdb to automatically generate models using an existing database. Is there an equivalent in FastAPI, SQLAlchemy or Pydantic? -
django filter: datetime filed
Pease help me with next. I create NotesFilter based on django_filters.FilterSet. All filters is working except datetime. I trying everything, but something wrong and it doesn't working. List is empty when i enter any value in any format in field "Reminder contains:" filter.py: class NotesFilter(django_filters.FilterSet): SORT_BY_ = ( ('title+', 'Title(A-Z)'), ('title-', 'Title(Z-A)'), ('reminder_data_time+', 'Reminder (0-9)'), ('reminder_data_time-', 'Reminder (9-0)'), ) sort = django_filters.ChoiceFilter(label='Order by:', choices=SORT_BY_, method='filter_') class Meta: model = Notes fields = { 'notes_category': ['exact', ], 'title': ['icontains', ], 'reminder_data_time': ['icontains',] } def filter_(self, queryset, name, value): if value == 'title+': sort = 'title' elif value == 'title-': sort = '-title' elif value == 'reminder_data_time+': sort = 'reminder_data_time' elif value == 'reminder_data_time-': sort = '-reminder_data_time' return queryset.order_by(sort) models.py: class Notes(models.Model): title = models.CharField(max_length=25) text = models.TextField() data_time = models.DateTimeField(auto_now_add=True) reminder_data_time = models.DateTimeField(default=datetime.datetime.now()) notes_category = models.ForeignKey(NotesCategory, on_delete=models.CASCADE) class Meta: verbose_name_plural = "Notes" def __repr__(self): return self.title def __str__(self): return self.title def get_absolute_url(self): return reverse('detail_note', args=[str(self.id)]) notes.html: [![<form method="get"> {% for choice in filter.form %} {% if choice.name == 'notes_category' %} <td>Category: {{ choice }}</td> {% elif choice.name == 'title__icontains' %} <td>Title contains: {{ choice }}</td> {% elif choice.name == 'reminder_data_time__icontains' %} <td>Reminder contains: {{ choice }}</td> {% elif choice.name == 'sort' … -
OperationalError at /accounts/login/ no such table: django_site
I wanted to ask a question, I am hosting my Django project on pythonanywhere, we are using the allauth package, I was having no problems until this happened.... OperationalError at /accounts/login/ no such table: django_site Request Method: GET Request URL: https://dariobackend2022.pythonanywhere.com/accounts/login/ Django Version: 4.1 Exception Type: OperationalError Exception Value: no such table: django_site Exception Location: /home/DarioBackEnd2022/.virtualenvs/lalcecCHACO- virtualenv/lib/python3.9/site- packages/django/db/backends/sqlite3/base.py, line 357, in execute Raised during: allauth.account.views.LoginView Python Executable: /usr/local/bin/uwsgi Python Version: 3.9.5 Python Path: ['/var/www', '.', '', '/var/www', '/usr/local/lib/python39.zip', '/usr/local/lib/python3.9', '/usr/local/lib/python3.9/lib-dynload', '/home/DarioBackEnd2022/.virtualenvs/lalcecCHACO- virtualenv/lib/python3.9/site-packages', '/home/DarioBackEnd2022/Grupo2-ProyectoFinal'] Server time: Mon, 05 Sep 2022 17:36:20 -0300 the context is that we were changing the name of the urls in the href of our templates, the allauth one is {% url 'account_login' %} but we get that error.... these are my URLs.py from argparse import Namespace from django.contrib import admin from django.urls import path, include from django.contrib.staticfiles.urls import staticfiles_urlpatterns from pagina import views urlpatterns = [ path('foro/', views.listarPost.as_view(), name='lista_post'), path('post/<slug:url>/', views.DetallePost.as_view(), name='detalle_post'), path('accounts/', include('allauth.urls')), path('accounts/profile', views.profile), ] urlpatterns += staticfiles_urlpatterns() if you need more information ask me please -
TypeError: modelform_factory() got an unexpected keyword argument 'extra'
I'm trying to use the modelformset_factory to render multiple forms. However, when trying to run the server, this error occurs TypeError: modelform_factory() got an unexpected keyword argument 'extra' All the online sources say that I should be able to specify the extra argument in the modelform_factory but I can't seem to. forms.py class MapSeniorTeachForm(ModelForm): role = forms.CharField(max_length=32) def __init__(self, teach_id, *args, **kwargs): super(MapSeniorTeachForm, self).__init__(*args, **kwargs) self.teach_id = teach_id self.fields['senior'] = forms.ChoiceField(choices=[(1,1),(2,2),(3,3)]) class Meta: model = MapSeniorTeach fields = ['role', 'senior'] MapSeniorTeachFormset = modelform_factory(MapSeniorTeach, form=MapSeniorTeachForm, extra=1) Clipped Output Log File "C:\Users\ethan\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\ethan\Documents\VSCodeProjects\bansheeApp\bansheeApp_project\banshee\training\urls.py", line 3, in <module> from .views import * File "C:\Users\ethan\Documents\VSCodeProjects\bansheeApp\bansheeApp_project\banshee\training\views.py", line 14, in <module> from .forms import LessonTeachForm, ActivityTeachForm, MapSeniorTeachFormset File "C:\Users\ethan\Documents\VSCodeProjects\bansheeApp\bansheeApp_project\banshee\training\forms.py", line 25, in <module> MapSeniorTeachFormset = modelform_factory(MapSeniorTeach, form=MapSeniorTeachForm, extra=1) One thing to note, if I remove the extra keyword, one instance of the form is successfully rendered. Here are some sources I was speaking about before: … -
DRF dynamic choices depend on current user
is there any way to make choices dynamically depend on current user something like that: class RideSerializer(serializers.ModelSerializer): provider_username = serializers.ChoiceField(choices=request.user.providers) -
Django fetch data as json from property and calculate it with jquery
Like the titile says, is it possible? I have like 100 numbers that are only updated but need to be calculated and and results should show in template, annotate allows me to calculate some fields but wont allow me to show it anywhere I need. And even if I got that as json I dont know jquery how would I calculate those numbers. my models in small class numbers(models.Model): number 1 = models.IntegerField(default=0) number 2 = models.IntegerField(default=0) number 3 = models.IntegerField(default=0) number 4 = models.IntegerField(default=0) number 5 = models.IntegerField(default=0) @property def sum of 1_2(self): return json.dumps(self.number 1 + self.number2) and so on -
django on cpanel ,, ImportError: No module named app_name.wsgi
I'm trying to deploy Django on Cpanel shared hosting .. after creating the app and everything was going okay following this guide, it never opens and it gives me this error : Traceback (most recent call last): File "/home/wateopjw/water_maps_dashboard/passenger_wsgi.py", line 1, in <module> from water_maps.wsgi import application ImportError: No module named water_maps.wsgi my passenger_wsgi.py from water_maps.wsgi import application my wsgi.py file """ WSGI config for water_maps. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'water_maps.settings') application = get_wsgi_application() Project Structure -
How to create a new field in django admin panel inside if condition in a method in the model
In the "save" method, I want to create a new field in the admin panel if the transaction type is transefere and vs code sees the new variable as a deadcode and says it's not accessed. ''''''''''''''''''''''''''''''''''''''''''''''' from django.db import models import uuid import random import math class Transaction (models.Model): customer=models.CharField(max_length=50) balance= models.DecimalField( max_digits=10,decimal_places=2 ,default=random.randint (0,30000)) class trans_options(models.TextChoices): CASH_IN= "cash in","cash in" CASH_OUT= "cash out" ,"cash out" TRANS= "transefere","transefere" INVALID="INVALID OPERATION", "INVALID OPERATION" Transaction_type=models.CharField( max_length=50,choices=trans_options.choices ,default=trans_options.INVALID) amount =models.DecimalField( max_digits=4,decimal_places=2) def save(self, *args, **kwargs): if self.Transaction_type == "cash in" : self.balance = self.balance + self.amount if self.Transaction_type == "cash out": self.balance=self.balance - self.amount if self.Transaction_type == "transefere" : self.balance=self.balance - self.amount customer2 = models.CharField(max_length=50) return super(Transaction, self).save(*args, **kwargs)' -
when I do python manage.py collectstatic I get the following error
I'm new to coding and djgango in general. I don't know what to do. I have checked my code time and again... and I'm lost. ``` STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'build/static') ] I Get the following error. I've checked my urls.py but aparently all is fine Traceback (most recent call last): File "/home/juanneg/ecommerce/manage.py", line 22, in <module> main() File "/home/juanneg/ecommerce/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/juanneg/ecommerce/envcom/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/juanneg/ecommerce/envcom/lib/python3.10/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/home/juanneg/ecommerce/envcom/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/juanneg/ecommerce/envcom/lib/python3.10/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/home/juanneg/ecommerce/envcom/lib/python3.10/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/home/juanneg/ecommerce/envcom/lib/python3.10/site-packages/social_django/models.py", line 14, in <module> from .fields import JSONField File "/home/juanneg/ecommerce/envcom/lib/python3.10/site-packages/social_django/fields.py", line 7, in <module> from django.utils.encoding import force_text ImportError: cannot import name 'force_text' from 'django.utils.encoding' (/home/juanneg/ecommerce/envcom/lib/python3.10/site-packages/django/utils/encoding.py) -
pagination in django works calculates pages correctly but doesn't separate them
The paginator in django correctly calculates the number of pages, but does not break the models into pages and everything is displayed on 1 page, please tell me what to do with this This is my views.py,where is a paginator: from django.shortcuts import render, get_object_or_404 from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from .models import * def index(request): news = Content.objects.filter(is_published=True) page = request.GET.get('page', 1) paginator = Paginator(news, 20) try: page_obj = paginator.page(page) except EmptyPage: page_obj = paginator.page(1) except PageNotAnInteger: page_obj = paginator.page(paginator.num_pages) return render(request, 'content/index.html', {'news': news, 'page_obj': page_obj}) def view_news(request, news_id): news_item = get_object_or_404(Content, id=news_id) return render(request, 'Content/view_news.html', {'news_item': news_item}) And there is my paginator template: {% block content %} <nav class="paginator"> <ul class="pagination"> {% if page_obj.has_previous %} <a class="page-link" href="?page={{ page_obj.previous_page_number }}"> <li class="page-item">Предыдущая</li> </a> {% else %} <a class="page-link"> <li class="page-item">Предыдущая</li> </a> {% endif %} {% for i in page_obj.paginator.page_range %} {% if page_obj.number == i %} <a class="page-link"> <li class="page-item">{{ i }}</li> </a> {% else %} <a class="page-link" href="?page={{ i }}"> <li class="page-item">{{ i }}</li> </a> {% endif %} {% endfor %} {% if page_obj.has_next %} <a class="page-link" href="?page={{ page_obj.next_page_number }}"> <li class="page-item">Следующая</li> </a> {% else %} <a class="page-link"> <li class="page-item">Следующая</li> </a> {% endif %} </ul> … -
Give permission if it is staff. django
I have this code in django and I want the button to appear if the user is a super user or staff. I don't know how I should put it, I tried with is_superuser or is_staff but it didn't work. {% if request.user == post.user %} <div class="trash"> <a href="{% url 'delete' post.id %}"> <i class="fa fa-trash-o" style="color:#657786; font-size: 20px" aria-hidden="true"></i> </a> </div> {% endif %} Code -
Error deploying on Heroku - Django app - collectstatic --noinput
I'm very new trying to deploy an app on Heroku my Django app, but a got the error from above, if you have any idea, and if you look for something else out place please be free to share it because I'm junior and I'm learning. error: the code before the following error is all the packages installed on the deploying, all the packages are installed successfully and then: ---> -----> $ python project/manage.py collectstatic --noinput Traceback (most recent call last): File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 259, in fetch_command app_name = commands[subcommand] KeyError: 'collectstatic' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/tmp/build_f151875e/project/manage.py", line 22, in <module> main() File "/tmp/build_f151875e/project/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 266, in fetch_command settings.INSTALLED_APPS File "/app/.heroku/python/lib/python3.10/site-packages/django/conf/__init__.py", line 92, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.10/site-packages/django/conf/__init__.py", line 79, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.10/site-packages/django/conf/__init__.py", line 190, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", … -
How should i fix the problem with opening django project\site?
i wrote classic django-admin startproject mysite cd mysite python manage.py runserver but the console shown this Error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xca in position 0: invalid continuation byte also console shown very big text and i can't understand what does it mean! help please!! full text in console -
Django: Parse the docx and get content from document
I'm writing Django app where user can upload the .docx file and get flashcards done in db from parsed document. Flashcards are created from different heading types, like below: Heading title: Category of flashcards, Heading 1: Title of flashcard, Heading normal: Content of flashcard The problem is when I upload word document. Category is created, but title and content are empty strings.. I did separate python file with the same func and there everything is working: category, title and content are exactly how it should be. Input is the same in both cases (Flask.docx file): Flask Framework (using heading Title, so it should be the category) Flask (using Heading 1, so it should be the title of a flashcard) Is a Python Web framework. (using heading normal, so it should be the content of a flashcard) Django: Models: from django.db import models # Create your models here. class FlashcardCategory(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=30, unique=True, help_text="Category of flashcards.") def __str__(self): return self.name class Flashcard(models.Model): id = models.IntegerField(primary_key=True) category = models.ForeignKey(FlashcardCategory, on_delete=models.CASCADE) title = models.CharField(max_length=50, help_text="Title of flashcard.") content = models.TextField(unique=True, help_text="Content (reverse) of flashcard.") def __str__(self): return f"{self.title} - {self.content}" View: def upload_documents_and_parse(request): """ Function based view where user … -
Dockerfile - chown command usage base on different env's
mkdir data && mkdir data/Files && chown -R 25708:16681 data Issue : Currently chown command is set based on DEV env. How do i specify chown command based on different envs: DEV, UAT, PROD in dockerfile. I have an variable in container: APP_ENV = DEV Or UAT OR PROD. Please advice. -
AttributeError: 'Settings' object has no attribute <class that I defined inside settings.py> when settings imported from conf
I've added enum in the settings.py file class Syncs(Enum): A = 'a' B = 'b' when I try to use them in an app by importing from django.conf import settings, it raises: AttributeError: 'Settings' object has no attribute Syncs on the other hand if I import settings file directly it works I know it's because from django.conf import settings works differently so that's why this doesn't work. Is there some recommended way to do this? So far I do: class Syncs(Enum): A = 'a' B = 'b' SYNCS = Syncs -
django.db.utils.ProgrammingError: cannot cast type date to integer
I am getting following error when trying to deploy my application to heroku.com: django.db.utils.ProgrammingError: cannot cast type date to integer LINE 1: ...ts" ALTER COLUMN "month" TYPE integer USING "month"::integer ^ As this is new for me, no idea what to correct as there is no link to file, row. etc. And I have only one field with month in my models - mm field in MonthlyCosts: class MonthlyCosts(models.Model): y = int(date.today().year) y1 = y - 1 year_selection = ( (y, y), (y1, y1), ) months_selection = ( (1, 'January'), (2, 'February'), (3, 'March'), (4, 'April'), (5, 'May'), (6, 'June'), (7, 'July'), (8, 'August'), (9, 'September'), (10, 'October'), (11, 'November'), (12, 'December') ) year = models.IntegerField("Year", choices=year_selection) mm = models.IntegerField("Month", choices=months_selection) But it is the integer, so why mentioning type "date"? Then I am using column "month" in pandas tables which are part of functions for particular views, but there are also int or str types, no date. So no idea what this error means. Thanks a lot for help. -
nested categories not working correctly in Django
I'm working on a project that contains lots of detail and extra information. I need to use nested categories for my navbar, the first time I ran the code, it was working properly but then when I faced a bug at migration and I had to re-create the project again, It isn't working now anymore. I have two different types of coding for this nested category and none of them works! class Category(MPTTModel): name = models.CharField(max_length=30) slug = models.SlugField(allow_unicode=True, blank=True, null=True, unique=True) parent = models.ForeignKey('self', default=None, null=True, blank=True, on_delete=models.SET_NULL, related_name='children') is_child = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: verbose_name = _('category') verbose_name_plural = _('categories') def __str__(self): return self.name this first one and this second one: class Category(MPTTModel): name = models.CharField(max_length=100) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name="children") is_child = models.BooleanField(default=False) slug = models.SlugField(unique=True, null=True, blank=True, allow_unicode=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: verbose_name = _('category') verbose_name_plural = _('categories') def __str__(self): return self.name once I create a new category as a child, it must be included in its parent. But nothing happens and it is created just as a separate category. I'll be so glad if you can help me with this. -
Why is solid i18n redirecting back to the previous language?
I am on an old Django version (1.8) and using solid-i18n==1.3.0 to support having the default language like English as / instead of /en. My problem is that, in production, a page whose sessions is set to Spanish, if you select any other language, redirects twice: first to the selected language and then back to Spanish. This is the session in Spanish: >>> from django.contrib.sessions.models import Session as Sess >>> s = Sess.objects.get(pk='f2l3drtob4ox797ohcwantp4xfrb4r5u') >>> s.get_decoded()['_language'] u'es' And this is the request chain: The POST body of the selectlang/ request is: csrfmiddlewaretoken=xxxxxxxxxxxxxxxxxxxx&next=%2Fedit%2Fxxxxxxxxxxxxxxxxxxxxx&language=en My confusion is about the third request: why is it going back to the /es/edit/xxxxxxxx page? My i18n settings are as follows: SOLID_I18N_USE_REDIRECTS = True # SOLID_I18N_HANDLE_DEFAULT_PREFIX = True # SOLID_I18N_DEFAULT_PREFIX_REDIRECT = True # not working, redirects to "en" back again And the view the selectlang/ URL points to is a custom one: def select_language(request): """ Just like `django.views.i18n.set_language` but adds `translation.activate(lang_code)` because of an issue with solid_i18n not redirecting to the default language (no path) when selected. """ next = request.POST.get('next', request.GET.get('next')) if not is_safe_url(url=next, host=request.get_host()): next = request.META.get('HTTP_REFERER') if not is_safe_url(url=next, host=request.get_host()): next = '/' response = http.HttpResponseRedirect(next) if request.method == 'POST': lang_code = request.POST.get('language', None) if … -
AttributeError: 'AnonymousUser' object has no attribute 'is_email_verified'
I have django app with registration system in it and it doesn't work as expected. I recently added email verification in my view and because of that I get error. For email verification I have 2 functions. One function sends email, the other verifies and creates user. function 1 def send_action_email(user, request): current_site = get_current_site(request) email_subject = 'Activate account | Zane' email_body = render_to_string('authentication/email/email_body.html', { 'user': models.PersonalUser, 'domain': current_site, 'uid': urlsafe_b64encode(force_bytes(user.pk)), 'token': generate_token.make_token(user) }) email = EmailMessage(subject=email_subject, body=email_body, from_email=settings.EMAIL_FROM_USER, to=[user.email]) email.send() function 2 def activate_user(request, uidb64, token): try: # uid = force_str(urlsafe_base64_decode(uidb64).decode()) uid = force_str(urlsafe_b64decode(uidb64)) user = models.PersonalUser.objects.get(pk=uid) except Exception as e: user = None if user and generate_token.check_token(user, token): user.is_email_verified = True user.save() print('user activated') return redirect(reverse('login')) return render(request, 'authentication/email/activation-failed.html') Then I have my main signup class: class PersonalRegister(View): def post(self, request, *args, **kwargs): ... #get data from form using request.POST.get send_action_email(request.user, request) ... def get(self, request, *args, **kwargs): return render(request, 'authentication/personal/personal_signup.html') When I run my app I get error AttributeError: 'AnonymousUser' object has no attribute 'is_email_verified'. What have I tried? Logging in before doing authentication proccess and It worked but point is to make new user logged out. Later I am also planning on restricting access to registration … -
Django adding link to parent when creating child in a many to one relationship
I have two models in a one to many relationship. I am editing a parent record and creating a child. When I create the child I cannot figure out how the send a reference of the parent so that I can instantiate the ForiegnKey of the child to point to the parent. Could anyone help. thanks The parent is: class Site(models.Model): name = models.CharField(max_length=100) address1 = models.CharField(max_length=100) address2 = models.CharField(max_length=100) postcode = models.CharField(max_length=50) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="sites") def __str__(self): return f"{self.name}, {self.postcode}" def get_queryset(): return set.request.user.sites.all() the child is: class Administrator(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) telephone = models.CharField(max_length=50) email = models.EmailField() site = models.ForeignKey( Site, on_delete=models.CASCADE, related_name="adminstrators" ) def __str__(self): return f"{self.first_name} {self.last_name}, {self.email}" I am trying to point the child at the parent in the child's validation function: def form_valid(self, form): self.object = form.save(commit=False) self.site = # I don't know what to put here as I have to reference to the parent Site object self.object.save() return HttpResponseRedirect(self.get_success_url()) -
Password Authentication failed for user 'postgres' and default to windows user in PyCharm Professional
I have installed PostgreSQL on my windows PC. During installation I was asked a choose a password and a default user: postgres was assigned. I am trying to connect PostgreSQL to PyCharm for a Django project. I have changed my default database to PostgreSQL and tested the connection in the database. It worked perfectly. Below is the databases in the settings.py file. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'btredb@localhost', 'USER': 'postgres', 'PASSWORD': 'PG_PASSWORD', 'HOST': '127.0.0.1', 'PORT': '5432', } } However, when I run manage.py runserver I get a password authentication failed for use 'cheap' which is my windows user. Why is PyCharm trying login to the windows user instead of the PostgreSQL user set in the databases settings? Can any one help to connect PostgreSQL to PyCharm professional? -
Add extra property to this json response returned by Django rest framework
I am running django 4.0.6 with djangorestframework. This is my serializers.py from django.contrib.auth import get_user_model from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): # new class Meta: model = get_user_model() fields = ( "id", "username", ) This is my views.py from django.contrib.auth import get_user_model from rest_framework import generics from .serializers import UserSerializer class UserList(generics.ListCreateAPIView): queryset = get_user_model().objects.all() serializer_class = UserSerializer Here is the json response of the API; { "count": 3, "next": null, "previous": null, "results": [ { "id": 1, "username": "test" }, { "id": 4, "username": "test1" }, { "id": 8, "username": "test3" } ] } I would like to add an extra property to this json response returned by Django rest framework such that it will look like this; { "count": 3, "next": null, "previous": null, "results": [ { "id": 1, "username": "test" "combine" : "test 1" }, { "id": 4, "username": "test1" "combine" : "test1 4" }, { "id": 8, "username": "test3" "combine" : "test3 8" } ] } The extra property combine is created by concatenating id and username. -
Django 4.1: How do I set Profile model's slug field's default value to username?
I've created a profile model for [Django's default user model](https://docs.djangoproject.com/en/4.1/ref/contrib/auth/#user-model) and I want to create a slug for it so that it can be called using a username and not a user id or pk, I've tried this so far but I've achieved nothing, **I'm not asking you to complete the way I'm trying to achieve this but if there is a better way of doing it, Please tell me** models.py: ```py from django.db import models from django.contrib.auth.models import User from django.urls import reverse from django.template.defaultfilters import slugify class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(blank=True, null=True) profile_picture = models.ImageField(upload_to=user, blank=True) slug = models.SlugField() def get_absolute_url(self): return reverse('details', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(User.objects.get(user__id = 1).username) return super().save(*args, **kwargs) urls.py: ```py from django.urls import path from django.contrib.auth.views import LogoutView from .views import UserCreateView, UserLoginView, UserProfileCreateView urlpatterns = [ path('register/', UserCreateView.as_view(), name='signup'), path('login/', UserLoginView.as_view(), name='login'), path('logout/', LogoutView.as_view(), name='logout'), path('u/<slug:slug>/edit_profile/', UserProfileCreateView.as_view(), name='edit_profile') ] -
Django - before model create
I have a model: book(book_id, release_year, book_number_by_release_year) Field book_number_by_release_year must be automatically generated and incremented by 1 within the release_year field for new model instances. What is the best way to do this in Django? Thank you for your help