Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Flexible form, how can I secure it?
I know that I make form in the foms.py, put it in the context, and send it to HTML. But I want to make it possible for the user to increase and decrease the form. If I operate with the code I uploaded now, I know that it is very vulnerable to security, so I wonder how I can secure it. def debate_create(request): if request.method == "POST": # validation ckeck # section dictionary for saving request.FILES section_id = dict() # save request.POST content content = request.POST.items() for k,v in content: if k == 'sup_title': sup_title = SuperTitle() sup_title.author = request.user sup_title.super_title = v sup_title.save() sup_title_id = sup_title.id elif 'img' not in k and 'opt' not in k and 'section' in k: sub_title = Subtitle() sub_title.super_title = get_object_or_404(SuperTitle, pk = sup_title_id) sub_title.sub_title = v sub_title.save() # saving subtitle.id to dictionary section_id[f'img_{k}'] = sub_title.id elif 'section' in k and 'opt' in k: opt = SelectOption() opt.sub_title = get_object_or_404(Subtitle, pk = sub_title.id) opt.option = v opt.save() # save request.FILES content for key,item in request.FILES.items(): for image in request.FILES.getlist(key): img = Images() img.images = image img.sub_title = get_object_or_404(Subtitle, pk = section_id[key]) img.save() return render(request, 'polls/test.html') else: # change HTML index.html to debate_form.html after make … -
Kaggle Dataset command returning wrong data
Hello guys please I am trying to download dataset off kaggle through my django app. In my utils, I have this code: def search_kaggle(search_term): search_results = os.popen("kaggle datasets list -s "+search_term).read().splitlines() return search_results On my view function, I have this: def search_dataset(request): context = { } print('search dataset reached') if request.method == "POST": searchkey = request.POST["searchkey"] dtsite = request.POST["dtsite"] dtsnum = request.POST["dtsnum"] if searchkey != "": if dtsite == "kaggle": results = search_kaggle(dtsite) context['results'] = results print("Kaggle reached") if dtsite == "datagov": print("datagov") if dtsite == "uci": print("UCI") if dtsite == "googlepd": print("googlepd") else: messages.error(request, " You must select a search keyword!") return render(request, 'datasetsearch/dataset_results.html', context) When I run the code, it actually returns some data from kaggle but this data is totally different from what I get when I run the same command in CLI using: kaggle datasets list -s 'fraud detection' In the code above, the search_term = 'fraud detection' so I believe it should return the same form of data but I am getting something different. The result of the command line is the correct result. See Command line result ref title size lastUpdated downloadCount v mlg-ulb/creditcardfraud Credit Card Fraud Detection 66MB 2018-03-23 01:17:27 430457 ealaxi/paysim1 Synthetic … -
HTMX Closest #ID
I'm trying to create a dynamic form where it has chained dropdowns using Django and HTMX. here is the form class WorkModelForm(ModelForm): system = forms.ModelChoiceField(queryset=System.objects.all(), widget=forms.Select(attrs={ 'hx-get': reverse_lazy('ajax_load_subsystem'), 'hx-include': "[name='subsystem']", 'hx-target': 'closest #id_subsystem', 'hx-trigger': 'load,change', 'hx-swap': 'innerHTML', })) startDate = DateField(widget=forms.SelectDateWidget(years=['2022', '2023']), label='Start Date', initial=datetime.date.today(), ) endDate = DateField(widget=forms.SelectDateWidget(), label='End Date', initial=datetime.date.today() + datetime.timedelta(days=1)) subsystem = forms.ModelChoiceField(queryset=SubSystem.objects.all(), widget=forms.Select(attrs={ 'hx-get': reverse_lazy('ajax_filter_user'), 'hx-target': '#id_assigned_to', 'hx-include': "[name='assigned_to'],[name='system']", 'hx-trigger': 'load,change', 'hx-swap': 'innerHTML', })) class Meta: model = ListOfItems fields = ( 'id', 'system', 'subsystem', 'assigned_to', 'issueCount', 'startDate', 'endDate', 'status', 'remarks', ) def clean_data(self): data = self.clean_data[ 'issueCount', 'assigned_to', 'system', 'subsystem', 'startDate', 'endDate', 'status', 'remarks', ] return data this is the form I'm using to create and update values <form method="POST" class="tr" hx-target="this" hx-swap="outerHTML"> {% csrf_token %} {% for field in form.visible_fields %} <div class="td">{{ field }}</div> {%endfor%} {%if projects%} <div class="td"><button type="submit" hx-post="{%url 'edit-work' projects.id%}">Save</button></div> {%else%} <div class="td"><button type="submit" hx-post="."> Submit </button></div> {%endif%} </form> Is there a way to create unique ID for subsystem and assigned_to in attributes. I have tried closest TD but it is replacing the original drop down. -
Django Meta class returning an invalid attribute error when setting up verbose_plural_name
I am new to django, I'm trying to create a a diary like project and currently trying to setup the models when encountered this error. 'class Meta' got invalid attribute(s): verbose_plural_name This is my model from django.db import models from django.contrib.auth.models import User from django.utils import timezone import datetime class Diary(models.Model): owner = models.ForeignKey(User, models.CASCADE) title = models.CharField(max_length=100) date_created = models.DateTimeField(default=timezone.now) class Meta: verbose_name = "diary" verbose_plural_name = "diaries" def __str__(self): return "{}'s diary".format(self.owner) -
change django upload folder based on queryset
Gday, I'm working on a section of my data management project where users will be able to upload premade data for it to be parsed and inputted into the database. I am currently stuck on uploading files. The upload field will be on the main page for the specific dataset, which is navigated to by using the dataset id. What I would like is for any files uploaded in on that page to be saved in a directory such as "/projectroot/uploads/dataset_name". is this possible? -
how to upload files in django backend?
I am trying to create an upload file function in my website. However , i keep getting the error The submitted data was not a file. Check the encoding type on the form. I tried to create a post function in views.py. Does this mean any files that i uploaded is not considered a file ? models.py class ClinicVisit(models.Model): upload_attachment = models.FileField(null=True , blank=True, upload_to='uploads/') views.py class ClinicVisitList(generics.ListCreateAPIView): serializer_class = ClinicVisitSerializer filter_backends = [DjangoFilterBackend, filters.OrderingFilter] filterset_class = ClinicVisitFilter permission_classes = [permissions.IsAuthenticated,] pagination_class = LargeResultsSetPagination ordering = ['-created_at'] parser_class = (FileUploadParser,) def get_queryset(self): return ClinicVisit.objects.based_on_access_level(self.request.user) def post(self, request, *args, **kwargs): file_serializer = ClinicVisitSerializer(data=request.data) print(request.data) if file_serializer.is_valid(): file_serializer.save() return response.Response(file_serializer.data, status=status.HTTP_200_OK) else: return response.Response(file_serializer.errors,status=status.HTTP_400_BAD_REQUEST) serializers.py class ClinicVisitSerializer(serializers.ModelSerializer): upload_attachment = serializers.FileField() class Meta: model = ClinicVisit exclude = clinicvisit_exclude extra_kwargs = { "staff_relationship": {"required": True}, "visit_type": {"required": True}, "visit_status": {"required": True}, } -
Accessing file size get error : An error occurred (404) when calling the HeadObject operation: Not Found
I am trying to access the size of file in my django template then I get the error : Traceback (most recent call last): File "D:\Project\Project 1\env\lib\site-packages\django\template\base.py", line 875, in _resolve_lookup current = current[bit] During handling of the above exception ('FieldFile' object is not subscriptable), another exception occurred: Exception Type: ClientError at /document/list-skai Exception Value: An error occurred (404) when calling the HeadObject operation: Not Found I am using S3 as my FileField Storage. I am trying to access the size in the template with {{file.size}}. Any help? -
Axios blocked by CORS policy with Django REST Framework: 'Access-Control-Allow-Origin' header in the response must not be wildcard
Using vuejs3 ans axios, I'm trying to make a API call out to a django project, and getting a CORS error on the chrome side. Not sure what setting I'm missing here... The preflight OPTIONS response returned is ok, but chrome is upset that the 'Access-Control-Allow-Origin' header is "*". I'm using django-rest-framework with django-cors-headers. django.settings: ALLOWED_HOSTS = ["*"] # CORS CORS_ALLOW_ALL_ORIGINS = False # was initially True CORS_ALLOW_HEADERS = "*" CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = ["https://mydomain", "http://localhost:8080", "http://127.0.0.1:8080"] # Application definition INSTALLED_APPS = [ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "corsheaders", ... ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.locale.LocaleMiddleware", "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", ... ] vuejs/axios side: axios.defaults.xsrfHeaderName = 'X-CSRFToken'; axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.withCredentials = true; const url = `https://mydomin/my/endpoint/`; response = axios.get(url); I thought setting CORS_ALLOW_ALL_ORIGINS to False and defining CORS_ALLOWED_ORIGINS values would resolve the issue, but the Access-Control-Allow-Origin header is still showing as "*". Am I missing a setting? -
How to redirect django url in off business hours
There is a requirement like app should be available in business hours 9 AM -6 PM and rest time, it should redirect to just one well defined page. Can someone explain me how to achieve this. -
Get Related Data from ManyToManyField in Django
Working with ManyToManyField I want to get data of all the users related to all the queried model object along with other field data in the model. For example for the below model, I have 2 users related to this "ChatRoom" class ChatRoomParticipants(models.Model): user = models.ManyToManyField(User, related_name='chatroom_users') room = models.ForeignKey(ChatRoom, on_delete=models.PROTECT) With the below query chatrooms = list(ChatRoomParticipants.objects.filter(user=user).values('user__user_uid', 'room__id', 'room__name')) I'm able to fetch [{'user__user_uid': UUID('f4253fbd-90d1-471f-b541-80813b51d610'), 'room__id': 4, 'room__name': 'f4253fbd-90d1-471f-b541-80813b51d610-872952bb-6c34-4e50-b6fd-7053dfa583de'}] But I'm expecting something like [{'user__user_uid': UUID('f4253fbd-90d1-471f-b541-80813b51d610'), 'user__user_uid': UUID('80813b51d610-872952bb-6c34-4e50-b6fd-7053dfa583de'), 'room__id': 4, 'room__name': 'f4253fbd-90d1-471f-b541-80813b51d610-872952bb-6c34-4e50-b6fd-7053dfa583de'}] I've searched and found I can do something like user_data = chatrooms.users.all().values('user_uid') But the above doesn't work well with filter and I would miss out data on room. Note: I know that's not a correct method to do what I'm trying to achieve, if anyone can enlighten with what's the correct way to achieve the same data. -
Django OAuth with Xero SDK can't access session for oauth2_token_getter and oauth2_token_saver as no request object can be passed
I am using Django with requests_oauthlib to access the Xero API using the xero-python SDK. Xero Starter Demo requests-oauthlib I am trying to use request.session to store the oauth token information. This works well on the initial call and callback, but in subsequent views when I want to load the correct token from the request.session I am hitting a problem. The Xero ApiClient (xero_python.api_client) wants me to configure two functions it can call to get and save the token in the future (oauth2_token_getter, oauth2_token_saver) (decorators are used in the demo). Those functions are called by the Xero API and take no parameters. I can create the functions no problem, and they get called correctly, but once inside the functions I have no request object so I can't access request.session to get or save the token to the session. The Xero demonstration projects use Flask which imports a root level session object (from flask import session) which can be accessed in any function, so this works fine for Flask. What is the correct way to solve this problem in Django? I have tried creating a SessionStore object but it was empty despite me knowing the data is in the request.session I … -
Django gmail api
I am working on a project that need to send out email to users. I am using google api since the less secure app in no longer available. I am following this post to set it up, at the finall stage that I need to grant access to google. python gmail.py is not does not generate token.picke file needed for the api to function. project folder layout Need help on how to go about it -
Django query getting row data based on user id that created
I need help with writing a query. A user signs up and creates a schema. I am trying to write a query that will get the schema from the user id that created it. I have two models one is named Client. models.py class Client(models.Model): name = models.CharField(max_length=100) created_on = models.DateField(auto_now_add=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE) For example: user | name ------------- 1 | test1 2 | test2 3 | test3 I am able to get the User ID, but I am unsure of how to get the name the user created. Below is my current code: views.py user_id = request.user.id user = User.objects.get(id=user_id) getTenant = Client.objects.get('name') tenant = Client.objects.filter(name=getTenant).filter(created_by=user) How can I write a Django query that will say "get name from user 1" therefore the desired output would be "test1"? And if I did "get name from user 2" the desired output would be "test2" and so on. Any and all help is appreciated. -
How to add a breed to an animal from the available breeds in django rest framework
i am looking how i can assign a breed to an animal upon the creation of an animal for example i have added many breeds to my database and now i want to clean it and assign a breed to each animal for example dogs can have rottweiler, Abradore and more in the rest framework this is how I made my serializer but it makes me create a new breed each time instead of chosing the breed from the available breeds class AnimalBreedSerializer(serializers.ModelSerializer): class Meta: model = AnimalBreed fields = ("name",) class AnimalTypeSerializer(serializers.ModelSerializer): animal_breed = AnimalBreedSerializer(many=False, read_only=True) class Meta: model = AnimalBreed fields = ("name","animal_breed") these are my models class AnimalBreed(models.Model): name = models.CharField(max_length=256, unique=True, primary_key=True) class AnimalType(models.Model): name = models.CharField(max_length=256, unique=True, primary_key=True) breed = models.ForeignKey(AnimalBreed, on_delete=models.CASCADE) -
How to make slight changes to objects related to each other without copying/creating new instances in Django
I have a Lessons Model, and I have a Challenges model. Right now they are related with foreign keys. So 1 lesson can have multiple challenges. My problem is that I want to re-use the Challenges objects in other lessons, but sometimes with very slight changes in the given challenge object. Up until now, I have just copied the challenge object, slightly changed it, and used that for the new lesson. The problem with this is that the database gets polluted with a bunch of similar objects, making it hard to scale with many lessons. -
Django: Project name is duplicated in the template path
My project structure is roughly as follows: dinnerproject/ dinnerproject/ settings.py dinners/ templates/dinners/ main.html templates/ base.html manage.py In settings.py I've got TEMPLATE configured like so: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] And dinners app is added to INSTALLED_APPS. I use a TemplateView with template_name = "main.html", which extends base.html. But when I try to open the page that's supposed to return main.html, I keep getting a TemplateDoesNotExist error saying: Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: C:\Users\User\dinnerproject\dinnerproject\templates\main.html (Source does not exist) (...) django.template.loaders.app_directories.Loader: C:\Users\User\dinnerproject\dinnerproject\dinners\templates\main.html (Source does not exist) For some reason, my project name is duplicated in the paths, so django cannot find the right directories. What am I doing wrong? -
Django allauth-django Exception Type: KeyError at /accounts/signup/ Exception Value: 'username'
I'm trying to implement a Custom User Model for allauth-django, also adding custom form and other attributes. I'm getting the error when I'm adding the 'username' field on the form class so I can style it. I also changed allauth login to use email instead of a username, so username will be used for display only. Any idea what I'm doing wrong? setting.py SITE_ID = 1 AUTH_USER_MODEL = "xmain.User" ACCOUNT_USER_MODEL_USERNAME_FIELD = "username" ACCOUNT_USER_MODEL_EMAIL_FIELD = "email" AUTHENTICATION_BACKENDS = [ # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ] ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_USER_MODEL_USERNAME_FIELD = "username" ACCOUNT_SIGNUP_REDIRECT_URL ="settings.LOGIN_REDIRECT_URL" ACCOUNT_USERNAME_BLACKLIST = ["admin","user"] ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 10 ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 1800 ACCOUNT_PASSWORD_MIN_LENGTH = 8 ACCOUNT_DEFAULT_HTTP_PROTOCOL = "https" ACCOUNT_LOGIN_ON_PASSWORD_RESET = True SOCIALACCOUNT_AUTO_SIGNUP = False ACCOUNT_FORMS = { 'login': 'xmain.forms.xMainLoginForm', 'signup': 'xmain.forms.xMainRegisterForm', } # Password validation AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] models.py from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser, PermissionsMixin ) from django.db import models # Create your models here. class UserManager(BaseUserManager): def create_user(self, … -
Python qrcode module generating qrcode with data not in source code
I'm creating an app for tracking stock using qr codes, I'm writing my app using Django and am using the qrcode module for generating qrcodes for items. In a previous version of my app the data I passed to the qrcode.make() function was different for the url it was representing. For some reason when generating the first wetsuit item, the qr code generated uses the old data for the url even though it's not present in my code. All other items work fine and any wetsuit instance after the first one generates a correct qr code with the correct data. My app is on my github here a folder named qrcodes in the static folder for the app to work correctly And the relevant code snippets: def generateQRCode(stockType, number, fileName): print(bcolors.OKGREEN+"Generating a new "+stockType+" QR code..."+bcolors.ENDC) #Generate qrcode from data qrData = 'http://192.168.0.72:8000/detail/'+stockType+'&'+str(number) print(bcolors.FAIL+qrData+bcolors.ENDC) qr = qrcode.make(qrData) print(bcolors.OKGREEN+"Saving generated QR code..."+bcolors.ENDC) path = 'static/qrcodes/'+fileName qr.save(path) if(exists(path)): return print(bcolors.OKBLUE+"Successfully generated and saved QR code!"+bcolors.ENDC) else: return print(bcolors.FAIL+"QR code failed to save!"+bcolors.ENDC) For some reason wetsuit instance 1's qrData is being generated as if the code below was written instead of what is in the snippet above: 'ip address'+stockType+'/'+brand+'&'+gender+'&'+size+'&'+number -
Django annotate average multiple columns
I have a model that has many to many fields to the same model class Project(models.Model): owner = models.ManyToManyField(User, related_name="owner_projects", blank=True) editor = models.ManyToManyField(User, related_name="editor_projects", blank=True) price = models.FloatField() So I am looking to return user average price, without knowing if the one is an owner or editor user_qs = User.objects.all().annotate( average_price = Avg(F('owner_projects') + F('editor_projects')) ) The problem is whenever one of the relationships is blank, the whole 'average_price' is returned as null. Is there a good way to average two columns on the database side? -
How to wrap a file downloading REST API with GraphQL?
I'm using Graphene and Django. And I tried to wrap the code below with GraphQL. def download(request): file_path = "/a/file/path/" if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 The wrapper looks like below (simply send an API call within the resolver): class Query(ObjectType): download_a_file = graphene.String(required=True) def resolve_download_a_file(root, info): url = info.context.build_absolute_uri(reverse("download")) response = requests.post(url) return str(response.status_code) If I send a GraphQL call, nothing is downloaded, I only get a 200 status code.If I use the REST API, I get the file. I'd like to know how I could get the file when calling the endpoint with GraphQL. -
what is the right way to use prefetch_related or select_related to achieve this in django
hey guys i have these models class Category(models.Model): name = models.charfield() class Product(models.Model): ...... class Order(models.Model): product = models.ForeigKey(Product) i want to fetch the product and the category of the product from an order instance in one query, i know that for forward foreignkey you should use select related but i don't think there's a way to fetch the product category when you use this: Order.objects.all().select_related('product') so is it right to use this one then: Order.objects.all().prefetch_related('product__category') -
Return existing csv file in django as download
I have a csv file in an assets folder with a few entries in my django project, and I want my angular frontend to be able to download this csv file. The existing examples show how to create a new csv file and send that, but I don't need to create a new csv file, I already have one, so how does the view/controller have to look? How can I return a csv file in django and make it able to be downloaded by my frontend? Please don't mention this reference, as it is not my intention to create a new csv file: https://docs.djangoproject.com/en/4.0/howto/outputting-csv/ -
I'm currently working on an online store website and I have a problem with updating the cart
views.py: from django.contrib.auth.decorators import login_required from django.shortcuts import render from .cart import Cart from product.models import Product def add_to_cart(request, product_id): cart = Cart(request) cart.add(product_id) return render(request, 'cart/partials/menu_cart.html') def cart(request): return render(request, 'cart/cart.html') def update_cart(request, product_id, action): cart = Cart(request) if action == 'increment': cart.add(product_id, 1, True) else: cart.add(product_id, -1, True) product = Product.objects.get(pk=product_id) quantity = cart.get_item(product_id) if quantity: quantity = quantity['quantity'] item = { 'product': { 'id': product.id, 'name': product.name, 'image': product.image, 'get_thumbnail': product.get_thumbnail(), 'price': product.price, }, 'total_price': (quantity * product.price) / 100, 'quantity': quantity, } else: item = None response = render(request, 'cart/partials/cart_item.html', {'item': item}) response['HX-Trigger'] = 'update-menu-cart' return response @login_required def checkout(request): return render(request, 'cart/checkout.html') def hx_menu_cart(request): return render(request, 'cart/partials/menu_cart.html') def hx_cart_total(request): return render(request, 'cart/partials/cart_total.html') cart.html: {% extends 'main/base.html' %} {% block title %}Shopping cart | {% endblock %} {% block content %} <div class="max-w-6xl mx-auto flex flex-wrap item-start py-6 px-6 xl:px-0"> <div class="products w-full lg:w-3/4"> {% for item in cart %} {% include 'cart/partials/cart_item.html' %} {% endfor %} </div> <div class="summary w-full md:w-1/4 p-6 bg-gray-100 rounded-xl mt-3"> <h2 class="uppercase text-lg mb-5">Summary</h2> <div class="mb-6 flex justify-between"> <span class="font-semibold">Total</span> <span hx-get="{% url 'hx_cart_total' %}" hx-trigger="update-menu-cart from:body" hx-swap="innerHTML"> {% include 'cart/partials/cart_total.html' %} </span> </div> <a href="{% url 'checkout' %}" class="inline … -
DRF - Relate an object to another using views, serializers and foreign key
Basically I have two models with one-to-one relationship. And I want retrieve information from one, when I call the other. My models: class Customer(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class CurrentAccount(models.Model): customer_account = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='customer_account', blank=True, null=True) balance = models.FloatField() So I can just call an POST and create an Customer, that customer will have id, first_name and last_name. For now everything is working. But when I try to call my endpoint to create an CurrentAccount informing my Customer to relate, nothing happens. My input: { "customer_account": 1 #this is some id from an Customer that is already created, "balance": 0.0 } The output that I expected: { "id": 42, "customer_account": { "id": 2, "first_name": "Michele", "last_name": "Obama" } "balance": 0.0 } The output that I received: { "id": 4, "balance": 0.0 } As you can see, Django are ignoring the relationship (In the database the field 'customer_account_id' is null too, so isn't just an problem with my return). Here is my serializers: class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = ('id', 'first_name', 'last_name') class CurrentAccountSerializer(serializers.ModelSerializer): customer_account = CustomerSerializer(read_only=True) class Meta: model = CurrentAccount fields = ('id', 'customer_account', 'balance') And my views to create the CurrentAccount: @api_view(['GET', … -
AUTH_USER_MODEL refers to model 'account_account.CustomUser' that has not been installed
I have checked solutions for the issue for two days only with failures. I have defined a customUser in my model.py to create a login system with email. The code snippet from the model is as following. class CustomUser(AbstractUser): email = models.EmailField(unique=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ("username", ) def __str__(self): return self.username also installed my app in settings.py added AUTH_USER_MODEL INSTALLED_APPS = [ 'account.apps.AccountConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ............. AUTH_USER_MODEL = "account.CustomUser" When I ran the migrations I got the following error: Traceback (most recent call last): File "F:\Ecom\my_env\lib\site-packages\django\apps\config.py", line 270, in get_model return self.models[model_name.lower()] KeyError: 'customuser' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "F:\Ecom\my_env\lib\site-packages\django\contrib\auth\__init__.py", line 170, in get_user_model return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) File "F:\Ecom\my_env\lib\site-packages\django\apps\registry.py", line 213, in get_model return app_config.get_model(model_name, require_ready=require_ready) File "F:\Ecom\my_env\lib\site-packages\django\apps\config.py", line 272, in get_model raise LookupError( LookupError: App 'account' doesn't have a 'CustomUser' model. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "F:\Ecom\ecomProject\manage.py", line 22, in <module> main() File "F:\Ecom\ecomProject\manage.py", line 18, in main execute_from_command_line(sys.argv) File "F:\Ecom\my_env\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "F:\Ecom\my_env\lib\site-packages\django\core\management\__init__.py", line 420, in execute django.setup() File "F:\Ecom\my_env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "F:\Ecom\my_env\lib\site-packages\django\apps\registry.py", …