Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Group by then loop
So I have products that I want to loop through display on a Django detail view. The detail view is for a particular truck that will take all the products assigned to it to a city. So all the products on the view are assigned to this particular truck. The problem is, each product is also assigned to a particular customer. So I want the view to look something like Truck 1 detail view Customer 1 Product 1 Product 2 Product 5 Customer 2 Product 3, Product 4, Produt 6 As a basic example. The real life example may have 20-30 products and 5-6 customers. Of course I could just do some kind of order by but I want the looping of these to allow me to start new style of formatting whenever there is a new customer (similar to the above format), in order to make it easier to view for the employee who will be loading this truck. Is this possible? as it's confused me a little bit. -
Django Raw Query Output Inconsistent with pgAdmin Output
I'm using django with a postgres 10 db engine to build a web based search tool via forms. When executing the queries via raw SQL in django I only receive 3 records as opposed to 902 when running the same SQL in the Ouery Tool of pgAdmin. I've tried using the django ORM to build my queries but the examples are so simple I haven't been able to successfully utilize it for my needs. Guidance on querying multiple models in the manner below would be appreciated. Django Raw SQL statement ProstateUpper = 'Prostate' ProstateLower = 'prostate' GenderMale = 'Male' GenderAll = 'All' Master_Query = Eligibilities.objects.raw('''SELECT DISTINCT ON (Eligibilities.nct_id) Eligibilities.id, Studies.brief_title, Eligibilities.nct_id, Conditions.name, Eligibilities.gender, Eligibilities.minimum_age, Eligibilities.maximum_age, Eligibilities.criteria, Interventions.intervention_type, Interventions.name, Facilities.city, Facilities.state, Facilities.country, Brief_Summaries.description, Facility_Contacts.name, Facility_Contacts.email FROM Eligibilities INNER JOIN Studies on Studies.nct_id = Eligibilities.nct_id INNER JOIN Conditions on Conditions.nct_id = Eligibilities.nct_id INNER JOIN Interventions on Interventions.nct_id = Eligibilities.nct_id INNER JOIN Facilities on Facilities.nct_id = Eligibilities.nct_id INNER JOIN Brief_Summaries on Brief_Summaries.nct_id = Eligibilities.nct_id INNER JOIN Facility_Contacts on Facility_Contacts.nct_id = Eligibilities.nct_id WHERE ((Conditions.name LIKE %s OR Conditions.name LIKE %s)) AND (gender LIKE %s OR gender LIKE %s) ''', [ProstateUpper, ProstateLower, GenderMale, GenderAll])[:1000] pgAdmin SQL statement SELECT DISTINCT ON (eligibilities.nct_id) eligibilities.id, studies.brief_title, eligibilities.nct_id, conditions.name, … -
djnago form allow users query using combination foreignkey fields in a mdel
I am new to django and was trying to learn by developing small web app. but I am stuck now and I couldn't come up with a working solution no matter I tried. I have a quiz model with three foreignkey fields: level, subject and year. The three fields uniquely identify a quiz. When the users want to take a quiz, they have to select each fields and submit a request. How can I populate the Quiz form fields with contents from Quiz model. Any suggestions would be appreciated. class Quiz(models.Model): name = models.CharField() level= models.ForeignKey() type= models.ForeignKey() year= models.ForeignKey() class Level(models.Model): level= models.CharField() class Type(models.Model): type= models.CharField() class Year(models.Model): year= models.CharField() class QuizForm(ModelForm): class Meta: model = Quiz fields = ['level', 'type', 'year'] -
Django problem - cannot get the value from the front - query value is none
I've got a problem with an basic searcher app - its about to searching the database for the value that i will be taping in the search bar. I was trying to get the solution from the internet, but there is none or its hard to find something. I was looking for some tut, but none of them works in my app. Main problem is : ValueError: Cannot use None as a query value. I know that this query is none, but i dont get it why and how. So, this is my base.html form code: <form type="GET" action="" accept-charset="utf-8"> <input type="text" name="query" placeholder="Search..."/> <input type="submit" value='Search' /> </form> views.py: class FilmListView(ListView): model = Film template_name = 'searcher/home.html' context_object_name = 'films' ordering = ['-date_posted'] paginate_by = 3 query = request.GET.get('query') queryset_list = Film.objects.filter(title__icontains=query) urls.py: urlpatterns = [ path('', FilmListView.as_view(), name='search-home'), path('films/', SearchedFilmListView.as_view(), name='searched-films'), path('user/<str:username>', UserFilmListView.as_view(), name='user-films'), path('film/<int:pk>/', FilmDetailView.as_view(), name='film-detail'), path('film/new/', FilmCreateView.as_view(), name='film-create'), path('film/<int:pk>/update/', FilmUpdateView.as_view(), name='film-update'), path('film/<int:pk>/delete/', FilmDeleteView.as_view(), name='film-delete'), path('about/', views.about, name='search-about'), ] The other thing in this app is that i have to import request to make it work. If you got any solution or any tips just help. THX for answers. -
How to dynamically filter a view by ModelChoiceField selection
I have created a template that renders a dropdown list of students. I want to filter a query set on another view to show schedule info for just the student that was selected. perm_id in student_list is primary key and perm in StudentSchedule is foreign key. Here are snippets of my models.py, forms.py and views.py models.py class StudentList(models.Model): student_name = models.CharField(max_length=45, blank=True, null=True) perm_id = models.IntegerField(primary_key=True) class StudentSchedule(models.Model): perm = models.ForeignKey(StudentList, on_delete=models.CASCADE) begin_period = models.CharField(max_length=45, blank=True, null=True) section_id = models.CharField(max_length=45, blank=True, null=True) course_title = models.CharField(max_length=45, blank=True, null=True) last_name1 = models.CharField(max_length=45, blank=True, null=True) forms.py class StudentForm(forms.Form): Student = forms.ModelChoiceField(queryset=StudentList.objects.all() .order_by('student_name')) views.py class ScheduleView(View): form_class = ScheduleForm template_name = 'learning_logs/student_schedule.html' def get(self, request): form = self.form_class(initial={}) data = StudentSchedule.objects.filter() return render(request, self.template_name, {'form': form, 'data': data}) I can do this and get student with id # 123456 data = StudentSchedule.objects.filter(perm=123456) But, I want Django to use the perm_id from the student selected from StudentList -
Django, MySQL and Microsoft Visual C++
I will directly tell what's happening: I'm trying to create a Django project in PyCharm and I'm trying to use MySQL. In my project's virtual enviroment I have installed: -Django 2.1.5 -mysql-connector-python-rf 2.2.2 -pip 18.1 -pytz 2018.9 -setuptools 40.6.3 What I yet need to install is "mysqlconnector", either I try to install it with PyCharm or Windows Cmd Console I get the following error: "error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/" In my Windows Apps I have: -Microsoft Visual C++ 2015 Redistributable(x64) - 14.0.23026.0 Extra data: - Python Version: 3.7.2 - Windows 10 x64bits - Pycharm IDE I will say again, I get this error either I try to install mysqlclient with PyCharm or Windows cmd console. Any solution? Many thanks! -
DRF Add some extra values to listview from external resource
I am overriding the def list(self, request) function of a ViewSet because i want to add some more fields to the returned Response by extracting some more info from an external API source. The merging is done through a common field of the two result sets called 'identity'. With some pseudocode below is what i want: class ExampleViewSet: def list(self, request): call_external_api = get_my_json_data_through_api() json_data = call_external_api.json() queryset = ExampleModel.objects.all() list_result = [entry.__dict__ for entry in queryset] result = {x['identity']: x for x in list_result + json_data}.values() serializer = MyCustomSerializer( data=result, many=True) serializer.is_valid() Is it a correct approach?. If yes how can i achieve my goal? -
Django model of a rent contract using Generic Foreign Key
I'm trying to model a rent contract in Django and use the admin form to insert and modify it. Both owner and tenant can be companies (VAT number) or individuals (no VAT number). Companies and individuals are stored in two different models (Company and Individual). I'm trying to solve this problem using Generic Foreign Key but I'm not able to show the tenant name in the admin page, only an integer field not friendly at all. gestimm is the name of the app and that's my oversimplified models: # my gestimm/models.py # from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models class Individual(models.Model): name = models.CharField(max_length=100, help_text='Name') def __str__(self): return self.name class Company(models.Model): name = models.CharField(max_length=100, help_text='Name') def __str__(self): return self.name class Contract(models.Model): description = models.CharField(max_length=30) start = models.DateField() stop = models.DateField() def __str__(self): return self.description class Tenant(models.Model): limit = models.Q(app_label='gestimm', model='individual') | models.Q(app_label='gestimm', model='company') contract = models.ForeignKey(Contract, on_delete=models.CASCADE, null=True, blank=True) content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT, help_text='Tenant', null=True, limit_choices_to=limit) object_id = models.PositiveIntegerField(null=True) tenant = GenericForeignKey('content_type', 'object_id') How I tried to solve the problem: # my gestimm/admin.py # from django.contrib import admin from .models import Individual, Company, Contract, Tenant class TenantInline(admin.StackedInline): model = Tenant extra = 1 class ContractAdmin(admin.ModelAdmin): … -
Django iterate on template with 2 dicts from views.py
I have the following code : views.py file : twittdict = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6} twitlistdict = {'A' : 'a', 'B': 'b', 'C': 'c'} return render(request, 'homepageapp/home.html', {'twittdict' : twittdict, 'twitlistdict' : twitlistdict}) homepage.html file : {% for user in twitlistdict %} <a href="https:*/{{ twittdict.user.3 }}"> <div class="card border-white mb-3"> <p class="card-title"><div class="media"> <img class="mr-3 align-self-center" src="https://source.unsplash.com/random/90x94"> <div class="media-body"> <h5>{{ twittdict.user.0 }}</h5> <h6>@{{ twittdict.user.1 }}</h6> <p></p> </div> </div></p> <img class="card-img-top img-fluid" src="https://source.unsplash.com/random/301x200" alt=""> <div class="card-body"> <p class="card-text">{{ twittdict.user.4 }}</p> <p class="card-text"> <hr> <i class="fas fa-retweet">{{ twittdict.user.6 }} </i> <i class="far fa-heart">{{ twittdict.user.5 }}</i> <span class="pl-5"> {{ twittdict.user.2 }}</span> </p> </div> </div> </div>{% endfor %} When i preview the page with the browser, instead of loop items ( eg: twittdict.user.2 corresponding value ), nothing is showed. Blank. How can i made this work and display correct values in the page ? Really struggling with this. Any help is greatly appreciated Thank you in advance. -
How do I write a Django ORM query where the select table shares a common column with another table?
I'm using Django and Python 3.7. I have these two models. Note they both have a similar field class Article(models.Model): publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE,) class WebPageStat(models.Model): objects = WebPageStatManager() publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE, ) score = models.BigIntegerField(default=0) I would like to write a Django ORM query that selects one of the models but does a join on the shared column in order to do a comparison on the "score" field. I tried the below, but alas the error Article.objects.filter(publisher=webpagestat.publisher, webpagestat.score__gte==100) File "<input>", line 1 SyntaxError: positional argument follows keyword argument How do I include the "WebPageStat" table in my join? -
How to get a django template to pull information from two different models?
I am coding a basic django application that will show a table of current store sales, based off of information from a MariaDB database. The data is entered into the database through a seperate process, so it isn't created in Django, it is just using a simple python script to load a csv file and parse it into an Insert query. There are two models in my code, Stores and ShowroomData. Showroomdata holds all of the records from the python script, however it does not hold any store information. I would like for it to be able to show all of the showroom data as well as the store's location title which is not stored in the ShowroomData model. I know I need to seperate models but can not figure out how to get them to link together. class ShowroomData(models.Model): storeid = models.IntegerField(default=0) # Field name made lowercase. date = models.DateField() # Field name made lowercase. time = models.TimeField() # Field name made lowercase. sales = models.DecimalField(max_digits=10, decimal_places=2) # Field name made lowercase. tax = models.DecimalField(max_digits=10, decimal_places=2) # Field name made lowercase. class Meta: unique_together = (('storeid', 'date', 'time'),) db_table = 'showroomdata' class Stores(models.Model): storeid = models.IntegerField(primary_key=True) location = models.CharField() … -
How to modify django import export package on the admin page
I am using Django Import export to import list of books through the admin page. I was wondering if it is possible to customize Django Admin page so it has a model choice field for the field of month that user can chose Models.py: from django.db import models class Author(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Book(models.Model): JANUARY = '1' FEBRUARY = '2' MARCH = '3' APRIL = '4' MAY = '5' JUNE = '6' JULY = '7' AUGUST = '8' SEPTEMBER = '9' OCTOBER = '10' NOVEMBER = '11' DECEMBER = '12' MONTH_CHOICES = ( (JANUARY, 'January'), (FEBRUARY, 'February'), (MARCH, 'March'), (APRIL, 'April'), (MAY, 'May'), (JUNE, 'June'), (JULY, 'July'), (AUGUST, 'August'), (SEPTEMBER, 'September'), (OCTOBER, 'October'), (NOVEMBER, 'November'), (DECEMBER, 'December'), ) name = models.CharField('Book name', max_length=100) author = models.ForeignKey(Author, models.SET_NULL, blank=True, null=True) author_email = models.EmailField('Author email', max_length=75, blank=True) imported = models.BooleanField(default=False) published = models.DateField('Published', blank=True, null=True) price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) categories = models.ManyToManyField(Category, blank=True) month = models.CharField( max_length=2, choices= MONTH_CHOICES, default=JANUARY, ) def __str__(self): return self.name admin.py from django.contrib import admin from import_export import resources from .models import * from import_export.admin import ImportExportModelAdmin from import_export.fields import Field … -
How do I make this friend request class-based-view work?
I am trying to make a friend request class-based-view work on a django project, but keep getting errors. The error I am currently getting is: TypeError at /friend_request/joe int() argument must be a string, a bytes-like object or a number, not 'User' My Friend model is not looking for an int() though, so I am unsure of what is going on. class-based view: class AddFriend(APIView): def get(self, request, username): friend = User.objects.get(username=username) current_user = request.user.username f = Friend(current_user, friend, 1) f.save() url: url(r'^friend_request/(?P<username>[\w.@+-]+)', AddFriend.as_view(), name = 'add_friend'), model: class Friend(models.Model): #static variables for friend_status attribute FRIENDS = 1 A_REQUESTS_B = 2 B_REQUESTS_A = 3 friend_A = models.ForeignKey(User, related_name='friend_A') friend_B = models.ForeignKey(User, related_name='friend_B') friend_status = models.IntegerField() def __str__(self): return '%s and %s friendship' % (self.friend_A, self.friend_B) class Meta: unique_together = (('friend_A', 'friend_B'),) Ideally this CBV would figure out who the user sending the request is, figre out what friend is being "looked up" in the url, and create/save a new friend instantiation. Where is this int() error coming from, and how do I fix it? -
How to define APIView's url?
I'm trying to make an APIView with the Django Rest Framework. When I associate the view with the url, I got this error : AssertionError: basename argument not specified, and could not automatically determine the name from the viewset, as it does not have a .queryset attribute. Here is mys APIView : class ExampleView(APIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) def get(self, request, format=None): content = { 'user': unicode(request.user), # `django.contrib.auth.User` instance. 'auth': unicode(request.auth), # None } return Response(content) And the router : router = routers.DefaultRouter() router.register('api/example', views.ExampleView.as_view()) So, what's wrong ? Thank you ! -
Auto increment field per user
I have a django app and I need to have two autoincrement fields. One is the pk and Django's default is good enough for that. But I need a second one that starts at 1 for each user. I have a User and they can create Tickets, and each one has a unique number relative to the user. So Ticket#1 for user1 and Ticket#1 for user2 would be two different entries and each user can see only their own tickets. This is necessary, and the ticket number is not arbitrary. Users need to see their ticket number and it must start at one always and increase according to each ticket created. I thought about storing the count on the user, but I'm not sure what would be the best approach for this. Ideally I would like to not have to modify my views and do everything on the models. -
How to fix 'This field is required' while submitting Django's ModelForm?
I'm using data from .csv file to prepopulate ModelForm choises. But the problem is that after clicking submit all required fields of ArticleForm and ArticleTranslationForm throw an error This field is required. Let me explain how It should work: I need a simple django-app which will allows user to load table data from file to be feed as choices parameter for each form field. After clicking 'Submit' the row data will be serialized in JSON file, otherwise the data from next row should be past in choices and form should be "refreshed". models.py class Article(models.Model): identifier = models.CharField(unique=True, max_length=255) number = models.CharField(max_length=255) ... collection = models.CharField(max_length=255) verified = models.IntegerField() class Meta: abstract = True class ArticleTranslation(models.Model): name = models.CharField(max_length=255, blank=True, null=True) description = models.TextField(blank=True, null=True) ... lightproofness = models.CharField(max_length=255, blank=True, null=True) kind_of_removal = models.CharField(max_length=255, blank=True, null=True) class Meta: abstract = True forms.py class ArticleForm(forms.ModelForm): class Meta: model = Article fields = ['identifier', 'number', ..., 'collection', 'verified'] class ArticleTranslationForm(forms.ModelForm): class Meta: model = ArticleTranslation fields = ['name', 'description', ..., 'lightproofness', 'kind_of_removal'] views.py def mapper(request): data = read_file(path='export_full.csv') if request.method == 'POST': article_form = ArticleForm(request.POST) translation_form = ArticleTranslationForm(request.POST) if article_form.is_valid() and translation_form.is_valid(): pass # does nothing, just trigger the validation else: article_form … -
How can I use a generator of JPEG images and convert it into a video stream?
I'm trying to setup a website to access a security camera from the outside world. However, it only has one image per refresh, and it's a JPEG. However, I'm not sure what the best approach is. I've tried taking the JPEG and putting it into a generator, and then passing that into StreamingHttpResponse. However on mobile it stops after a while, and I don't know how to easily apply HTML/CSS to it to make it look nice. The code below is my StreamingHttpResponse solution, but again, it doesn't work too well. def content_gen(url): while True: res = requests.get("{}/top.htm".format(url), allow_redirects=True) soup = BeautifulSoup(res.content, 'html.parser') image = "{}/{}".format( url, soup.html.body.table.find_all('tr')[4].td.table.tr.img['src'] ) byte_resp = requests.get(image) yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + byte_resp.content + b'\r\n\r\n') I'm not exactly sure what to do, I don't know how to integrate AJAX with this which is what I've seen suggested. If possible, I'd like to see an example just to see it materialized better. -
Mousewheel scroll on iframe does not work when file served via Django
Please have a look here for more details: https://youtu.be/CLzQU-5iNIA I create a simple html file with a bunch of iframe videos from youtube. I save the file and open it in chrome. I move the cursor over the videos and use the mousewheel to scroll. It works! Now, I serve the exact same file via Django using Runserver. I move cursor over video and use the mousewheel to scroll. It does NOT work! Chrome Version 71.0.3578.98 (Official Build) (64-bit) -
Unable to create object from form
After changing the field used as the primary key in a model, I now receive an error when trying to create an object from a form. I have deleted everything in the migrations directory and performed makemigrations and migrate. I do not believe the problem is with the database, rather something in the code no longer functions the same now that I am not using a custom primary key. As someone new to Django, I suspect I am missing something fundamental but cannot quite identify what that is. views.py @login_required def job_create(request): client = request.POST.get('client') form = JobForm(request.POST or None) form.fields['client'].initial = Client.objects.get(client_name=client) if request.method == "POST": if form.is_valid(): form.save() return JsonResponse({"Success": True})` models.py class Client(models.Model): client_name = models.CharField(max_length=255, unique=True) def __str__(self): return self.client_name class Job(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) job_number = models.CharField(validators=[RegexValidator(regex='^\d{4}$', message='Invalid job number', code='invalid')], max_length=4, unique=True) job_description = models.CharField(max_length=30) forms.py class JobForm(forms.ModelForm): class Meta: model = Job fields = ('client', 'job_number', 'job_description',) The above code fails to create and save the object into the database. Below is my attempt to recreate this using the Django shell: >>> from myproject.models import Client, Job >>> from myproject.forms import JobForm >>> client = Client.objects.get(client_name='John') >>> jobform = JobForm() >>> jobform.client … -
Combing Django/HTML & Javascript
I have the following block of code in my Django project, HTML view: {% for world in world_list%} {% if forloop.first %}<div class="row">{% endif %} <div class="col-xs-4 center-block"> {% if world.cover_image %} <img src="{{ world.cover_image.url }}"> {%endif%} <h2 href="#"> {{ world.name }} </h2> </div> {% if forloop.counter|divisibleby:3 %}</div><div class="row">{% endif %} {% if forloop.last %}</div>{% endif %} This displays a set of data in bootstrap row/columns depending on how much data there is. What I would like to do is centre the images as they are rendered in the middle of the columns. I looked at this stackoverflow answer and it recommends a jQuery plugin, specifically this one. The example shown in the github is: $('ul.image-list img').centerImage(); but what I don't understand is how I can apply the .centerImage() function call to this line of code in my module: <img src="{{ world.cover_image.url }}"> I am new to the world of the web so if I'm missing something obvious please tell me. -
SQL Alchemy not handling single quotes in column name
For multi-index dataframes, Pandas writes the column names to the database in the format ('index1[i]', 'index2[i]'). When trying to save to the DB this results in the following error: KeyError at .../ "('SF', 'monkeys'" Where SF is the first index and monkeys is the second. The closing parens is truncated. I've tried to trace this all through the stack and I can confirm Pandas is generating the following statement: CREATE TABLE "data" ( "('SF', 'monkeys')" REAL, "('SF', 'orangutans')" REAL, "('SF', 'girafes')" REAL, "('LA', 'monkeys')" REAL, "('LA', 'orangutans')" REAL, "('LA', 'girafes')" REAL ) But it doesn't seem to be working with SQL Alchemy Pandas code: dataframe.to_sql( '"{}"'.format(self._table_name), index=False, chunksize=50000, con=engine, ) SQLAlchemy engine engine = sqlalchemy.create_engine( "postgresql://{}:{}@{}:{}/{}".format( _warehouse_db_settings["USER"], _warehouse_db_settings["PASSWORD"], _warehouse_db_settings["HOST"], _warehouse_db_settings["PORT"], _warehouse_db_settings["NAME"], ) ) -
Simple Django rest framework Authentification
I'm building a Django API, with the Django Rest Framework, and Angular 7 for the front app. I'm lookng for a simple way to just test if an user is authentified or not, but I can't find it. Is there a way to use easily the Django default Authentification system (I'm user the Django AbstractUser) Thank you. -
Post params are showing in request.body instead of request.POST
this is actually a javascript question. When I'm submitting the form my Django server shows the params only in request.body. What am I doing wrong? thanks! -
Google Cloud SQL - Django - PostgreSQL Backups and Restorations
I am in the process of creating a database backup portion of my Django project I have opted to use dumpdata per my question here: Django Dumpdata with Specific DB and I have stored the output of the dumped data into a DB table stored in my project's only DB instance on Google App Engine. My question, since Google only provides full instance backups and I am storing client DB and universal DB backups in my default DB with the dumpdata command through my project's only DB instance, what is the proper method of restoring data if my actual main Gcloud DB instance needs to be restored before I can access my individual entries that hold the dumpdata information? Would it be best for me to create a separate instance for DB backups, or would it be best to restore the instance to a new instance, grab the dumpdata entries for each client DB, and then run loaddata for them? I've tried to be brief as this is a logistics question, if you need more information to show what I am describing, I can certainly provide it. I am looking for suggestions from users who have also used the Google … -
Implementing Freshsales API in Python
I am trying to integrate Freshsales functionality within my Django server in order to create leads, schedule appointments, etc. Freshsale's API Documentation in Python lacks detail, however. Here is a link to their API functionality using curl commands: https://www.freshsales.io/api/. Their python code is as follows: from .freshsales_exception import FreshsalesException import requests import json def _request(path, payload): try: data = json.dumps(payload) headers = { 'content-type': 'application/json', 'accept': 'application/json' } resp = requests.post(path, data=data, headers=headers) if resp.status_code != 200: raise FreshsalesException("Freshsales responded with the status code of %s" % str(resp.status_code)) except requests.exceptions.RequestException as e: raise FreshsalesException(e.message) In the case of the curl command, for example, to create an appointment, is: curl -H "Authorization: Token token=sfg999666t673t7t82" -H "Content-Type: application/json" -d '{"appointment":{"title":"Sample Appointment","description":"This is just a sample Appointment.","from_date":"Mon Jun 20 2016 10:30:00 GMT+0530 (IST)","end_date":"Mon Jun 20 2016 11:30:00 GMT+0530 (IST)","time_zone":"Chennai","location":"Chennai, TN, India","targetable_id":"115765","targetable_type":"Lead", "appointment_attendees_attributes":[{ "attendee_type":"FdMultitenant::User","attendee_id":"223"},{"attendee_type":"FdMultitenant::User","attendee_id":"222"},{"attendee_type":"Lead","attendee_id":"115773"}] }}' -X POST I understand that I need to use the requests library to make a post request. However, I do not understand how I need to format the request. The furthest extent I understand to list all appointments, for example, is for my request to be the following: my_request = "https://mydomain.freshsales.io/api/appointments/token=myexampletoken" response = requests.post(myrequest) I am unsure of how …