Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
keep the side dropdown menu open when i get the submenu of the main menu page
Dashboard Dashboard Manage E Money Create E Money Withdraw E Money Disburse E Money Bulk Transaction Template Report Transaction Report Transaction Pin Change Transaction Pin Profile My Profile Change Password {% if user.language == 1 %} Language: French {% else %} Language: English {% endif %} [enter image description here][1] -
Restrict roles for users management inside a Company object in Django Rest Framework
So, I have Company model like class Company(models.Model): company_name = models.CharField(max_length=150, blank=True, default='', verbose_name='Company Name') ... *other fields* And also have User model with class User(): operator_account = models.ForeignKey(Operator, on_delete=models.CASCADE, related_name='users', blank=True, null=True) Role in company = charfield with choices, can be a Manager, Regular user and Viewer ... *other fields* As you can see, in a Company I can have a multiple users with different roles. So, I need have some way to restrict users actions inside a company, base on user role and use for it serializers or viewsets. Just like if for example user has Manager role - then he will can edit company info and other users connected to company and create new users in this company and if user not Manager - he can`t create new users in company. This is a main goals, please, help! -
Trying to auto-populate a model field using JavaScript and it does not work
I have a model named Package. It has fields named, diagnosis, treatment, patient_type, max_fractions and total_package. The fields diagnosis, treatment and patient_type have foreign keys defined in separate individual classes, making diagnosis, treatment and patient_type choice fields. Now what I want is to auto-populate the max_fractions and total_package fields whenever treatment and patient_type are selected. I was suggested to use JavaScript to accomplish that. I tried and wrote the codes but to no avail. I'm trying it on max_fractions field first, when I succeed in doing that, I will do it for all the needed fields. Can anyone help me on this, it will be much appreciated. Here are my models: class Diagnosis(models.Model): diagnosis=models.CharField(max_length=30, blank=True) def __str__(self): return self.diagnosis class Treatment(models.Model): treatment=models.CharField(max_length=15, blank=True) def __str__(self): return self.treatment class PatientType(models.Model): patient_type=models.CharField(max_length=15, blank=True) def __str__(self): return self.patient_type class Package(models.Model): rt_number=ForeignKey(Patient, on_delete=CASCADE) diagnosis=models.ForeignKey(Diagnosis, on_delete=CASCADE) treatment=ForeignKey(Treatment, on_delete=CASCADE) patient_type=ForeignKey(PatientType, on_delete=CASCADE) max_fractions=models.IntegerField(default=None) total_package=models.DecimalField(max_digits=10, decimal_places=2) forms.py: class DiagnosisForm(ModelForm): class Meta: model=Diagnosis fields='__all__' class TreatmentForm(ModelForm): class Meta: model=Treatment fields='__all__' class PatientTypeForm(ModelForm): class Meta: model=PatientType fields='__all__' class PackageForm(ModelForm): class Meta: model=Package fields='__all__' widgets={ "treatment" : forms.Select(attrs={"onmouseup":"mf();"}), "patient_type" : forms.Select(attrs={"onmouseup":"mf();"}), } views.py: def package_view(request): if request.method=='POST': fm_package=PackageForm(request.POST) fm_diagnosis=DiagnosisForm(request.POST) fm_treatment=TreatmentForm(request.POST) fm_patient_type=PatientTypeForm(request.POST) if fm_package.is_valid() and fm_diagnosis.is_valid() and fm_treatment.is_valid() and fm_patient_type.is_valid(): diagnosis=fm_diagnosis.save() treatment=fm_treatment.save() … -
Integrating a QR-code-reader based on the cozmo jsQR, a javascript QR code reading library into a DJANGO project
Am a Python newbie trying to build a PYTHON DJANGO WEB APP, am trying to implement a QR code scanner functionality on my site. I am using a jQuery plugin qrcode-reader to implement a browser interface for the cozmo jsQR QR code reading library. Firstly, OUT OF THE DJANGO PROJECT The following project structure and Code works: qr |_src | |_____beep.mp3 | |_____jquery.min.js | |_____jsQR.min.js | |_____qrcode-reader.css | |_____qrcode-reader.js | |_qrcode_reader.html Part of the qrcode-reader.js file that contains code for the $.qrCodeReader.jsQRPath and $.qrCodeReader.beepPath is as follows: var qrr, // our qrcode reader singletone instance QRCodeReader = function () {}; //******************************************************* //here are the questiobale paths $.qrCodeReader = { jsQRpath: "./jsQR.min.js", beepPath: "./beep.mp3", //******************************************************* instance: null, defaults: { // single read or multiple readings/ multiple: false, // only triggers for QRCodes matching the regexp qrcodeRegexp: /./, // play "Beep!" sound when reading qrcode successfully audioFeedback: true, // in case of multiple readings, after a successful reading, // wait for repeatTimeout milliseconds before trying for the next lookup. // Set to 0 to disable automatic re-tries: in such case user will have to // click on the webcam canvas to trigger a new reading tentative repeatTimeout: 1500, // target input element … -
Docker run at Heroku using Heroko Addon: Heroku-postgresql. Error: could not translate host name "db" to address: Name or service not known
I am using docker and attempting to set up a webapp at heroku via git and set up docker container at heroku as a postgresql database via Heroku addon: heroku-posgresql and the error is generated message as "django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known". It is my first time using heroku-postgresql. What it did went wrong? heroku.yml setup: addons: - plan: heroku-postgresql build: docker: web: Dockerfile release: image: web command: - python manage.py collectstatic --noinput run: web: gunicorn config.wsgi $ heroku create $ heroku stack:set container -a peaceful-eyrie-17232 $ heroku addons:create heroku-postgresql:hobby-dev -a peaceful-eyrie-17232 $ heroku git:remote -a $ git push heroku master $ heroku run python manage.py migrate Running python manage.py migrate on ⬢ peaceful-eyrie-17232... up, run.9164 (Free) Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.8/site-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not translate host name "db" to address: Name or service not known The … -
Serializing (to json) a dictionary containing a Django queryset which contains DecimalField items
I have a Django queryset containing model objects with some fields being Decimal objects, a format that doesn't exist in json. I know how to use Django serializers to convert this queryset to json. However, I need to wrap the queryset in a dictionary before sending it to the front-end, like so: { "type": stream1", "data": queryset } Serializers don't work here. Error is "AttributeError: 'str' object has no attribute '_meta'". I understand why this is the case. What I've tried (nested json objects): I serialized the queryset and then added it to the dictionary before converting the dictionary to json. But this is inelegant since it requires the front-end to parse the dictionary first, and then parse the serialized value inside it. Makes for a poor experience. How do I serialize the dictionary containing the Django queryset in one shot? -
How to use csrf-token in POST-hyperlink?
I need to make a hyperlink in Django for a POST-request. For example, "Add to blacklist" in the menu. It's easy to do with a form with a submit button but I need a menu item not button. I found Javascript code for doing this but it gives me an error 403: CSRF token missing or incorrect. And I couldn't find understable for me information how to insert csrf-token into the Javascript function. I don't know Javascript, I write in Python. Here's the function from https://ru.stackoverflow.com/questions/65237/Вызов-метода-post-через-ссылку: <script type="text/javascript"> function postToUrl(path, params, method) { method = method || "post"; var form = document.createElement("form"); form.setAttribute("method", method); form.setAttribute("action", path); for(var key in params) { var hiddenField = document.createElement("input"); hiddenField.setAttribute("type", "hidden"); hiddenField.setAttribute("name", key); hiddenField.setAttribute("value", params[key]); form.appendChild(hiddenField); } document.body.appendChild(form); form.submit(); } </script> Here's how I call it: <a href="#" onclick="postToUrl('/account/add_to_blacklist/watched_user_id{{ message.recipient.user.id }}/next={{ request.get_full_path }}', {}, 'POST');">To blacklist</a> This is my view: class AddToBlacklistView(View): def post(self, request, watched_user_id, next_url=None, *args, **kwargs): if not next_url: next_url = '../profile.html/user_id{0}'.format(watched_user_id) if request.user.is_authenticated: try: user = User.objects.select_related("profile").get(username=request.user) watched_user = User.objects.select_related("profile").get(id=watched_user_id) except User.DoesNotExist: raise Http404 if watched_user.id == user.id: return redirect(next_url) if watched_user not in user.profile.blacklist.all(): user.profile.blacklist.add(watched_user) user.save() if watched_user.profile in user.profile.friends.all(): user.profile.friends.remove(watched_user.profile) if user.profile in watched_user.profile.friends.all(): friendship = Friendship.objects.get(user=watched_user.profile, friend=user.profile) … -
Django 'Dynamic' object storing in mongoDB
Is it possible to detect dynamically what object 'user' is sending based on its property/properties/type and after that store it into table ? I have abstract base class ConditionModel and a Concrete class Strategy which contains lists of ConditionModels. There will be many different condition model classes that will inheritance from Condition base class. Those classes will have different fields inside but still should implement the base class property and overwrite Isfulfilled method. How to create my djongo model that will accept this "dynamic different fields" ? My code: I have created abstract objects in models.py: class AbstractModelMeta(ABCMeta, type(models.Model)): pass The condition model which has only one field and one method to overwrite by child class: class ConditionModel(models.Model, metaclass=AbstractModelMeta): type = models.CharField(max_length=50) class Meta: abstract = True def __init__(self, type: str): self.type = type @abstractmethod def Isfulfilled(self) -> bool: pass And there's strategy model that will have list of Conditions type classes: class Strategy(models.Model): name = models.CharField(max_length=50) conditions = models.EmbeddedField(model_container=ConditionModel) def someMethods ( ... ) Here's an example of not abstract condition class: class SomeCondition(ConditionModel): type = models.CharField(max_length=50, default="Price") field1 = models.DecimalField(max_digits=1000, decimal_places=5) field2 = models.DecimalField(max_digits=1000, decimal_places=5) ( some other fields ) def Isfulfilled(self) -> bool: return field1 < field2 … -
what does value error in django refers , i am stuck
#ValueError: "<Profile: Profile object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used. what is value error why am i getting these , ValueError at /admin/profiles/profile/add/ "<Profile: Profile object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used. from django.db import models from django.contrib.auth.models import User from django.template.defaultfilters import slugify # Create your models here. from . utils import get_random_code class Profile(models.Model): first_name = models.CharField(max_length=200, blank=True) last_name = models.CharField(max_length=200, blank=True) user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(default="no bio...", max_length=300) email = models.EmailField(max_length=200, blank=True) country = models.CharField(max_length=200, blank=True) avatar = models.ImageField(default='avatar.png', upload_to='avatars/') friends = models.ManyToManyField(User, blank=True, related_name='friends') slug = models.SlugField(unique=True, blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def save(self, *args ,**kwargs): ex = False if self.first_name and self.last_name: to_slug =slugify(str(self.first_name ) + "" + str(self.last_name)) ex = Profile.objects.filter(slug =to_slug).exists() while ex: to_slug = slugify(to_slug+""+str(get_random_code())) ex = Profile.objects.filter(slug=to_slug).exists() else: to_slug = str(self.user) self.slug=to_slug super().save(*args ,**kwargs) #`enter code here`utlis.py file import uuid def get_random_code(): code = str(uuid.uuid4())[:8].replace('-', '').lower() return code -
Get Django objects JSONField that contains any item of list in its specific value
I have a JSONField in Django model like this: #Object1 JSONField: {"Fruits": ["banana", "cherry", "apple", "strawberry"], "Vegetables": ["broccoli", "cucumber", "eggplant"]} #Object2 JSONField: {"Fruits": ["fig", "coconut", "pear"], "Vegetables": ["broccoli", "cucumber", "eggplant"]} When I only search one item in objects it return the result correctly: def get_queryset(self, *args, **kwargs): qs = super(RecommendsListView, self).get_queryset(*args, **kwargs) qs = qs.filter(data__Fruit__icontains='cherry') # This return Object1 currectly but the problem is where I want to get those objects that their Fruits value have at least one of the items of the list: def get_queryset(self, *args, **kwargs): qs = super(RecommendsListView, self).get_queryset(*args, **kwargs) lst = ['cherry', 'coconut'] qs = qs.filter(data__Fruit__icontains=lst) # This return Object1 currectly I expect this to return both object1 and object2, but it does not return anything. -
How to not set image field as null when PUT/Patch in Django rest framework
I have a website that has users each user has his own profile, the problem is when the user wants for example edit his email or username and save this appear profile_image: The submitted data was not a file. Check the encoding type on the form. I thought that the frontend problem and I tried to edit the user username field without touch the image field in the Django rest framework API screen but it shows the same problem the user image field has a path to his image in getting but in put the image input is empty, how I can get edit the user other fields without loss the user image my view class UserProfileRetrieveUpdate(generics.GenericAPIView): serializer_class = UserProfileChangeSerializer def get(self, request, *args, **kwargs): serializer = UserProfileChangeSerializer( instance=request.user) return Response(serializer.data) def put(self, request, *args, **kwargs): user_profile_serializer = UserProfileChangeSerializer( instance=request.user, data=request.data, ) if user_profile_serializer.is_valid(): user_profile_serializer.save() print(user_profile_serializer.data) return Response(user_profile_serializer.data, status=status.HTTP_200_OK) errors = dict() errors.update(user_profile_serializer.errors) return Response(errors, status=status.HTTP_400_BAD_REQUEST) My serializer class UserProfileChangeSerializer(serializers.ModelSerializer): profile_image = serializers.ImageField() class Meta: model = Account fields = ('pk', 'email', 'username', 'UserFullName', 'bio', 'profile_image') -
how to send different html message to different email address Django python
i am currently building a contact us form on my app. i want when a user filed the form and submit it will send the user welcome message and also forward the user data to my email. i was able to use EmailMultiAlternatives to achieve sending the html template to my users with the code below. but the problem is that EmailMultiAlternatives doesn't support sending different message to different email address. i thought of using send_mass_mail but it doesn't support html content. how can i Customize EmailMultiAlternatives to send multiple message to defferent email. here is my code class Conactme(CreateView): form_class = Contactusform context_object_name = "forms" template_name = "registration/contactus.html" success_url = reverse_lazy('home') def form_valid(self, form): if form.is_valid(): email = form.cleaned_data['email'] full_name = form.cleaned_data['full_name'] purpose = form.cleaned_data['purpose'] phone = form.cleaned_data['phone'] comment = form.cleaned_data['comment'] form.save() content = {"fullname": full_name, "phone": phone, "purpose": purpose } userssubject = "Users Registrations" adminsubject = "Welcome message" html_message = render_to_string( template_name="emails/email_comfirmation.html", context=content) meg = EmailMultiAlternatives( adminsubject, full_name, EMAIL_HOST_USER, [email]) meg.attach_alternative(html_message, 'text/html') meg.send() if meg.send: return render(self.request, "registration/sucesss.html") -
Why django is not installing on ubuntu?
I am trying to install django using pipenv but failing to do so. pipenv install django Creating a virtualenv for this project... Pipfile: /home/djangoTry/Pipfile Using /usr/bin/python3.9 (3.9.5) to create virtualenv... ⠴ Creating virtual environment...RuntimeError: failed to query /usr/bin/python3.9 with code 1 err: 'Traceback (most recent call last):\n File "/home/.local/lib/python3.6/site-packages/virtualenv/discovery/py_info.py", line 16, in <module>\n from distutils import dist\nImportError: cannot import name \'dist\' from \'distutils\' (/usr/lib/python3.9/distutils/__init__.py)\n' ✘ Failed creating virtual environment [pipenv.exceptions.VirtualenvCreationException]: Failed to create virtual environment. Other info python --version Python 2.7.17 python3 --version Python 3.6.9 python3.9 --version Python 3.9.4 pip3 --version pip 21.1 from /home/aman/.local/lib/python3.6/site-packages/pip (python 3.6) Please help.Thanks -
A Django query to find top 3 posts with maximum comments
here are my models BlogPost Comments post = models.ForeignKey('BlogPost', null=False, on_delete=models.CASCADE) -
Jquery ajax call not working in django application for dependent drop down
I am trying to fetch localities based on the city in my django application using jquery ajax call but this does not seem to be working. What is actually going wrong here? Help html <h1>Dependent Dropdown</h1> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("#selectcities").change(function () { const city_id = $(this).val(); $.ajax({ url: '/getdetails', data: { 'city_id': city_id }, success: function (data) { console.log(data) $("#selectlocalities").html(data); } }); }); </script> <form action="/submit/" method="POST"> <h4>Select city</h4> <select id="selectcities" name="selectcity"> <option selected>Select City</option> {% for city in cities %} <option val="{{ city.id }}">{{city.name}}</option> {% endfor %} </select> <h4>Select Locality</h4> <select id="selectlocalities" name="selectlocality"> <option selected>Select Locality</option> </select> <input type="submit" class="btn btn-dark btn-lg"> </form> views.py def pageload(request): cities=city.objects.all() context={'cities': cities} return render(request,'index.html',context) def load_localities(request): city_id = request.GET.get('city_id') localities = locality.objects.filter(city_id=city_id).all() context={'localities':localities} return render(request, 'locality_dropdown_list_options.html',context) -
i Have a error in Django ,i deploy my weab app in heroku
[enter image description here][1] Help Me [1]: https://i.stack.imgur.com/fTgYO.jpg -
use serializer in that model properties
can i use serializer in that model properties? I have (most likely due to a circular import) Error for use curcular. ImportError: cannot import name 'Customer' from partially initialized module -
SQL error while making email field required and unique in Django
I'm developing an ReST API using DRF. I'm currently working on authentication module. I am using Djsoer to provide authentication API middle-ware. I am using token based authentication as it provides auto-logout (not provided by JWT). Library Version Python : 3.9 Django : 3.2.3 DRF : 3.12.4 Djsoer : 2.1.0 I'm currently using Postgres 13 for development but system is expected to work on all major SQL DB provider (i.e. Postgres, Oracle, MySQL and MsSQL) in production Windows 10 64-bit is used during development and Ubuntu or CentOS will be used for production deployment. I'm making email field required (null=False, blank=False) and unique. To do this I have extended AbstractUser model class in a custom user model created by me. The extended class hold additional user related information like phone number, etc. I refereed the following stack overflow article : Django: Make user email required User-Profile Model : from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ from phonenumber_field.modelfields import PhoneNumberField # Create your models here. class UserModel(AbstractUser): class Meta : db_table = 'user_profile' email = models.EmailField(_('email address'), null=False, unique=True, blank=False) mobile_number = PhoneNumberField(null=False, blank=True) whats_app_number = PhoneNumberField(null=False, blank=True) User-Profile Serializer: from .models import UserModel … -
/<int:id> doesn't redirect to html in django
So I have a image in html redirect to a certain url: <div class="image"> <a href="/accounts/startlistening/{{i.song_id}}"> <img src="{{i.image.url}}"> </a> </div> Here i.song_id gives a integer value. The url.py is: urlpatterns = [ url('register/', views.registration, name="signup"), url('login/', views.loginUser, name="login"), url('logout/', views.logoutUser, name="logout"), url('upload/', views.upload, name="upload"), url('startlistening/', views.startlistening, name="startlistening"), url('startlistening/<int:id>', views.player, name="player") ] The views.py for my player is: def player(request, id): song = Song.objects.filter(song_id = id).first() return render(request, 'accounts/player.html',{'song':song}) But for some reasons on runserver, on clicking the image, it changes the url but doesn't redirect to player.html Eg: on clicking it changed from http://127.0.0.1:8000/accounts/startlistening/ to http://127.0.0.1:8000/accounts/startlistening/17 but the content is same. -
how to import app rest to my app in projects django
enter image description here from mywebsite.statistical.models import ProfileUser mywebsite it is name projects and statistical.models it's path i want import to app ProfilePhoneBook -Please help me i has sister very beautiful -
Can not send email asynchronously
I have a Django view function to send email asynchronously . I think it should work asynchronously . Means return the response before sending email . But it is working synchronously. But why . Could you please help #helper function async def async_send_email(): send_a_mail = sync_to_async(send_mail) await send_mail( <subject>, <message>, <sender>, [<receiver>], fail_silently=False ) #View function async def emailSenderView(request): if request.method == 'GET': asyncio.create_task(async_send_email()) return JsonResponse({}, status=200) -
Django - inline formset data duplication
I have a create view with an inline formset. I'm trying to allow the user to create & save multiple budgets for the subprogram, it does save the budget for each row that I create but the data is the same for each regardless of what I enter in each field. Why is the data the exact same and not what I enter in each row? Views: class SubprogramCreateView(LoginRequiredMixin, CreateView): model = Subprogram form_class = SubProgramCreationForm login_url = "/login/" success_url = '/' def get_context_data(self, **kwargs): SubprogramBudgetFormSet = inlineformset_factory( Subprogram, SubprogramBudget, fields=('subprogram', 'budgetYear', 'budgetCost'), can_delete=False, extra=1, ) data = super().get_context_data(**kwargs) if self.request.POST: data['budget'] = SubprogramBudgetFormSet(self.request.POST) else: data['budget'] = SubprogramBudgetFormSet() return data def form_valid(self, form): context = self.get_context_data() budget = context["budget"] if budget.is_valid(): self.object = form.save() budget.instance = self.object budget.save() else: return self.form_invalid(form) return super(SubprogramCreateView, self).form_valid(form) Model: class SubprogramBudget(models.Model): subprogram = models.ForeignKey(Subprogram, on_delete=models.CASCADE) budgetYear = models.CharField(verbose_name="Budget Year", choices=BUDGET_YEAR_CHOICES, max_length=200) budgetCost = models.DecimalField(verbose_name="Subprogram Budget", decimal_places=0, max_digits=11) Form: class SubprogramBudgetForm(forms.ModelForm): class Meta: model = SubprogramBudget exclude = () SubprogramBudgetFormSet = inlineformset_factory(Subprogram, SubprogramBudget, form=SubprogramBudgetForm, extra=1) Template: <h2>Budget</h2> <table class="table table-light"> {{ budget.management_form }} {% for form in budget.forms %} {% if forloop.first %} <thead> <tr> {% for field in form.visible_fields %} <th scope="col">{{ field.label|capfirst }}</th> … -
how to make some fields only accessible by some type of Users in Django?
my model.py class User(AbstractUser): is_student = models.BooleanField('student status', default=False) is_creator = models.BooleanField('content creator status', default=False) is_mentor = models.BooleanField('mentor status', default=False) Here I am adding three additional fields like is_creator for superuser, is_mentor for a class mentor and is_student for a student, i want to know how to give a new user their role among from above three during signup, so that it can be checked while giving permissions -
Setting src={{form.image_url}} cannot render image but form.image_url does contain the URL (Django)
I have a list of forms which, among other fields, contain a URLField. I try, very simply, to display those images: {% extends "myapp/base.html" %} {% block extra_head %} {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'myapp/mycss.css' %}"> {% endblock %} {% block content %} {% load crispy_forms_tags %} <div class="form-group"> {% for form in forms %} <img src="{{form.image_url}}" alt="Image of product"/> # Not working {{form.image_url|as_crispy_field}} #shows image-url, thus it's not empty {% endfor %} </div> {% endblock content %} as you can see in the picture below the image is not rendered and it displays some om the HTML-code afterwards (it seems some character escaping is missing?), but it does indeed contain the URL (the url-bar below). If I copy-paste the image-url directly into src it works fine. -
Nested API testing in Django Test Framework
So, Situation is following. ParentModel -PM ChildModel Child 1 (Fk relation with "PM") Child 2 (Fk relation with "PM") .... I had built a custom API to creates all child objects when creating a Parent Object , well that is working fine(tested on POSTMAN). I was writing Test Cases for these API's but i was unable to create child objects using 1 single API that is working fine i have mentioned. I have used following Client Classes for writing test cases:- TestAPIClient APIClient etc . Can i find some standard way to test my application? Or there is any standard way to solve my problem?Please guide me.