Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django nginx 413 Request Entity Too Large
After logining the admin page it is returning 413 error (Request Entity Too Large). Than I added client_max_body_size to my /etc/nginx/nginx.conf and restarted nginx, but it didnt helped :( I know that this error is a common one, but I had to ask this question because there is no more information that about client_max_body_size. user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; client_max_body_size 100; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; # gzip_vary on; # gzip_proxied any; # gzip_comp_level 6; # gzip_buffers 16 8k; # gzip_http_version 1.1; # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; ## # Virtual Host Configs ## include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } #mail { # # See sample authentication script at: # # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript # # # auth_http localhost/auth.php; # # pop3_capabilities "TOP" "USER"; # # imap_capabilities "IMAP4rev1" "UIDPLUS"; # # server { # … -
Change the default for a model on a form
how in forms.py class, overwrite the default value of the model category, without adding it to the html form? forms.py class FastForm(forms.ModelForm): class Meta: model = Orders fields = ['device'] models.py class Orders(models.Model): device = models.CharField(max_length=150) category = models.ForeignKey('Category', default=1, on_delete=models.PROTECT) class Category(models.Model): category = models.CharField(max_length=150, db_index=True) -
Is it possible to assign jinja variable to id of an anchor tag without using javascript only in html?
HTML {%with pid='a1' %} {%endwith%} <a href="https://www.google.com/" id="{{pid}}" >Google</a> -
django.db.utils.ProgrammingError: can't adapt type 'set'
I'm using Django lookup has_key but I get the error of django.db.utils.ProgrammingError: can't adapt type 'set'. This is the part of my code where I use has_key: programs = Program.objects.values('title', 'details', 'date_added').order_by('date_added') if program.duration: programs = programs.filter(details__duration__has_key=program.duration) paginator = Paginator(programs, 10) page_obj = paginator.get_page(program.page) list(page_obj) data={ 'results': page_obj.object_list, 'total_records': paginator.count, 'page': page_obj.number, 'has_next': page_obj.has_next(), 'has_prev': page_obj.has_previous(), } return data Part of data where I use has_key query: "details": { "duration": { "full_time": { "quantity": 24, "period": "months", "description": "" } }, } How can I solve it? -
Django multiple slug urls
I have two kind of slugs: path('<slug:category_slug>/', butik_views.category_page_view), path('<slug:shop_page_slug>/', butik_views.shop_page_view), Category slugs are working fine, but if I open a shop_page URL, it looks in category view and not in the shop_page_view. Is there something i missed? regards -
how to write for action when programing with django
i want to write form action to call newpost function from viwes.py , newpost function has 2 arguments which are newpost(request,myid), but when i tried to write action="{%url 'newpost' %}" an error appears like this : TypeError at /newpost newpost() missing 1 required positional argument: 'myid' how can i send this argument in form action ? please tell me def newpost (request,myid): blockedperson=[1] assert isinstance(request, HttpRequest) print("if1") print (request.POST.get('postcontent')) print (type(request.POST.get('postcontent'))) while request.POST.get('postcontent'): print ("if2") if myid not in blockedperson : savepost=post() savepost.person_id= 437819147 savepost.content=request.POST.get('postcontent') savepost.p_date=dt.datetime.now() savepost.save() else : blocked="sorry, you are blocked, you can not share a post, for more information contact with IT on 437819147@kku.edu.sa" return render (request,'home.html',{'block':blocked}) allpost=post.objects.all() allperson=person.objects.all() allstudent=student.objects.all() allteacher=teacher.objects.all() allcomp=company_rep.objects.all() return render (request,'home.html',{'posts':allpost , 'person':allperson,'student':allstudent,'teacher':allteacher,'comp':allcomp,'id':myid}) <form name="postbox" action="{%url 'newpost' %}" method="POST" align="center"> {% csrf_token %} <label>shear your ideas, information, and experience...</label> <br /> <textarea id="post" name="postcontent" rows="4" cols="50"> </textarea> <br /> <input style="width: 31%;" type="submit" value="post" name="postsubmit"> </form> -
django.db.utils.OperationalError: no such column: home_post.assign_to_id
I want to assign a task to one of the users who commented on the post. But when I try to go on post_detail.html an error occurs, and i.e. OperationalError at /home/ no such column: home_post.assign_to_id So, here is the code snippet. I can give more information if needed. Thanks in advance! views.py def SaveAssigned(request): if request.method == "POST": if request.POST.get('assigned'): savevalue = Post() savevalue.assign_to = request.POST.get('assigned') savevalue.save() return render(request, 'post_detail.html') else: return render(request, 'post_detail.html') models.py class Post(models.Model): title = models.CharField(max_length = 100) snippet = models.CharField(max_length= 200) content = RichTextField(blank=True, null=True) date_posted = models.DateTimeField(default = timezone.now) author = models.ForeignKey(User, on_delete= models.CASCADE) category = models.CharField(max_length=255, default='Coding') assign_to = models.ForeignKey(User,related_name='assign_to', on_delete=models.CASCADE, null=True) def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('home') post_detail.html {% extends 'users/base.html' %} {% block body %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ object.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ object.author }}</a> <small class="text-muted">{{ object.category }}</small> <small class="text-muted" style="float: right;">{{ object.date_posted|date:"F d, Y" }}</small> </div> <h2 class="article-title">{{ object.title }}</h2> <p class="article-content">{{ object.content|safe }}</p> </div> </article> {% if object.author == user %} <div> <a class="btn btn-outline-secondary bt-sm mt-1 mb-1" href="{% url 'post-update' object.id %}">Update</a> <a class="btn btn-outline-danger bt-sm mt-1 mb-1" href="{% url … -
Django user created from admin panel can't authenticate
I have custom User model class User(AbstractBaseUser, PermissionsMixin): """ Модель User - пользователь сайта """ id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = models.CharField(max_length=255, unique=True, db_index=True) email = models.EmailField(max_length=255, unique=True, db_index=True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) balance = models.FloatField(default=0.0) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() def __str__(self): return self.email def tokens(self): """" Метод получения токена """ refresh = RefreshToken.for_user(self) return { 'refresh': str(refresh), 'access': str(refresh.access_token) } The admin.py file looks like this from django.contrib import admin from .models import * # Register your models here. admin.site.register(User) The login serializer looks lie this class LoginSerializer(serializers.ModelSerializer): email = serializers.EmailField(max_length=255, min_length=3) password = serializers.CharField(max_length=68, min_length=6, write_only=True) username = serializers.CharField(max_length=255, min_length=3, read_only=True) tokens = serializers.SerializerMethodField() def get_tokens(self, obj): user = User.objects.get(email=obj['email']) return { 'refresh': user.tokens()['refresh'], 'access': user.tokens()['access'] } class Meta: model = User fields = ['email', 'password', 'username', 'tokens', 'id'] def validate(self, attrs): """ Валидация email и password """ email = attrs.get('email', '') password = attrs.get('password', '') user = auth.authenticate(email=email, password=password) if not user: raise AuthenticationFailed('Invalid credentials, try again') if not user.is_active: raise AuthenticationFailed('Account disabled, contact admin') if not user.is_verified: raise AuthenticationFailed('Email is not verified') return { 'email': user.email, 'username': user.username, 'tokens': … -
how to show data through input tag
I am working on a Django project .In front-end I want to add user data through input tags but I do not know how to save data through input tags A part of my register.html file is: <div class="card-body"> <h2 class="title">Registration Form</h2> <form method="POST">{% csrf_token %} <div class="row row-space"> <div class="col-2"> <div class="input-group"> <label class="label">Full name</label> <input class="input--style-4" type="text" name="first_name"{{form.full_name}}> </div> </div> <div class="col-2"> <div class="input-group"> <label class="label">Sur name</label> <input class="input--style-4" type="text" name="last_name"{{form.sur_name}}> </div> </div> </div> I just want the Django model field to be working in input tags -
How to get interconnected records in django?
I have a django model called Person and PersonRelation class Person(model.Models) person_name = models.charfield(max_length=255, blank=False) person_address = models.charfield(max_length=255, blank = False) class PersonRelation(model.Models): person = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='sibling_of') person_relation = models.ForeignKey(Person, on_delete=models.CASCADE) Now Lets say: SAM is Related to JOHN SMITH is Related to JOHN TOM is related to SMITH How can I get all the related siblings from the database? Required output of related siblings: SAM - JOHN - SMITH - TOM -
Why is fetch always returning undefined here?
I am working on a Unit Conversion API, and I am having a lot of issues with fetch(). My backend API is working, for example, when I call curl "http://localhost:8000/unitconv/convert?to=lb&from=kg&value=10" I get the correct response: {"units": "lb", "value": 22.04623}. Yet when I do the exact same thing with fetch(), this is what I get: I have tried both localhost and 127.0.0.1 and I still cannot get past this "undefined". What's wrong here? -
model condition in admin panel
I created several tables in models.py and in these tables I have a table named "Asset" that I added assets. my Asset table features are name, description, point geometry and line geometry. For this table, when I enter the django admin panel and add assets with "+ Add", I want an option to appear first. A or B will be selected as an option. If I press A, let only name, description and point geometry come from properties of Asset table for asset record. If I press B, the name, description and line geometry come up. How do I do this conditional choice? -
How to display Model in each HTML template?
But create a request in each functions inside views.py I do not want. Is it possible to output the model in each template using only one request? I tried to use templateetags but that so @register.simple_tag(takes_context=True) def header_categories(context): return Categorie.objects.all().order_by('id') what is like that @register.simple_tag(takes_context=True) def header_categories(context): categories = Categorie.objects.all().order_by('id') args = {} for cat in categories: args[cat.text] = { 'id':cat.id, } if cat.parent: args[cat.text]['parent_id'] = cat.parent.id args[cat.text]['parent_text'] = cat.parent.text return args Nothing works correctly {% for cat in header_categories %} cat.text {% endfor %} I tried through js var arr = {%header_categories%} but django changes everything {&#x27;dresses&#x27;: {&#x27;id&#x27;: 19}, -
FileField not populated after validation error
In my form I have several FileFields. If I provide a file with a wrong extension I get a Validation Error. When the form is reloaded the validation errors are shown. But the other FileFields with the correct filse are not populated anymore and I have to upload those file again. In other words: all the textfiels etc. are filled after reloading. I would like to have the FileFields also filled. Any ideas? Thanks in advance! views.py def artist_application(request): if request.method == 'POST': form = Form(request.POST, request.FILES) if form.is_valid(): genre = form.cleaned_data.pop('genre') instance = Artist(**form.cleaned_data) tag = Tag.objects.filter(id__exact=1).first() # add tag Artist Application instance.save() instance.tag.add(tag) for g in genre: instance.genre.add(g) return render(request, 'application_form.html', {'form': form, 'artist': instance}) else: form = ApplicationForm() return render(request, 'application_form.html', {'form': form}) application_form.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <h2>Artist Application</h2> {% if form.errors or form.non_field_errors%} <div class="errors"> <p>Please adjust the following fields:</p> {{ form.errors }} {{ form.non_field_errors }} </div> {% endif %} {% crispy form %} {% endif %} {% endblock %} forms.py from django.forms import ModelForm, BooleanField from artist_application.models import Artist, Genre from dal import autocomplete from crispy_forms.helper import FormHelper from crispy_forms.bootstrap import AppendedText from crispy_forms.layout import Layout, … -
What is the best practice of unique_together & auto-populated created_by work together?
I use the below codes for a long time and nothing is wrong. Now, when I start using djagno-rest-framework, I start wondering the way I used to do. I have a model Diary like this: class Diary(models.Model): date = models.DateField(verbose_name=_('Date'), default=today) created_by = models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Meta: unique_together = (('date', 'created_by')) With this DiaryModelForm, it works fine: class DiaryModelForm(forms.ModelForm): class Meta: model = Diary exclude = ['created_by'] def full_clean(self): super().full_clean() try: self.instance.validate_unique() except forms.ValidationError: self.add_error(field='date', error=_('The diary with this date has already existed.')) In the create/update views I use them like this: def diary_create(request): instance = Diary(created_by=request.user) if request.method == 'POST': form = DiaryModelForm(request.POST, instance=instance) if form.is_valid(): instance = form.save() def diary_update(request, pk): instance = get_object_or_404(Diary, pk=pk, created_by=request.user) if request.method == 'POST': form = DiaryModelForm(request.POST, instance=instance) if form.is_valid(): instance = form.save() They work fine. By just passing a different instance, I can easily handle logic of create/update views. The processes seems consistent. When I start using django-rest-framework, I try to convert what I do with from ModelForm to ModelSerializer, but I found that hard. Some method names (like full_clean) between thses two class are a little different. And some ways I found in their doc seems convenient, but not the … -
502 bad gateway for django site
I deployed my Django app to gcloud and everything uploads with no error but when I go on the site it comes up with a 502 bad gate way. I've checked the logs and this error pops up. textPayload: "Container called exit(1)." insertId: "6067eaaf00085f11035507b0" resource: {2} timestamp: "2021-04-03T04:10:23.548428287Z" severity: "WARNING" labels: {1} Any ideas on this? I've been stuck on this all day, I have my app.yaml done properly (to my knowledge) and the database in settings.py runs fine. -
Error after changing from sqllite3 data base to PostgreSQL
I have been running into some error after changing from sqllite3 database to PostgreSQL.Here is some of the error. ValueError at /post/None/ Field 'id' expected a number but got 'None'. Request Method: GET Request URL: http://127.0.0.1:8000/post/None/ Django Version: 3.1.6 Exception Type: ValueError Exception Value: Field 'id' expected a number but got 'None'. Exception Location: /home/mike/.local/share/virtualenvs/mercy-TKuV6FoL/lib/python3.7/site-packages/django/db/models/fields/__init__.py, line 1778, in get_prep_value Python Executable: /home/mike/.local/share/virtualenvs/mercy-TKuV6FoL/bin/python Python Version: 3.7.5 Python Path: ['/home/mike/Web/mercy', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/home/mike/.local/share/virtualenvs/mercy-TKuV6FoL/lib/python3.7/site-packages'] Server time: Sat, 03 Apr 2021 06:52:29 +0300 and here is some code in the views.py file def post(request, id): category_count = get_category_count() most_recent = Post.objects.order_by('-timestamp')[:3] post = get_object_or_404(Post, id=id) if request.user.is_authenticated: PostView.objects.get_or_create(user=request.user, post=post) form = CommentForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.instance.user = request.user form.instance.post = post form.save() context = { 'form': form, 'post': post, 'most_recent': most_recent, 'category_count': category_count, } return render(request, 'post.html', context) -
Why is my Pillow app not working with Django
I tried to include ImageField to my models in models.py of the model Topic. When I tried to migrate the model. It is not working. It says that I need to install pillow (which I did and when I tried again it is still not working. Please refer to this video The video thats shows how this doesn't work Models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Topic(models.Model): text = models.CharField(max_length = 200) date_added = models.DateTimeField(auto_now_add = True) image = models.ImageField(upload_to = 'backgroud_images', null = True, blank = True) owner = models.ForeignKey(User,on_delete = models.CASCADE) def __str__(self): return self.text class Entry(models.Model): topic = models.ForeignKey(Topic,on_delete = models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add = True) class Meta: verbose_name_plural = "Entries" def __str__(self): return self.text[:50] the INSTALLED_APPS list from settings.py.Is it because I didn't include pillows in here? INSTALLED_APPS = [ 'learning_logs', 'users', 'bootstrap4', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] -
Ubuntu/Django/Postgres degrading server performance over several hours until server becomes unresponsive
I have a website running on an AWS EC2 instance with Django and Postgres. Also I have a python script constantly running and writing to the database. CPU and RAM seem fine, but after several hours the server starts slowing down and eventually becomes unresponsive. I can't even SSH into it to check what's going on. The only option is to force reboot it. What troubleshooting would you recommend? -
How can i register my new router inside urls file
I'm working on a small project using Django Rest Framework, and I create my first application successfully called (contact), now i created a second one called List, I would like to know how can I register the router again that's what I did to register my first application called ( contact ) I created a file called router.py inside my contact/api/ router.py from django.urls import path from contact.api.views import ContactView from rest_framework import routers router = routers.DefaultRouter() router.register(r'contact', ContactView, basename="contact") and I have included router.py in my urls.py by doing : from django.contrib import admin from django.urls import path, include from contact.api.router import router urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)), ] NB : Until the moment everything is OK Now how can i register my second file router.py of my list application inside urls again -
ValueError: badly formed hexadecimal UUID string
In my system I'm trying to auto generate a unique random string for each users to be passed later on in the URL as the reference to that account and I recently read about the UUID in django models. And this is how my model looks like: class User(AbstractBaseUser, PermissionsMixin): card_number = models.CharField(max_length=20, unique=True) first_name = models.CharField(max_length=150) middle_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) address = models.CharField(max_length=200) account_code = models.UUIDField(max_length=200, default=uuid.uuid4(), editable=False) And I ran into an error when start creating superuser in the terminal: Traceback (most recent call last): File "C:\Users\User\PycharmProjects\ViajeroProject\viaje\manage.py", line 22, in <module> main() File "C:\Users\User\PycharmProjects\ViajeroProject\viaje\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 113, in handle error_msg = self._validate_username(username, verbose_field_name, database) File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 234, in _validate_username self.UserModel._default_manager.db_manager(database).get_by_natural_key(username) File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\contrib\auth\base_user.py", line 45, in get_by_natural_key return self.get(**{self.model.USERNAME_FIELD: username}) File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\db\models\query.py", line 425, in get num = len(clone) File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\db\models\query.py", line 269, in __len__ self._fetch_all() File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\db\models\query.py", line … -
Else statement is not working. Getting error: TypeError: markdown() missing 1 required positional argument: 'text'
Django code is to create an Entry Page where Visiting /wiki/title, where TITLE is the title of an encyclopedia entry, should render a page that displays the contents of that encyclopedia entry. The view should get the content of the encyclopedia entry by calling the appropriate util function. If an entry is requested that does not exist, the user should be presented with an error page indicating that their requested page was not found. But if statement is working fine, but else statement is not working. When I am browsing http://127.0.0.1:8000/wiki/CSS, it should navigate me to that dedicated page. But I am getting an error: markdown() missing 1 required positional argument: 'text'. Please advise how to mitigate this error? views.py from markdown import markdown from django.shortcuts import render from . import util #EntryPage using title def entry(request, entry): #markdowner = markdown() entryPage = util.get_entry(entry) #Displays the requested entry page, if it exists if entryPage is None: return render(request, "encyclopedia/nonExistingEntry.html", { "entryTitle": entry }) # Title exists, convert md to HTML and return rendered template else: return render(request, "encyclopedia/entry.html", { "entry": markdown().convert(entryPage), "entryTitle": entry }) urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:entry>", … -
Large software project development tips & suggestions
Can anyone give me any insight as to how they typically go about building a rather large software project with lots of moving parts? Do you start with the frontend? Backend? How do you draw out architecture for backend/state maps for frontend? Do you do this? When do you actually begin to program it? All the projects I have done, I've kind of just jumped in, but those are much smaller and are less impacted by scalability issues any help would be appreciated -
How do I render images saved in my database as a field of a model
I have a model class NewListing(models.Model): title= models.CharField(max_length= 20) image= models.ImageField(upload_to= "static", default="static/default_image.jpg", null=True) description = models.TextField() Starting_Bid= models.IntegerField() time= models.CharField(max_length= 30) and the model's form class NewListingForm(ModelForm): class Meta: model= NewListing fields= ["title", "image", "description", "Starting_Bid"] In my views.py, i want the index url to display a list of all the Listings so i wrote this def index(request): return render(request, "auctions/index.html", { "listings": list(NewListing.objects.all()) }) This is my index.html where i tried to display each listing in its own div {% for listing in listings %} <div> <h3> <a href='listings/{{listing.title}}'> {{listing.title}}</a> </h3> <p>{{listing.description}}</p> <img src='static/{{listing.image}}'> <p>{{listing.time}}</p> </a> </div> {% endfor %} The problem is whenever i try to render this page, I get a broken thumbnail instead of the image. How do i fix this? -
Django: Override for delete_selected not working
I created a custom user model (users_user) to be used instead of Django's default auth_user model. When i got to the default Admin site and open the User object, it correctly shows the list of records for my custom user model. But when I delete one of those records, it seems to be referencing the default auth_user model. I get the error: IntegrityError at /admin/users/user/ insert or update on table "django_admin_log" violates foreign key constraint "django_admin_log_user_id_c564eba6_fk_auth_user_id" DETAIL: Key (user_id)=(3) is not present in table "auth_user". users/models.py from django.db import models from PIL import Image from django.conf import settings from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) #~~~ CUSTOM USER ~~~ class UserManager(BaseUserManager): def create_user(self, email, username, password=None): print('username in UserManager.create_user(): ' + username) if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have a username') user = self.model( email=self.normalize_email(email), username=username, #todo: confirm, is this right? ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, password): """ Creates and saves a staff user with the given email and password. """ user = self.create_user( email, username=username, password=password, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, email, username, password): print('username in UserManager.create_superuser(): ' + username) """ Creates …