Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
tell me what it means this symbol ` ` and what programming language we can use and how we use it?
please tell me what it means for this symbol `` and what programming language we can use and how we use it? I tried a lot of documentations and I can't find answers. I'd like to know how to use it in my code. -
SMTPServerDisconnected at /auth/users/
I am currently working with Python 3.10.0 and Django 4.0 on the back end, and React/Redux on the front end. I have an app where after a user signs up, an activation email will be sent. However, the email never shows up and while visiting the backend, I see this error inside the network tab in devtools. I switched from gmail due to the work arounds that ended up not working for me so I went with SendGrid, but haven't gotten that to work yet either. From all of the posts I have seen so far, this looks right. settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'api' EMAIL_HOST_PASSWORD = 'password' DEFAULT_FROM_EMAIL = 'email@gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True auth.js // sign up function export const signup = (email, password, re_password) => async (dispatch) => { const config = { headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken, }, }; const body = JSON.stringify({ email, password, re_password }); try { const response = await axios.post( `${process.env.REACT_APP_API_URL}/auth/users/`, body, config ); dispatch({ type: SIGNUP_SUCCESS, payload: response.data, }); } catch (err) { dispatch({ type: SIGNUP_FAIL, }); } }; -
How to update a single column in MySQL using API from DRF
I want to auto-increment the value of the column upon URL hit using DRF class-based API. Proposed URL: /autoincrememt/<id>/ I have the functional API but it is returning 201 even the element to update is not present in the database. @api_view(['POST']) @permission_classes([permissions.IsAuthenticatedOrReadOnly]) def updateClick(request, uri_id): p = Url_data.objects.filter(uri_id=uri_id).update(clicks=F('clicks')+1) print("PPPP: ", p) url_obj = Url_data.objects.all() serializer = ClickSerializer(url_obj, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.status_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This is what I wrote so far... class Increment(APIView): """ Update click count when hit. * Requires token authentication. """ permission_classes = [permissions.IsAuthenticatedOrReadOnly] def patch(self, request, uri_id, *args, **kwargs): if request.method == 'PATCH': patch_url = Url_data.objects.get(uri_id=uri_id) This is also my question asked earlier. -
How to get updates from the input field in Django
I have this code in template {% block content %} <script> function onChange(value) { console.log("log") } </script> <h3>List</h3> <input type="text" placeholder="Filter by..." onchange="onChange(this.value)" value={{ searching_value }} > But it doesn't seem to work.. -
how to bulk_create in DRF Serializer to seperate django instances
I get an array of urls and the goal is to write each url as separate model instance with other constant params that are same for all urls django model: class BlockedUrl(models.Model): url = models.URLField() date_add = models.DateField(auto_now_add=True) class Meta: app_label = 'main' db_table = 'blocked_url' ordering = ['-date_add'] django view: from main.models import BlockedUrl from api.serializers import BlockedUrlSerializer class BlockedUrlsViewSet(GenericViewSet, CreateModelMixin): queryset = BlockedUrl.objects.all() serializer_class = BlockedUrlSerializer permission_classes = (AllowAny,) django serializer: class BlockedUrlSerializer(Serializer): urls = ListField(child=URLField(), min_length=1, max_length=1024) # create - to do (iter the list of urls and insert separately into model with one transaction) def create(self, validated_data): crawler = validated_data['crawler'] blocked_urls = [BlockedUrl(url=url) for url in validated_data['urls']] return BlockedUrl.objects.bulk_create(blocked_urls) # update - raise not implemented error def update(self, instance, validated_data): raise NotImplementedError but it does not work as I get AttributeError: 'list' object has no attribute 'urls' -
Python Pillow load font file .ttf from server
I am using Pillow and I need to load a font from a server, lets say AWS, I bet its possible but I'm not sure how. font = ImageFont.truetype("https://criptolibertad.s3.us-west-2.amazonaws.com/img/fonts/Roboto-LightItalic.ttf", size=40) img_draw.multiline_text((20, 200), "Watevs", font=font, fill=(255, 0, 0)) It doesn't work. How do I load the font file from a server? OSError at /courses/certificate_preview/1 cannot open resource -
Problem in passing attribute to view section
In my settings.urls of main project, the url is as follows: path('announcements/', include('Post.urls'), {'url_type':'announcement'}) In my Post app the URL is as follows: path('all', PostList.as_view()) My view section is as follows: class PostList(generics.ListCreateAPIView): permission_classes=[permissions.IsAuthenticatedOrReadOnly] queryset = Post.objects.all() serializer_class = InstructorSupportSerializer def get_queryset(self): return self.queryset.filter(post_type = self.url_type) As per as the django documentation, url_type was supposed to be passed to view section. What am I doing wrong? Here is the error: AttributeError: 'PostList' object has no attribute 'url_type' -
Django 3.2.11 LTS admin change form and change list page shows all the models
I am using django version 3.2.11, and on change form, change list page of every model it shows all the models. I have attached the image. PS: collectstatic command is run too. -
Changes list_display when choosing different filter options
I need to change the displayed columns of django model For example, I have the following model id - user - type1 - type2 - type3 - type4 And a filter with the following fields - filter1 - filter2 - filter3 How can I display only id - user - type1 fields when filter1 is selected, when filter2 is selected, display only id - user - type2 fields, when filter3 is selected, display only id - user - type3 - type4 fields, is there such a possibility in django? -
CSRF Failed HTTP header incorrect while posting with django axios
I'm getting a 403 Forbidden error while making a post request with axios to django. CSRF Failed: CSRF token from the 'X-Csrftoken' HTTP header incorrect. I am using session authentication. GET requests works fine, but POST requests are all rejected! These are my settings: PROTOCOL = "https://" if PRODUCTION else "http://" SESSION_COOKIE_DOMAIN = ".mywebsite.com" CSRF_COOKIE_NAME = "csrftoken" CSRF_USE_SESSION = True CSRF_TRUSTED_ORIGINS = [ "http://localhost:3000", "https://mywebsite.com", "https://gestione.mywebsite.com", "https://api.mywebsite.com", ] CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOWED_ORIGINS = [ f"{PROTOCOL}mywebsite.{EXT}", f"{PROTOCOL}api.mywebsite.{EXT}", f"{PROTOCOL}gestione.mywebsite.{EXT}", f"{PROTOCOL}admin.mywebsite.{EXT}", "http://127.0.0.1:3000", "http://localhost:3000", ] CORS_ALLOWED_ORIGIN_REGEXES = [ r"^https://\w+\.mywebsite\.com$", r"^http://\w+\.mywebsite\.local$", ] if PRODUCTION: SESSION_COOKIE_SECURE = True MIDDLEWARE = [ "django_hosts.middleware.HostsRequestMiddleware", "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "corsheaders.middleware.CorsMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "django_hosts.middleware.HostsResponseMiddleware", ] and my axios configuration is: const api = axios.create({ xsrfHeaderName: "X-CSRFToken", xsrfCookieName: "csrftoken", responseType: "json", withCredentials: true, baseURL: "https://api.mywebsite.com" }); What is wrong? -
Error: That Port is already in use (Heroku/Django)
When I run heroku local on my machine I get the following error: 07:44:21 web.1 | Watching for file changes with StatReloader 07:44:22 web.1 | Error: That port is already in use. [DONE] Killing all processes with signal SIGINT 07:44:22 web.1 Exited with exit code null When I run sudo lsof -i tcp:5000 This is what I see: COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME ControlCe 83303 x 19u IPv4 0x874167a5a53a48c7 0t0 TCP *:commplex-main (LISTEN) ControlCe 83303 x 20u IPv6 0x874167a5922f00af 0t0 TCP *:commplex-main (LISTEN) I've tried to kill the above processes using kill -9 but they don't seem to go away - I'm not sure if these are what are causing the issue either. Any help appreciated. -
Own django tokens authentication
I would like to have standard super user in Django app. On the other side, I have to make login system and authentication system for "users of myapp" (generate and using tokens for rest requests). So do I have to inheritate User class with my models class Worker or I can make to use tokens without that. I think that this would make that everyone can access to system as super user, because every user I make would be super user, or I have to give him some privileges? Is this necessary to inheritate AbstractBaseUser class: class Worker(AbstractBaseUser): username = models.CharField(max_length=30, unique=True, default="user") password = models.CharField(max_length=300, default="password") company = models.ForeignKey(Company, on_delete=models.RESTRICT) workerName = models.CharField(max_length=50) workerSurname = models.CharField(max_length=50) workerPhoneNumber = models.CharField(max_length=30) Or, is there any way to generate and use tokens with Worker objects, and to separate Worker accounts from super user admin account? -
Google Cloud Run, Django and "no such table" during build
I am following this tutorial to upload my existing Django project running locally on sqlite to Google Cloud Run / Postgres. I have the cloud_sql_proxy service running and can sign into Postgres. I am at the point of running the command gcloud builds submit --config cloudmigrate.yaml \ --substitutions _INSTANCE_NAME=INSTANCE_NAME,_REGION=REGION It runs for a while making good progress but then fails with: Step #2 - "apply migrations": django.db.utils.OperationalError: no such table: registration_setting Finished Step #2 - "apply migrations" ERROR ERROR: build step 2 "gcr.io/google-appengine/exec-wrapper" failed: step exited with non-zero status: 1 I do have a settings table in my registration app. But I don't understand where its missing from. Is this just the first table it's trying to create? Do I have to do something first to have it create the initial tables in Postgres? When I inspect Postgres I don't see any tables created in it. I tried wiping out my migration and pycache folders and recreating them. -
Use django-taggit package with graphene mutations
I'm using the package django-taggit with graphene-django. Initially, I was getting the error specified in this question (Don't know how to convert the Django field skills (<class 'taggit.managers.TaggableManager'>); but thanks to the answers there, I resolved the issue. However, there's another issue! I have the following mixin: class GrapheneRenderTaggitTags: """ Use this mixin to enable graphene-django correctly render django-taggit tags (as a list of strings). The corresponding model of the graphene type using this mixin should have a property `get_tags` that returns the tags of the model (e.g. obj.tags.all()) """ # Make django-taggit's TaggableManager interpretable to graphene @convert_django_field.register(TaggableManager) def convert_field_to_string(field, registry=None): print(field) print("i'm in the taggit parser function") return List(String, source='get_tags') When I use this mixin with the DjangoObjectType from graphene, it works flawlessly. However, when it comes to mutations, it raises the error Don't know how to convert the Django field skills (<class 'taggit.managers.TaggableManager'>) ! By the way, to prevent manually creating CUD mutations, I tried external packages such as graphene_django_extras, graphene_model_mutations, graphene_django_cud; but all of them raise the same error with or without the aforementioned mixin. Note that I get this error only when using the mutation classes provided by these packages. Please, what can I do to … -
How to Make Rest API Views and EndPoint URL of following Django Modol Code
it's my Django Web Code of Friend Request Functionality. We are moving to making RestAPIs of same functionalities in DjangoREST Framework. Confused how to make serializes, urls and API Views in DjangoREST API. Please Help. Code from django.db import models from userAuth.models import UserAuth class FriendList(models.Model): user = models.OneToOneField(UserAuth, on_delete=models.CASCADE, related_name="user") friends = models.ManyToManyField(UserAuth, blank=True, related_name="friends") def add_friend(self, account): """ Add a new friend. """ if not account in self.friends.all(): self.friends.add(account) self.save() def remove_friend(self, account): """ Remove a friend. """ if account in self.friends.all(): self.friends.remove(account) def unfriend(self, removee): """ Initiate the action of unfriending someone. """ remover_friends_list = self # person terminating the friendship # Remove friend from remover friend list remover_friends_list.remove_friend(removee) # Remove friend from removee friend list friends_list = FriendList.objects.get(user=removee) friends_list.remove_friend(remover_friends_list.user) def is_mutual_friend(self, friend): """ Is this a friend? """ if friend in self.friends.all(): return True return False class FriendRequest(models.Model): """ A friend request consists of two main parts: 1. SENDER - Person sending/initiating the friend request 2. RECEIVER - Person receiving the friend request """ sender = models.ForeignKey(UserAuth, on_delete=models.CASCADE, related_name="sender") receiver = models.ForeignKey(UserAuth, on_delete=models.CASCADE, related_name="receiver") is_active = models.BooleanField(blank=False, null=False, default=True) timestamp = models.DateTimeField(auto_now_add=True) def accept(self): """ Accept a friend request. Update both SENDER and RECEIVER friend lists. … -
Server Error (500) heroku-django after deveployed to heroku
After I host my site to heroku and change DEBUG = False its says: Server Error (500) even in the production Enviroment its shows me: Server Error (500) how can i solve that please ? i sees alot of docs but because i have seen it occur in different ways, solving it can be a complex things for a juniour web developer. I try to fix that by adding my domain name in the settings.py file: DEBUG = False ALLOWED_HOST = ['example.com'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', #Scial liogin Module 'social_django', #My App Module 'itouch', #Bootstrap Module 'bootstrap5', #cloudinary Module 'cloudinary', ] I install whitenoise correctly MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIR = (os.path.join(BASE_DIR, 'static'),) STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIR = ( os.path.join(BASE_DIR, 'static'),) STATIC_URL = '/static/' MEDIA_URL ='/images/' STATICFILES_DIR = [ BASE_DIR / 'static' ] MEDIA_ROOT = BASE_DIR / 'static/images' STATIC_ROOT = BASE_DIR / 'staticfiles' my urls.py in myapp: from django.urls import path from . import views urlpatterns = [ path('', views.login, name='login'), path('home', views.home, name='home'), path('logout', views.logout, name='logout'), path('add/', views.addPhoto, name='add'), path('view/<str:pk>/', views.viewPhoto, name='Photo'), ] -
How to log production database changes made via the Django shell
I would like to automatically generate some sort of log of all the database changes that are made via the Django shell in the production environment. Our code base is version controlled so if we introduce a bug, it's easy to track it back. But if a developer in the team changes the database via the Django shell which then introduces an issue, at the moment we can only hope that they remember what they did or/and we can find their commands in the Python shell. I'm particulalry interested in a solution that works with Python/Django. Ideally we would log also the Python code that triggered the data change. -
Django: how to check if user has permission before create or upadte and object
Context we have three types of users: owner, host and admin. The owner has a property that a host manages. a host should be able to create and/or update expenses to some property related to himself I already created some filters for GET method, but couldn't figure it out how to validate user before POST or PATCH... any help will be appreciated Codes here is Expense model: class Expenses(models.Model): """Model for property expenses """ property = models.ForeignKey('property.Property', on_delete=models.CASCADE) register_date = models.DateField() expense_date = models.DateField(blank=True, null=True) reason = models.CharField(blank=True, max_length=1024) description = models.CharField(blank=True, max_length=1024) supplier = models.CharField(blank=True, max_length=1024) value = models.DecimalField(decimal_places=2, max_digits=50, default=0) refund = models.DateField(blank=True, null=True) statement_image = models.ForeignKey(FileItem, on_delete=models.CASCADE) maintenance_image = models.ForeignKey(FileItem, on_delete=models.CASCADE) owner_approval = models.BooleanField(blank=True, null=True) class Meta: verbose_name_plural = "Expenses" def __str__(self): return f"Expense id: {self.id}" Serializer: class ExpensesSerializer(serializers.ModelSerializer): statement_photo = f_serializers.FileItemSerializer(required=False) maintenance_photo = f_serializers.FileItemSerializer(required=False) class Meta: model = models.Expenses exclude = [] def to_representation(self, instance): representation = super().to_representation(instance) print(instance.refund) if instance.refund is None: # condition representation['refund'] = "Pending" return representation return representation ViewSet class ExpensesViewSet(viewsets.ModelViewSet): queryset = models.Expenses.objects.all() serializer_class = serializers.ExpensesSerializer http_method_names = ['get', 'post', 'patch'] permission_classes = (IsHost | IsAdmin | IsOwner,) def get_queryset(self): user = self.request.user property_id = self.request.query_params.get('property_id') register_date = self.request.query_params.get('register_date') refund = … -
It is required that you pass in a value for the "algorithms" argument when calling decode()
The following pages are the code of projects: If i am using token = jwt.encode(payload,'secret', algorithm='HS256').decode('utf-8') statement then 'str' object has no attribute 'decode' error is occuring. Also, when I am removing and using it without .decode('utf-8') and proceeding with the further code. it is working fine. But when I am applying payload = jwt.decode(token, 'secret', algorithm=['HS256']) then It is required that you pass in a value for the "algorithms" argument when calling decode()" This above-mentioned error is occurring. Please Help me to rectify this error. This is the mentioned error that saying algorithms argument when calling decode() error should be rectified. View Page: from django.http import request, response from django.shortcuts import render from rest_framework import serializers from rest_framework.views import APIView from myusers.serializers import UserSerializer from rest_framework.exceptions import AuthenticationFailed from rest_framework.response import Response from .models import User import jwt, datetime # Create your views here. class RegisterView(APIView): def post(self,request): serializer = UserSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) class LoginView(APIView): def post(self,request): email=request.data['email'] password = request.data['password'] user = User.objects.filter(email=email).first() if user is None: raise AuthenticationFailed('User Not Found!!!') if not user.check_password(password): raise AuthenticationFailed('Incorrect Password!!!') payload={ 'id':user.id, 'exp':datetime.datetime.utcnow() + datetime.timedelta(minutes=60), 'iat':datetime.datetime.utcnow() } token = jwt.encode(payload,'secret', algorithm='HS256').decode('utf-8') response = Response() response.data={ "jwt":token } response.set_cookie(key='jwt', value=token, … -
Form wiht post method return almost fully empty queary dict python django
I am doing small project with python and django. This is my login.html: <form action="chats/login" method="post"> {% csrf_token %} <label for="usrname">Username:</label><br> <input type="text" id="usrname" name="usrname" required><br> <label for="usrname">Password:</label><br> <input type="password" id="pass" name="pass" required><br><br> <input type="submit" value="Login"> </form> <input type="button" href="register.html" value="Register"> and this is my views.py: def login(request): if request.method == "POST": username = request.POST['usrname'] password = request.POST['pass'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return render(request, "index.html", {'fname': username}) ... else: return render(request, "index.html", {'fname': username}) ... else: return render(request, "login.html") The problem here is that when I send the post method the querydict has only this: <QueryDict: {'csrfmiddlewaretoken': ['dcATRguCVcOKWy15aRRwpmTj46B1op5xu4aBxZHg3WzxiS2gYCaioauxHx2Oyaxe']}> and nothing else. Can someone explain where is my mistake? PS: Thats my urls if matters: urlpatterns = [ path('', views.index, name='index'), path('login', views.login, name='login') ] -
Django Rest Framework OAuth2 Access Token Guidance Required
I'm trying to implement OAuth and jwt token login in Django Rest Framework for practice. I'm using social-auth-app-django and djangorestframework_simplejwt. I use the basic documentation and successfully created a user using GitHub (Checked that in Django Admin) and I also created a user using Simple CreateAPIView. For login purposes, I can use simple jwt to login and retrieve the access token to call the other authenticated APIs, but how can I do the same using an OAuth logged-in user account. Another problem I'm facing is, whenever to visit http://localhost:8000/api/auth/login/github/ in the browser is prompts my login screen, after login, it redirects me to http://localhost:8000/api/auth/complete/, which returns 404 because it's not the right endpoint as per the Django default error page. It represents api/auth/complete/<str:backend>/ [name='complete'] as one of the available endpoint. When I visit /api/auth/complete/github/ the error that comes up is AuthMissingParameter at /api/auth/complete/github/. I don't have any idea what is happening. My settings.py configurations are: INSTALLED_APPS = [ --- # Plugins "rest_framework", "corsheaders", "oauth2_provider", "social_django", "rest_framework_social_oauth2", --- ] REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "oauth2_provider.contrib.rest_framework.OAuth2Authentication", "rest_framework_social_oauth2.authentication.SocialAuthentication", "rest_framework_simplejwt.authentication.JWTAuthentication", ), } AUTHENTICATION_BACKENDS = ( "rest_framework_social_oauth2.backends.DjangoOAuth2", "django.contrib.auth.backends.ModelBackend", "social_core.backends.github.GithubOAuth2", "social_core.backends.spotify.SpotifyOAuth2", "django.contrib.auth.backends.ModelBackend", ) -
Updating model with signals
now i'm trying to update field from my model with help of post_save signal. All works well in the admin page, but the field "number_of_photos" updates only after i click save button in the second time. Why is this happening? Signal code: @receiver(post_save, sender=PhotoAlbum) # noqa def count_photos(sender, created, instance, *args, **kwargs): # noqa instance.number_of_photos = instance.photos.count() signals.post_save.disconnect(count_photos, sender=PhotoAlbum) instance.save() signals.post_save.connect(count_photos, sender=PhotoAlbum) -
how to render data in django template that has been queried in backend using "__contains"
I am using django multiselect field in my model that is used to upload cases. Now I have a field in my model where the admin can select multiple categories for the same case. I have seperate pages to render this data according to the categories selected for them. I am filtering the data like this views.py law_data= Laws.objects.all().filter(sub_law_type__contains = 'ipc').order_by('-date') for law in law_data: print("\n these are the available cases : ", law.title," with sub law types : ", law.sub_law_type, "\n") return render(request, 'citation_ipc.html', {'law_data': law_data} ) here I want to filter all the cases that has ipc in it. And the result I am getting is this, which is accurate these are the available cases : dfsdf with sub law types : ipc, pocso, pmla, ni_act these are the available cases : dfgdfg with sub law types : ipc Now I am trying to render out this data in my html like this html <div id="sclimitations" class="tabcontent"> {% for data in law_data %} {% if data.law_category == 'limitations' and data.court_type == 'The Supreme Court of India' %} <div class="tab"> <div class="judge-content"> <a class="judge-ttle" href="{% url 'doc' data.pk %}">{{data.title|safe}} &nbsp <i class="fas fa-external-link-alt"></i></a><br/><br/> <p> <strong> {{data.sub_title|safe}} </strong> </p> <div … -
How to run my local django server using poetry
I am new to python/django and I am coming into an existing codebase that uses the package manager poetry. My question is simple; how do I start my local django server using poetry run? If not using poetry I understand I can just use python manage.py runserver, but when I run that in my project, I get ImportError: No module named django.core.management. The other most relevant command I ran was poetry run python manage.py runserver, but that yielded ModuleNotFoundError: No module named 'django_q'. I am literally just trying to figure out how to run poetry commands, and in this instance, start my local django server. I am decently lost, so any help with django/poetry would be very helpful. Thank you all in advance! -
Can not create super user, because foreign key can not be null
How to assign foreign key value, when creating super user in Django? I want to make new superuser using python manage.py createsuperuser command, but I get an error: ValueError: Cannot assign "<QuerySet [<Company: Company object (1)>]>": "Worker.company" must be a "Company" instance. Here is the code: class CompanyAccountType(models.Model): accountTypeName = models.CharField(max_length=50) accountTypeValue = models.IntegerField() class Company(models.Model): city = models.ForeignKey(City, on_delete=models.RESTRICT) category = models.ForeignKey(Category, on_delete=models.RESTRICT) companyAccountType = models.ForeignKey(CompanyAccountType, on_delete=models.RESTRICT) class MyAccounManager(BaseUserManager): def create_user(self, username, password): user = self.model( username=username, ) #I tried this for testing (real I would like to send id throught request), but I get error #ValueError: Cannot assign "<QuerySet [<Company: Company object (1)>]>": "Worker.company" must be a "Company" instance. companyObj = Company.objects.filter(id=1) user.company = companyObj user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, password): user = self.create_user(username=username, password = password, ) #user.company.id = 1 user.save(using=self._db) return user class Worker(AbstractBaseUser): username = models.CharField(max_length=30, unique=True, default="user") password = models.CharField(max_length=300, default="password") company = models.ForeignKey(Company, on_delete=models.RESTRICT) #blank=True workerName = models.CharField(max_length=50) workerProfileImage = models.ImageField(upload_to='images/', default = "images/defaultUser.png", null = True) USERNAME_FIELD = 'username' #REQUIRED_FIELDS = ['company'] objects = MyAccounManager() def __str__(self): return self.username def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance)