Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to translate dates and date times in django rest framework?
I want to translate dates and times to current language. I don't know how to combine current language with translation with dates. So what is the best way to translate dates in django rest framework? -
Django's authenticate method returns 'None' for a an already saved User
Settings.py AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) Tests.py which has the code triggering the error class LoginTest(TestCase): def test_can_redirect_to_user_page_if_authentificated(self): test_user = User(username='foo', password='bar', first_name='Testy', last_name='McTestingTon', email='testy@email.com', is_active=True) test_user.save() current_user = authenticate(username=test_user.username, password=test_user.password) print(current_user) response = self.client.post('/login', data = {'username' : current_user.username, 'password' : current.password}) self.assertEqual(response.url, '/users/Testy') current_user is always returned as None I've tried numerous advices from other posts here on SO but authenticate still returns None for a user whose is_active I've explicitly set to True and with the ModelBackend added to my settings.py. -
Django Form Tools not Working with Dynamic Formsets
Anyone who has worked with integrating Django formtools with Dynamic Formsets? I have 7 forms in my form wizard and in one of the forms I am trying to add/remove as many questions as I can dynamically. However, when I submit the wizard, only one of the questions (last text input) gets saved regardless of how many I have added. Below is my wizard view class JobWizard(SessionWizardView): form_list=[JobForm7FormSet,JobForm1,JobForm2,JobForm3, JobForm4,JobForm5,JobForm6 ] file_storage= FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'jobs')) template_name="jobs/jobforms.html" def get_template_names(self): return [TEMPLATES[self.steps.current]] def done(self, form_list, form_dict, **kwargs): form_dict = self.get_all_cleaned_data() categories = form_dict.pop('categories') sub_categories = form_dict.pop('sub_categories') # job_question=form_dict.pop('formset-0', None) # print(job_question1) print("_________________________") job_question = form_dict.pop('job_question') job=Job.objects.create(**form_dict) job.categories=categories job.job_question=job_question print("_________________________") for sub_category in sub_categories: job.sub_categories.add(sub_category) # for question in job_question: # job.job_question.append(question) job.save() return redirect('job_list') And my forms.py is as below. I am using model forms and creating a formset from the model form. class JobForm7(forms.ModelForm): class Meta: model = Job fields = ['job_question'] JobForm7FormSet = modelformset_factory(Job,extra=1,max_num=10, fields=('job_question',), form=JobForm7) The rendering in my template as below: {% block content %} <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p> <form action="" method="post" enctype="multipart/form-data" id="job-question">{% csrf_token %} <table> {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form |crispy … -
get foreign key values drf django
every thing working just want to modify the views: models.py: class TypeOfCity(models.Model): key = models.CharField(verbose_name=_("key"), max_length=15, unique=True) value = models.CharField(verbose_name=_("value"), unique=True, max_length=15) status = models.SmallIntegerField(_("status:1 for Active; 0: Inactive"), default=1) def __str__(self): return self.key class CityTier(models.Model): key = models.CharField(verbose_name=_("key"), max_length=10, unique=True) value = models.CharField(verbose_name=_("value"), unique=True, max_length=10) status = models.SmallIntegerField(_("status:1 for Active; 0: Inactive"), default=1) def __str__(self): return self.key class City(BaseModel): name = models.CharField(_("City Name"), max_length=80, null=False, blank=False) state_name = models.ForeignKey(State, to_field="uid", on_delete=models.DO_NOTHING, max_length=55, null=False, blank=False) city_type = models.ForeignKey(TypeOfCity, to_field="key", on_delete=models.DO_NOTHING, max_length=15, null=False, blank=False) city_tier = models.ForeignKey(CityTier, to_field="key", on_delete=models.DO_NOTHING, max_length=10, null=False, blank=False) status = models.SmallIntegerField(_("Status: 1 for Active; 0:Inactive"), default=1) serializers.py: class TypeOfChoiceSerializer(serializers.ModelSerializer): class Meta: model = TypeOfChoice fields = ('value',) class CityTierSerializer(serializers.ModelSerializer): class Meta: model = CityTier fields = ('value',) class CitySerializer(serializers.ModelSerializer): city_type = TypeOfChoiceSerializer(read_only=True) city_tier = CityTierSerializer(read_only=True) def get_typeofchoices(self,obj): return TypeOfChoiceSerializer(TypeOfChoice.objects.all()).data def get_city_tiers(self,obj): return CityTierSerializer(CityTier.objects.all()).data class Meta: model = City fields = '__all__' views.py: @api_view(['POST']) def cityList(request): queryset = City.objects.all() serializer_obj = CitySerializer(queryset, many=True) return HttpResponse(serializer_obj.data) output: [{ "id": 1, "city_type": { "value": "Normal City" }, "city_tier": { "value": "Tier I" }, "name": "test", "status": 1, }] i'm expecting output like this: [{ "id": 1, "city_type": "Normal City", "city_tier": "Tier I", "name": "test", "status": 1, }] or just add … -
What Is The Best Way To Store User Details After Login?
I Try To Develop School Management System , Each Teacher Will Be Having Its Own Role And Department And Class Her/his Belong . I Finish To Build Authentication (login And Logout ) . Using Django Restframework And Jwt The Problem I Face Is When Teacher After Login In I Want To Store His/her Profile Details Through Multiple Page So When Teacher Doing Certain Action In A Certain Model It Will Be Easy To Know A Certain Action Has Been Done By This Teacher . I Use Django And Angular 8 As Front End Thanks. -
How to query in django view to add two numbers?
I want to query in view.py such that I can display the sum of two integers input by the client. I can't seem to find a way on how to add numbers entered by client and display on server. Any suggestion on how to approach this problem will be real helpful. If any query related to question please ask, I will try to make it clearer. Models.py:: from django.db import models from django.conf import settings class Addition(models.Model): name = models.CharField(max_length=10) int1 = models.IntegerField(default=True) int2 = models.IntegerField(default = True) Form.py:: from django import forms from . models import Addition class AdditionForm(forms.ModelForm): class Meta: model = Addition fields = [ 'name', 'int1', 'int2', ] Serializer.py:: from rest_framework import serializers from . models import Addition, Subtraction class AdditionSerializer(serializers.ModelSerializer): class Meta: model = Addition fields = '__all__' View.py:: from django.shortcuts import get_list_or_404,render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from . forms import AdditionForm from . models import Addition from . serializers import AdditionSerializer from .forms import SubtractionForm from . models import Subtraction from . serializers import SubtractionSerializer class AdditionList(APIView): def get(self,request): additions = Addition.objects.all() serializer = AdditionSerializer(additions,many = True) return Response(serializer.data) class AdditionListForm(APIView): def post(request): form = AdditionForm(request.POST … -
how to implement password reset in Django without using Django auth and forms
I am new to python and i want to implement reset password using emails. is it possible to make it without using Django auth and Django forms? -
CRUD operations in django rest framework having many-to-many fields relationship
I am using django rest framework for creating REST APIs. My model contains one many-to-many field and I am facing some complications in serializing it. models.py class CustomerMaster(models.Model): customer_key = models.IntegerField(db_column='CUSTOMER_KEY', primary_key=True) # Field name made lowercase. first_name = models.TextField(db_column='FIRST_NAME', blank=True, null=True) # Field name made lowercase. last_name = models.TextField(db_column='LAST_NAME', blank=True, null=True) # Field name made lowercase. email = models.CharField(db_column='EMAIL', max_length=255, blank=True, null=True) # Field name made lowercase. gender = models.TextField(db_column='GENDER', blank=True, null=True) # Field name made lowercase. dob = models.DateField(db_column='DOB', blank=True, null=True) # Field name made lowercase. phone = models.CharField(db_column='PHONE', max_length=255, blank=True, null=True) # Field name made lowercase. address = models.TextField(db_column='ADDRESS', blank=True, null=True) # Field name made lowercase. ... class Meta: managed = False db_table = 'customer_master' def __str__(self): return self.first_name + self.last_name class Segment(models.Model): name = models.CharField(max_length=100) folder = models.CharField(max_length=100) selection = JSONField() createdAt = models.DateTimeField(null=True) updatedAt = models.DateTimeField(null=True) createdBy = models.ForeignKey(User, on_delete=models.CASCADE, null=True) contact = models.ManyToManyField(CustomerMaster) def __str__(self): return self.name Serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('pk', 'email', 'first_name', 'last_name',) class CustomerEmailSerializer(serializers.ModelSerializer): class Meta: model = CustomerMaster fields = ('email', ) class SegmentSerializer(serializers.ModelSerializer): contact = CustomerEmailSerializer(many=True) createdBy = UserSerializer(required=False) class Meta: model = Segment fields = ('name', 'folder', 'selection', 'createdAt', 'updatedAt', 'createdBy', 'contact') … -
How can I add a prefix to ALL my urls in django
I want to add a prefix to all my URLs in Django python (3.0.3) so all my path that I defined in urls.py will start with "api/". The prefix may be changed in the future so I want it to be dynamic as possible -
Accessing other fields in ModelForm
I've got the following model. class FAQ(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) question = models.CharField(max_length=100, null=True, blank=False) answer = models.TextField(max_length=500, null=True, blank=False) def __str__(self): return self.user.username I've also got the following ModelForm class FAQForm (forms.ModelForm): class Meta: exclude = ('user',) model = FAQ def __init__(self, *args, **kwargs): super(FAQForm, self).__init__(*args, **kwargs) Within my model form, how can I access the the value within the user field of the FAQ model? I'd like to be able to access it under def init(self, *args, **kwargs): or super(). Thanks so much! -
django w/ uwsgi Fatal Python error: initfsencoding: Unable to get the locale encoding
I am trying to do a uwsgi installation and I get the following error Fatal Python error: initfsencoding: Unable to get the locale encoding in my logs. in my .ini I set the pythonpath $ cat /etc/uwsgi/sites/exchange.ini [uwsgi] project = exchange uid = kermit base = /home/%(uid) chdir = %(base)/www/src/%(project) home = %(base)/Env/ module = %(project).wsgi:application pythonpath = /home/kermit/www/src/exchange master = true processes = 5 socket = /run/uwsgi/%(project).sock chown-socket = %(uid):www-data chmod-socket = 660 vacuum = true but I can't tell if it is actually loaded echo $PYTHONPATH comes up empty, even when attempting from user environment in my .bashrc I have fi export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3 export WORKON_HOME=~/Env #export PYTHONPATH=~/www/src/exchange source /usr/share/virtualenvwrapper/virtualenvwrapper.sh directory structure: (secret) kermit@tuna:~ $ ls Env exchange pgp uwsgi-ini www (secret) kermit@tuna:~ $ ls Env/ get_env_details postactivate postmkproject postrmvirtualenv predeactivate premkvirtualenv secret initialize postdeactivate postmkvirtualenv preactivate premkproject prermvirtualenv (secret) kermit@tuna:~ $ ls www/ src treefrog (secret) kermit@tuna:~ $ ls www/src exchange $ cat www/src/exchange/exchange/settings.py """ Django settings for exchange project. Generated by 'django-admin startproject' using Django 2.2.7. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, … -
Django: date format management and unique_together -> 'date format "20/03/2020" is invalid. Correct format is "yyy-mm-dd"
I develop a Django project with internationalization English/French dates have to be displayed with the dd/mm/yyyy format when user webbrowser is FR and yyyy-mm-dd when user webbrowser is EN to do that, I use JS that test webbrowser user favorite language and display format accordingly That works fine until I change my model to add unique_together constraint with this date Now, I got the error when webbrowser is in french and I try to register date (asp_ent_dat) 'date format "20/03/2020" is invalid. Correct format is "yyy-mm-dd". models.py: class Entree(models.Model): asp_ent_cle = models.AutoField(primary_key=True) asp_ent_loc = models.CharField("Site concerned by the operation", max_length=10, null=True, blank=True) med_num = models.CharField("Trial batch number", max_length=3, null=True, blank=True,) asp_ent_dat = models.DateField("Entry date", null=True, blank=True) asp_ent_pro_pay = models.CharField("Country of treatment origin in case of entry", max_length=10, null=True, blank=True) asp_ent_pro_sit = models.CharField("Processing source site in case of entry", max_length=10, null=True, blank=True) opr_nom = models.CharField("Input operator", max_length=10, null=True, blank=True) opr_dat = models.DateField("Entry date", null=True, blank=True) log = HistoricalRecords() class Meta: db_table = 'pha_asp_ent' verbose_name_plural = 'Entries' ordering = ['asp_ent_cle'] unique_together = ['asp_ent_loc','med_num','asp_ent_dat'] JS: $(function(){ if(window.navigator.language == 'fr-FR' | window.navigator.language == 'fr'){ $("#id_asp_ent_dat").datepicker( { dateFormat: 'dd/mm/yy', } ); } else { $("#id_asp_ent_dat").datepicker( { dateFormat: 'yy-mm-dd', } ); }); -
UNIQUE constraint failed in django test client
I have a code like this inside tests.py: thirduser = User( username = "thirduser", password = "12345678" ) thirduser.save() third_user = Profile( user = thirduser ) third_user.save() it returns the error of UNIQUE... If I remove third_user.save() it works. But when I want to assign it to my project as project01 = Project( user = third_user, title = "prg01", description = "dsc01", category = cleaning, deadline = deadline, date_posted = date_posted, status = OPEN ) project01.save() Then it returns another error of save() prohibited to prevent data loss due to unsaved related object 'user'. Note: The user for project should be from Profile model that I have in my code. and Profile model has a field named user which is from User (from django.contrib.auth.models import User) -
'Update' in model results in overwriting
I have a code here to update a field in database which is null initially. dumlist=['ss','bb'] for ntn in imggetvalues: for datas in dumlist: imgget.update(data=datas) where imgget gives objects of the Django ORM imgget=Model.objects.filter(page_num=3) imggetvalues=[smtng for smtng in imgget] But this code only overwrites the previous entry as the inner loop runs. How can I get 1st value from dumlist to update 1st field in model object and 2nd in 2nd field,considering there are 2 objects? -
Django - How to subclass a CBV so that it will render according to a condition?
I am at a point where I need to check whether a user is using facebook or google-auth to log in or their e-mail address and password. So, before using PasswordResetView, I would like to check this and do something different according to the answer. Can somebody tell me how to subclass this CBV so that I can do check for a condition before rendering? Thanks in advance! -
How to add custom headers in django test cases?
I have implented a custom authentication class in django rest framework which requires client id and client secret on user registration in headers. I am writing test cases for user registration like this:- User = get_user_model() client = Client() class TestUserRegister(TestCase): def setUp(self): # pass self.test_users = { 'test_user': { 'email': 'testuser@gmail.com', 'password': 'Test@1234', 'username': 'test', 'company': 'test', 'provider': 'email' } } response = client.post( reverse('user_register'), headers={ "CLIENTID": <client id>, "CLIENTSECRET": <client secret> }, data={ 'email': self.test_users['test_user']['email'], 'username': self.test_users['test_user']['username'], 'password': self.test_users['test_user']['password'], 'company': self.test_users['test_user']['company'], 'provider': self.test_users['test_user']['provider'], }, content_type='application/json', ) self.assertEqual(response.status_code, status.HTTP_201_CREATED) def test_register(self): response = client.post( reverse('user_register'), headers={ "CLIENTID": <client id>, "CLIENTSECRET": <client secret> }, data={ "first_name": "john", "last_name": "williams", "email": "john@gmail.com", "password": "John@1234", "username": "john", "company": "john and co.", "provider": "email", }, content_type="application/json" ) self.assertEqual(response.status_code, status.HTTP_201_CREATED) Here is my custom authentication class:- from oauth2_provider.models import Application from rest_framework import authentication from rest_framework.exceptions import APIException class ClientAuthentication(authentication.BaseAuthentication): @staticmethod def get_client_credentials(request): try: client_id = request.headers.get('CLIENTID') client_secret = request.headers.get('CLIENTSECRET') except: raise APIException(detail="Missing Client Credentials", code=400) return { 'client_id': client_id, 'client_secret': client_secret } def authenticate(self, request): credentials = self.get_client_credentials(request) client_instance = Application.objects.filter( client_id=credentials['client_id'], client_secret=credentials['client_secret'], ).first() if not client_instance: raise APIException("Invalid client credentials", code=401) return client_instance, None But it is still giving me 500 internal … -
local variable 'post_image' referenced before assignment [duplicate]
I am very new to python and django, am making an app using beautifulsoup to extract some infos from an eCommerce site, everything worked perfectly until i tried to extract images. i added the class of the img tag and tried to extract the src but it ended up giving this error: UnboundLocalError at /new_search local variable 'post_image' referenced before assignment Request Method: POST Request URL: http://127.0.0.1:8000/new_search Django Version: 2.2.5 Exception Type: UnboundLocalError Exception Value: local variable 'post_image' referenced before assignment Exception Location: C:\Users\Ahmed\codelist\myapp\views.py in new_search, line 51 Python Executable: C:\Users\Ahmed\Anaconda3\python.exe Python Version: 3.7.4 Python Path: ['C:\\Users\\Ahmed\\codelist', 'C:\\Users\\Ahmed\\Anaconda3\\python37.zip', 'C:\\Users\\Ahmed\\Anaconda3\\DLLs', 'C:\\Users\\Ahmed\\Anaconda3\\lib', 'C:\\Users\\Ahmed\\Anaconda3', 'C:\\Users\\Ahmed\\Anaconda3\\lib\\site-packages', 'C:\\Users\\Ahmed\\Anaconda3\\lib\\site-packages\\win32', 'C:\\Users\\Ahmed\\Anaconda3\\lib\\site-packages\\win32\\lib', 'C:\\Users\\Ahmed\\Anaconda3\\lib\\site-packages\\Pythonwin'] Server time: Mon, 23 Mar 2020 07:28:15 +0000 my view.py final_postings = [] for post in post_listings: if post.find(class_='_2LFGJH'): post_title = post.find(class_='_2LFGJH').text elif post.find(class_='_2cLu-l'): post_title = post.find(class_='_2cLu-l').text else: post_title = post.find(class_='_3wU53n').text post_url = post.find('a').get('href') post_price = post.find(class_='_1vC4OE').text if post.find(class_='_1Nyybr _30XEf0'): post_image = post.find(class_='_1Nyybr _30XEf0').get('src') print(post_image) final_postings.append((post_title, post_url, post_price, post_image)) my new_search.html file {% extends 'base.html' %} {% block content %} <div class="container"> <style> .column { float: left; width: 50%; } </style> <h2 style="text-align: center">{{ search | title }}</h2> <div class="row"> <div class="column"> <h4 style="text-align: center;"><strong>Delta</strong></h4> {% for post in final_postings %} <div class="col s12"> <div … -
Django: Cannot reference a fieldname in template which contains a dot
The object which I pass from view to template has a few fields which are dynamically incremented and allocated e.g the object looks like: row = { 'id':id, 'input.object1':obj1 'input.object2':obj2 } I am trying to access the value of "input.object1" as "{{ row.input.object1 }}" in template. but the page does not show anything for this field (same for "input.object2") {% for row in row_list %} <tr> <td>{{ row.id }}</td> <td>{{ row.input.object1 }}</td> <td>{{ row.input.object2 }}</td> </tr> {% endfor %} Is there anyway to access these values in html ? Thanks in advance :) -
Better way of sending bulk requests to a remote API with Django Celery?
I have users table with 24K users on my Django website and I need to retrieve information for each of my users by sending a request to a remote API endpoint. So my plan is to use the Celery periodic tasks with a new model called "Job". There are two ways in my perspective: 1. For each user I will create a new Job instance with the ForeignKey relation to this user. 2. There will be a single Job instance and this Job instance will have a "users" ManyToManyField field on it. Then I'll process the Job instance(s) with Celery, for example I can process one Job instance on each run of periodic task for the first way above. But..there will be a huge amount of db objects for each bulk request series... Both of them seem bad to me since they are operations with big loads. Am I wrong? I guess there should be more convenient way of doing so. Can you please suggest me a better way, or my ways are good enough to implement? -
Django Admin Profile Display to the Front -End
I want to show my admin profile info to the front-end. Not editable profile just admin profile. How can I do that? -
Django - Email is not sent but its object is created in DB
When I try to send email via django, I notice that object of email is created and all fields (email, title, body) are in it, but the actual email is not sent. When I check celery logs, I see the following message: SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more `at\n5.7.8 https://support.google.com/mail/?p=BadCredentials` but I'm 100% sure that I use correct credentials and my mailbox isn't secured with two factor authentication Code in settings.py EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend" EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_USE_SSL = False EMAIL_PORT = 587 EMAIL_HOST_USER = '*******@gmail.com' # my email, I'm sure it's correct EMAIL_HOST_PASSWORD = '********' # my password, I'm sure it's correct Code in views.py (contact form where I gather needed info - email, title, body) class ContactUs(CreateView): template_name = 'my_profile.html' queryset = Contact.objects.all() fields = ('email', 'title', 'body') success_url = reverse_lazy('index') def form_valid(self, form): response = super().form_valid(form) message = form.cleaned_data.get('body') subject = form.cleaned_data.get('title') email_from = form.cleaned_data.get('email') recipient_list = [settings.EMAIL_HOST_USER, ] send_email_async.delay(subject, message, email_from, recipient_list) return response Code in tasks.py (for celery) @shared_task() def send_email_async(subject, message, email_from, recipient_list): send_mail(subject, message, email_from, recipient_list, fail_silently=False) but it doesn't really matter if it's celery or not - email is not sent itself but … -
when i add a field in model,,this is not support migrate,that time showing this error
WARNINGS: ?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default' HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon inse rtion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangop roject.com/en/3.0/ref/databases/#mysql-sql-mode Operations to perform: Apply all migrations: Hospitalapp, admin, auth, contenttypes, sessions Running migrations: No migrations to apply. -
Deploy elasticsearch + mongodb and django on different machines
I just used elasticsearch integrated with mongodb and django. I am using django-elasticsearch-dsl. I have run successfully on the same machine. Currently, I want to deploy django on one machine and elasticsearch mongodb on another machine. I transferred mongodb but with elasticsearch, I do not know how. In the settings in django, I have set: ELASTICSEARCH_DSL = { 'default': { 'hosts': 'ip-mongodb: 9200' }, } but got an error elasticsearch.exceptions.ConnectionError: ConnectionError (<urllib3.connection.HTTPConnection object at 0x7ffac85d7a58>: Failed to establish a new connection: [Errno 111] Connection refused) caused by: NewConnectionError (<urllib3.connection.HTTPConnection object at 0x7ffac85d7a58>: Failed to establish a new connection: [Errno 111] Connection refused) Hope everyone helps me solve this problem -
Need Help setting up Database Router for multiple mysql databases
I created a project that has two identical models for work from home(wfh) employees, and work from office (wfo) employees. I want wfh employee data to be stored in 'wfh' database and wfo data in 'wfo' database. Database used is mysql. However I am facing following troubles: 1) Migration fails with error: In allow_migrate() method in Router_name.py, model_name received multiple values. So I had to replace allow_migrate() method with allow_syncdb() which got rid of error and migrations were applied. 2)tables are not generated even though migrations are successful for all databases. Python shell is unable to add new employee entries to database (table does not exist error) 3)Creating superuser, after entering just the username, throws exception for improperly configured database 4)superuser created earlier (just after making project) on trying to login from admin panel gives incorrect credentials message Project Structure Project Folder | +--env | +--multi_db | +--basic_app | | | +--AuthRouter.py | +--DbRouter.py | +--models.py | +--multi_db | | | +--settings.py | +--manage.py settings.py DATABASES = { 'default': {}, 'auth_db': { 'NAME': 'auth_db', 'ENGINE': 'django.db.backends.mysql', 'HOST': '127.0.0.1', 'PORT': '3306', 'USER': '***', 'PASSWORD': '***', # connect options 'OPTIONS': {'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", }, }, 'work_from_home':{ 'ENGINE': 'django.db.backends.mysql', 'HOST': '127.0.0.1', 'PORT': '3306', … -
Adding field to serializer with 2 foreign keys
I have 2 models that look like this: class Topic(models.Model): name = models.CharField(max_length=25, unique=True) def save(self, *args, **kwargs): topic = Topic.objects.filter(name=self.name) if topic: return topic[0].id super(Topic, self).save(*args, **kwargs) return self.id class PostTopic(models.Model): topic = models.ForeignKey(Topic, on_delete=models.CASCADE) post= models.ForeignKey(Post, on_delete=models.CASCADE) If the topic is already in the Topic table, then we return the id of that topic. We do not create another. When a user submits a Post with tagged topics (think of it as hashtags), then if those topics don't exist in the Topic table they will be created along with the relationship in PostTopic That being said, here's how my serializer looks: class PostSerializer(serializers.ModelSerializer): topics = serializers.ListField( child=serializers.CharField(max_length=256), max_length=3 ) class Meta: model = Post fields = ('user', 'status', 'topics') def create(self, validated_data): topics= validated_data.pop('topics') post = Post.objects.create(**validated_data) for topic in topics: topic_id = Topic(name=topic).save() PostTopic(post_id=post.id, topic_id=topic_id).save() return post Currently, my serializer gives me an AttributeError, because topics is not a field in Post. How can I fix this so that I can make it work? If I use PostTopic then how would I get the user to give the actual topics?