Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
500 internal server problem in Django issued from an inexistent favicon
I am a newbie in the Django world, and I am trying to start a new Django project but in vain! first of all, I have an old favicon from another project that appears. I don't have any referred favicon in this new project even I tried to add one it was the same problem. During the handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/user/.local/lib/python3.8/site-packages/django/template/base.py", line 470, in parse compile_func = self.tags[command] KeyError: 'endif' During the handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.8/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/home/jihan/.local/lib/python3.8/site-packages/django/contrib/staticfiles/handlers.py", line 76, in __call__ return self.application(environ, start_response) File "/home/user/.local/lib/python3.8/site-packages/django/core/handlers/wsgi.py", line 133, in __call__ response = self.get_response(request) File "/home/user/.local/lib/python3.8/site-packages/django/core/handlers/base.py", line 128, in get_response response = self._middleware_chain(request) File "/home/user/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 49, in inner response = response_for_exception(request, exc) File "/home/user/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 103, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/home/user/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 138, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "/home/user/.local/lib/python3.8/site-packages/django/views/debug.py", line 52, in technical_500_response html = reporter.get_traceback_html() File "/home/user/.local/lib/python3.8/site-packages/django/views/debug.py", line 329, in get_traceback_html t = DEBUG_ENGINE.from_string(fh.read()) File "/home/user/.local/lib/python3.8/site-packages/django/template/engine.py", line 136, in from_string return Template(template_code, engine=self) File "/home/user/.local/lib/python3.8/site-packages/django/template/base.py", line 155, in __init__ self.nodelist = self.compile_nodelist() File … -
Docker container Losing all file when start from cache
I am trying to create a Dockerfile for developing Django backend. However, when I finished my Dockerfile and tried to build it, a very strange error occurred. When my container was successfully built and automatically started, all the files I had copied into it were lost. Container build log Container log I try to change the CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] to CMD ["python"] and used ls check the file, its empty. file check Then I found the last cache and used it to generate a container, and found that the process worked perfectly fine, which was the most peculiar part. Container from cache working fine Environment I'm using: Windows 11 Docker for windows v4.17.1 PyCharm 2023.1 (Professional Edition) Configuration setting Docker setting configuration setting I don't know if this is a problem with my Dockerfile or a bug with Docker, but since I need to provide my team with a Docker to complete our task, I hope to solve this problem and enable my team to build containers correctly from the Dockerfile. -
How to create django registration with email conformation code
Someone has a guide mb or tutorial about how can i make instant email verification by code like i want to register user and after he typed his email username and password in registerForm send him code on email NOT link and check that code and create user if everything is good with code And i also searching for way to do the same with drf -
Django update_or_create() from JSON when key may or may not exist
So i am create a function where data is being pushed to models from the JSON file. There is a possibility that my JSON may or may not have the desired key. but i am not sure how can i pass default value such as N/A if key not existed. Sample JSON: Here 1st object have title key and 2nd does not h {"timestamp":"2023-04-20T15:45:53.085646251+05:30","status_code":200,"content_length":17620,"failed":false, "title":Test Website} {"timestamp":"2023-04-20T15:45:53.085646251+05:30","status_code":200,"content_length":17620,"failed":false} Django view: data = [] for line in open(results.json', 'r'): data.append(json.loads(line)) for item in data: obj, created = http.objects.update_or_create(asset=item['input'], defaults={ 'status_code':item['status_code'], 'title':item['title'], 'last_added':datetime.now()},) This gives me KeyError('title') Can I add default value to be added only if key not existed? -
ERROR 404 (Page not found) in POST Method with Django
I'm creating a Django project, and I've just implemented the functions for creating, editing, listing, and deleting an instance (object) through the front-end. See below: The view to create an instance(add_category.py): def add_category(request): template_name = 'tasks/add_category.html' context = {} if request.method == 'POST': form = CategoryForm(request.POST) if form.is_valid(): f = form.save(commit=False) f.owner = request.user f.save() messages.success(request, 'Categoria adicionada com sucesso') form = CategoryForm() context['form'] = form return render(request, template_name, context) The template add_category.html: {% extends 'base.html' %} {% load widget_tweaks} {% block title %} Adicionar Categoria - {{ block.super }} {% endblock title %} {% block body %} <div class="container"> <h1>Categoria</h1> {% include 'partials/messages.html' %} <div class="row"> <div class="col-md-12"> <form action="." method="post"> {% csrf_token %} <div class="form-group"> <label for="{{ form.name.id_for_label }}">Nome</label> {{ form.name }} </div> <div class="form-group"> <label for="{{ form.description.id_for_label }}">Descrição</label> {{ form.description}} </div> <button class="btn btn-lg btn-primary btn-block mt-5" type="submit" >Salvar</button> </form> </div> </div> </div> {% endblock body %} The Url's: from django.urls import path from . import views app_name = 'tasks' urlpatterns = [ path('categorias/', views.list_categories, name='list_categories'), path('categorias/adicionar/', views.add_category, name = 'add_category' ), path('categorias/editar/<int:id_category>', views.edit_category, name = 'edit_category' ), path('categorias/excluir/<int:id_category>', views.delete_category, name = 'delete_category' ), ] so far it's working normally. See it: The template Save de object … -
Django can't show Bokeh plot's through CloudFlare tunnel
Have a **Django **website that was accessed through port forwaring in the router. Django lives in an Windows server and in a happy companion with a Bokeh server. Accessing the server ip to a dedicated port gave respons and Django got nice graphics from Bokeh. So I bought a domain and accessed the Django site via a Cloudflare Tunnel, and the Django website can’t get any grapics from Bokeh anymore. How should this be configured and what is best practic for this to work well through Cloudflare. I'am stretching my skills a bit here. Anybody who can help me solve this puzzle? Best regards Jon Helge Thougth in the beginning that the problem were in Bokeh, so installed SSL to solve communication between DJango and Bokeh. Did not solve the problem Tried to find out how Django and Bokeh communicates with each other but still not seen a drawing for how exchenge of data is done between them. But if we go localhost again all is functioning again. A bit stuck om how to go further. -
django-admin returns - zsh: [PATH] no such file or directory
I read through similar posts and learned the Path may be an issue. When I request my path I get the following: (env) Josevv@Eye-C-You env % echo $PATH /Users/Shared/codeproj/env/bin:/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr/bin I see a lot of repetition here. Does anything seem extraordinary here? -
Setting log factory logic from outside settings.py
I have a Django application where I want to update the standard logging to structured JSON format. I can get this working fine by adding my logging config and some business logic into settings.py, but I want to keep the business logic separate. Is there any Django built-in file (akin to the settings.py) that allows you to add some logic that Django will pick up, or can I load a file with this additional logic from settings.py? Here is what I have: settings.py LOGGING = { 'version': 1, 'formatters': { 'structured': { 'format':'%(json_structured)s', 'datefmt': "%H:%M:%S" } }, 'handlers': { ... }, 'loggers': { ... } } # Below is what I want to move from settings.py class JsonDateTimeEncoder(JsonStringFallbackEncoder): def default(self, obj): if isinstance(obj, datetime): return obj.strftime('%Y-%m-%dT%H:%M:%S%z') else: return super().default(obj) std_record_factory = logging.getLogRecordFactory() def structured_log_record_factory(*args, **kwargs) -> logging.LogRecord: record = std_record_factory(*args, **kwargs) record.json_structured = json.dumps( { 'level': record.levelname, ... }, cls=JsonDateTimeEncoder, ) return record logging.setLogRecordFactory(structured_log_record_factory) I know I can load the LOGGING config from file, but not sure how best to achieve this with the additional logic. -
Annotate a QuerySet with Exists instead of Count
I have a model which contains a ManyToManyField: class UserHasProduct(Model): user = ForeignKey(User, on_delete=CASCADE) products = ManyToManyField(Product) class Product(Model): is_nfr = BooleanField(default=False) I want to annotate my queryset with a simple is_nfr value that returns True if any of the products have is_nfr set to True. The best I could come up with is this: UserHasProduct.objects.filter(user=self.request.user).annotate( is_nfr=Count("license_code_products", filter=Q(products__is_nfr=True)) ) That works, but instead of a boolean it returns an integer. Not a huge deal, but I am still wondering if it's possible to return a boolean, and if that would help with query performance in any way (i.e. it can stop as soon as it finds the first match, no idea if it works like that). -
Django CSRF verification failed after setting SSL with Certbot
I'm currently working on a Django project that utilizes Docker, and I recently set up an SSL certificate using a containerized version of Certbot in order to secure my Django app through HTTPS. However, after implementing the SSL certificate and updating my nginx configuration, I began to experience the 'CSRF verification failed' error, which was not an issue before the setup. Previously, I was able to log into my Django app when it was using HTTP. What could be the cause of this problem? My Django setting. # settings.py ALLOWED_HOSTS = ["*"] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] if DEBUG: CORS_ALLOW_ALL_ORIGINS = True else: CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = [ 'https://example.ph', ] My previous nginx configuration. upstream api { server sinag_app:8000; } server { listen 80; location / { proxy_pass http://api; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /static/; } } My new nginx configuration with SSL certificate. upstream api { server sinag_app:8000; } server { listen 80; server_name ${DOMAIN}; location /.well-known/acme-challenge/ { root /vol/www; } location / { return 301 https://$host$request_uri; } } server { listen 443 ssl; server_name ${DOMAIN}; ssl_certificate /etc/letsencrypt/live/${DOMAIN}/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/${DOMAIN}/privkey.pem; include /etc/nginx/options-ssl-nginx.conf; ssl_dhparam … -
Django show TypeError'>' not supported between instances of 'NoneType' and 'float'
I try to compare value from get with value in database. First, I get input from url as f1, f2. Then, if alert_field = 1 set f1 as f , if alert_field = 2 set f2 as f . Then, if alert_symbol = 1 compare f with alert_value using = ,if alert_symbol = 2 compare f with alert_value using >. def test(request): key = request.GET.get('key') f1 = request.GET.get('f1') f2 = request.GET.get('f2') f1 = float(f1) if f1 is not None and is_float(f1) else None f2 = float(f2) if f2 is not None and is_float(f2) else None if Key.objects.filter(api_key=key).exists(): # Alert dv = Device.objects.filter(api_key=dv_key) for dv in dv: # get all condition # Check if alert_field=1 then use f1 value to compare, if alert_field=2 then use f2 value to compare if(dv.alert_field==1): f = f1 fname = rcv_set.field1_name elif(dv.alert_field==2): f = f2 fname = rcv_set.field2_name if(dv.alert_symbol==1): # Check if alert_symbol=1 then compare with = if(f==dv.alert_value): msg = "=" lineAlert(dv_key.line_api, msg) elif(dv.alert_symbol==2): # Check if alert_symbol=2 then compare with > if(f>dv.alert_value): msg = ">" lineAlert(dv_key.line_api, msg) In database I set alert_symbol=2. I send data to get is 50 it show error like this. '>' not supported between instances of 'NoneType' and 'float' Error at … -
Django migrations - opertions to perfrom
i am building a django project and i migrate i get this message: Operations to perform: Apply all migrations: app1, app2, admin, app3, auth, authtoken, contenttypes, sessions Running migrations: No migrations to apply. when i see thae tables in the admin page i can see the changes i am doing but i dont understand how the changes are made but im getting the messgae Operations to perform if someone can please explain to me that would be halpful thanks -
Django migrations - opertions to perfrom
i am building a django project and i migrate i get this message: Operations to perform: Apply all migrations: app1, app2, admin, app3, auth, authtoken, contenttypes, sessions Running migrations: No migrations to apply. when i see thae tables in the admin page i can see the changes i am doing but i dont understand how the changes are made but im getting the messgae Operations to perform if someone can please explain to me that would be halpful thanks -
TemplateDoesNotExist at /app/search_flights/ in Django
I'm making a web app that lets a user login, logout, search a flight, book a flight and view the bookings made. For some reason the 'search_flights/html' is not being rendered or Django's not being able to find it. I spent a lot of time trying to debug it but with no luck. Project directory (I've included search_flights.html both in the root templates folder as well as the app templates folder as of now to see if changing anything will work, but it didn't) flight └─ flight_booking ├─ app │ ├─ admin.py │ ├─ apps.py │ ├─ migrations │ │ ├─ 0001_initial.py │ │ ├─ __init__.py │ │ └─ __pycache__ │ │ ├─ 0001_initial.cpython-39.pyc │ │ └─ __init__.cpython-39.pyc │ ├─ models.py │ ├─ templates │ │ ├─ app │ │ │ ├─ book_flight.html │ │ │ └─ search_fights.html │ │ └─ base.html │ ├─ tests.py │ ├─ urls.py │ ├─ views.py │ ├─ __init__.py │ └─ __pycache__ │ ├─ admin.cpython-39.pyc │ ├─ apps.cpython-39.pyc │ ├─ forms.cpython-39.pyc │ ├─ models.cpython-39.pyc │ ├─ urls.cpython-39.pyc │ ├─ views.cpython-39.pyc │ └─ __init__.cpython-39.pyc ├─ db.sqlite3 ├─ flight_booking │ ├─ asgi.py │ ├─ settings.py │ ├─ urls.py │ ├─ views.py │ ├─ wsgi.py │ ├─ __init__.py … -
Uploading file in django but in data base it just save its nome and didnot found any file in media folder
I am new in Django I am working on a project where user will able to add file name and its file file can be **doc, img, pdf, csv ** i want that to be saved but when i upload them they didn't get saved here is my code **model.py** class Resources(models.Model): resource_name = models.CharField(max_length=255) rec_file = models.FileField(upload_to = "resources/", max_length=10000, null=True, default=None) created_at = models.DateField(auto_now=True) **view.py** def add_resources(request): title="Add Resources" requesturl = request.get_full_path title = 'Create Clinic' if request.method == "POST": resource_name = request.POST.get('resource_name') resource_file = request.POST.get('resource_file') resource_instances = Resources.objects.create( resource_name = resource_name, rec_file = resource_file ) resource_instances.save() return render(request, 'add_resources.html',{'title':title, 'requesturl':requesturl}) **setting.py** MEDIA_ROOT = BASE_DIR/"media" MEDIA_URL = "/media/" **url.py** from django.conf import settings from django.conf.urls.static import static if settings.DEBUG: urlpatterns+=static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) when i upload the file it just save the file name and nothing is saved in the media folder please help thank you -
How to count row from backref in template?
I have a question. I need to count MemePositiveRating for Meme in template. I try meme.memeratingpositive|length but not working. There is any idea to do it with Abstract layer in models ? home.html <a class="mr-2" href="#">{{ meme.memeratingpositive|length }}</a> models.py class Meme(models.Model): title = models.CharField(max_length=100) meme = models.ImageField(upload_to='memes') creation_date = models.DateField(default=timezone.now) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) def __str__(self): return f'Meme id: {self.id}' class MemeRating(models.Model): meme = models.ForeignKey(Meme, on_delete=models.CASCADE, related_name = 'ratings', blank = True, null = True) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) class Meta: abstract: True class MemeRatingPositive(MemeRating): pass class MemeRatingNegative(MemeRating): pass views.py class HomeView(ListView): template_name = 'meme/home.html' model = Meme context_object_name = 'memes' def get_queryset(self): return Meme.objects.filter(memestatus__is_in_moderating_room=False, memestatus__is_in_waiting_room=False) -
SELECT app_product.id FROM app_product left JOIN app_order ON app_product.id = app_order.product_id GROUP BY app_product.id
this is sql quary how to convert in django orm please given this problem solution -
how to merge excel file with python django
i use google translation I am making a website using Django. I am trying to upload 4 excel files so that one excel file can be downloaded. After defining the views.py function for each file, modifying the Excel file and then defining a function that merges the files into one, implements the download function. Excel editing for each file is possible, but the merge function is not implemented, so I ask a question. Current code is below(ignore the korean) views.py import pandas as pd from django.shortcuts import render, HttpResponse, redirect from io import BytesIO def index(request): return render(request, "index.html") def health_upload(request): if request.method == "POST": file = request.FILES.get("health_input") 건강2 = pd.read_excel(file) 건강2.rename(columns= {"성명" : "근로자명"} , inplace=True) 건강2.rename(columns= {"주민등록번호" : "생년월일"} , inplace=True) 건강2["생년월일"] = 건강2["생년월일"].str[: -8] 건강2 = 건강2.set_index(["근로자명", "생년월일"]) 건강기본 = 건강2.iloc[: , -1 : ].copy() 건강기본["개인부담금"] = 건강기본.가입자총납부할보험료 건강기본["사업주부담금"] = 건강기본.가입자총납부할보험료 건강기본.drop(columns = ["가입자총납부할보험료"], inplace=True) return render(request, "index.html") def national_upload(request): if request.method == "POST": file2 = request.FILES.get("national_input") aaa = pd.read_excel(file2) aaa.rename(mapper = {"가입자명" : "근로자명"}, axis="columns", inplace=True) aaa.rename(mapper = {"주민번호" : "생년월일"}, axis="columns", inplace=True) aaa["생년월일"] = aaa["생년월일"].str[: -8] 국민기본 = aaa.set_index(["근로자명", "생년월일"]) 국민기본 = 국민기본.iloc[: , -1 : ].copy() 국민기본["개인부담금"] = 국민기본.결정보험료/2 국민기본["사업주부담금"] = 국민기본.결정보험료/2 국민기본.drop(columns = … -
django.db.utils.IntegrityError: (1215, 'Cannot add foreign key constraint') in Django
It is my first time encountered this error, I've implemented it multiple times on my different projects and migrated to database it works fine , but just this one returns me an error, when I tried to migrate my models.py it says: django.db.utils.IntegrityError: (1215, 'Cannot add foreign key constraint') Now I have UserDetails class which linked to the AuthUser of Django migration I tried it multiple times in previous projects but this one has an error, I don't know the real issue here. class AuthUser(models.Model): //comes from the command : python manage.py inspectdb > models.py password = models.CharField(max_length=128) last_login = models.DateTimeField(blank=True, null=True) is_superuser = models.IntegerField() username = models.CharField(unique=True, max_length=150) first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) email = models.CharField(max_length=254) is_staff = models.IntegerField() is_active = models.IntegerField() date_joined = models.DateTimeField() class Meta: managed = False db_table = 'auth_user' class UserDetails(models.Model): user_id = models.OneToOneField(AuthUser, on_delete=models.CASCADE) middle_name = models.CharField(max_length=128, blank=True, null=True) birthdate = models.DateField(blank=True, null=True) sex = models.CharField(max_length=128, blank=True, null=True) address = models.CharField(max_length=128, blank=True, null=True) position = models.CharField(max_length=128, blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) class Meta: managed = True db_table = 'user_details' -
Reactjs - Axios instance - withCredentials not working
I made a view in ReactJS to edit the user profile, and started to use axios like this: //profile.js axios.post("/api/user/update/",{ withCredentials: true, username: newUsername, email: newEmail, lang: "", }).then... This is working perfectly well as the credentials are sent with the request, however when making an axios instance like that: //axiosInstance.js const API = axios.create({ withCredentials: true, baseURL: django_base_url + "/api/", }) export default API; //profile.js API.post("user/update/", { username: newUsername, email: newEmail, lang: "", }).then... The credentials are not sent with the request and I get a 403 from my django backend that says that it's missing the CSRF_TOKEN. React and Django are not running on the same url (:8000 django :3000 React), I already set the proxy to :8000 in my package.json. I also tried to force the credentials this way API.defaults.withCredentials = true; but without any success either. I am confused on why the instance doesn't work when it does without it? I'm just trying to force the credentials on every axios request. -
Quiz django. Can't get answers to the questions
I'm new to django and I don't understand why the answers to the questions are not displayed on the screen (although the questions themselves are displayed). Everything is also empty in the source code of the page. Help please model.py from django.utils.translation import gettext as _ class people(models.Model): CHOICES_TEST_ID = (('0', 'КСС'), ('1', 'Золотые правила'), ('2', 'MWD'), ('3', 'DD')) firstname = models.CharField(max_length=50, null=False) lastname = models.CharField(max_length=50, null=False) surname = models.CharField(max_length=50, null=False) test_id = models.CharField(max_length=10, choices=CHOICES_TEST_ID, default=0, blank=False) date_of_passage = models.DateField(_('Date'), auto_now_add=True) correct_answer = models.IntegerField(default=0) done = models.BooleanField('Тест сдан', default=False) def number_correct_answer(self): self.correct_answer += 1 class questions(models.Model): question = models.CharField('Вопрос', max_length=500, null=False) test_id = models.CharField('Идентификационный номер теста', max_length=2, null=False) def __str__(self): return self.question class Meta: verbose_name_plural = 'Вопросы' class answers(models.Model): answer = models.CharField('Ответ', max_length=200, null=False) true_answer = models.BooleanField('Правильный ответ', default=False) question = models.ForeignKey(questions, on_delete=models.CASCADE) def __str__(self): return self.answer class Meta: verbose_name_plural = 'Ответы' forms.py from .models import people, answers from django.forms import ModelForm, TextInput, RadioSelect class PeopleForm(ModelForm): class Meta: model = people fields = ['firstname', 'lastname', 'surname', 'test_id'] widgets = {'firstname': TextInput(attrs={'class': 'firstname', 'placeholder': 'Ввод'}), 'lastname': TextInput(attrs={'class': 'lastname', 'placeholder': 'Ввод'}), 'surname': TextInput(attrs={'class': 'surname', 'placeholder': 'Ввод'}), 'test_id': RadioSelect()} class AnswersForm(ModelForm): class Meta: model = answers fields = ['answer', 'true_answer', 'question'] widgets = … -
How can I add CKeditot in django ? Can anyone explain step by step?
When I tried to run python manage.py collectstatic it was now working.enter image description here I just expecting that how to add Richtexteditor in in static files -
Admin login page using Django
I'm stuck writing a login function (in the views.py file) that redirects the user to his homepage. I have created one single interface for all the users (doctor, receptionist, patient and the admin). It works for all the users except for the admin, as I'm a beginner in Django I don't know how to resolve this and I don't want to create a separate login page for the admin as well as a separate login function for him, I want to combine it all in one single function, is it possible ? Thank you for your help. This is the login function that worked for patients, doctors and receptionists: def loginpage(request): error = "" page = "" if request.method == 'POST': u = request.POST['email'] p = request.POST['password'] user = authenticate(username=u,password=p) try: if user is not None: login(request,user) error = "no" g = request.user.groups.all()[0].name if g == 'Doctor': page = "Doctor" d = {'error': error,'page':page} return render(request,'homepageDoctor.html',d) elif g == 'Receptionist': page = "Receptionist" d = {'error': error,'page':page} return render(request,'homepageReceptionist.html',d) elif g == 'Patient': page = "Patient" d = {'error': error,'page':page} return render(request,'homepagePatient.html',d) else: error = "yes" except Exception as e: error = "yes" return render(request,'login.html') This is the login function … -
What are u use in project with django.contrib.auth.models user
I wanna ask what u do when wanna create more than just name passwod and password_confirm . Like "from django.contrib.auth.models import Abstractuser class name model(Abstractuser):" and add fields what u need or use "user = models.OneToOneField(User, on_delete=models. CASCADE) " in other model,and if u can pls explain which method and why.Cause i cant find this on documentation(if u can just send me link with this topic) i dont know which method better and dont understand difference -
Django: How to also migrate the name of a Primary Key `id_seq` in PSQL database
I am using Postgres 12 with Django 4.0.x and I have a Django App named Polls with a model named Foo in polls/models.py: class Foo(models.Model): ... From the command line, I can inspect my PSQL database: python manage.py dbshell => \d List of relations Schema | Name | Type | Owner --------+-----------------------------------+----------+------- public | auth_group | table | username ... public | polls_foo | table | username public | polls_foo_id_seq | sequence | username (21 rows) Notice the polls_foo_id_seq sequence for my polls_foo table. Now I want to refactor and rename the Foo class to Bar. But I also want to change all database table and sequence names to remove the old name foo and change it to bar. So first I change my Python code in polls/models.py to: class Bar(models.Model): ... From the command line, I run: $ python manage.py makemigrations; Was the model polls.Foo renamed to Bar? [y/N] y Migrations for 'polls': polls/migrations/0002_rename_foo_bar.py - Rename model Foo to Bar $ python manage.py migrate; Operations to perform: Apply all migrations: admin, auth, contenttypes, polls, sessions Running migrations: Applying polls.0002_rename_foo_bar... OK The migration runs smoothly. Now I want to inspect the change in PSQL, so I run: $ python manage.py …