Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused
I have an issue with my container. I tried to Dockerize my django project and now i get some errors that i cannot resolve this is my Dockerfile FROM python:3.9-slim-buster ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN apt-get update && apt-get install -y libpq-dev RUN apt-get update && apt-get install -y python3-psycopg2 RUN pip3 install Psycopg2-binary RUN pip install --upgrade pip && pip install -r requirements.txt COPY . /code/` this is my 'docker-compose.yml' version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - localhost localhost: image: postgres:10 environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=Dimitri98! - POSTGRES_DB=test_DB_IS volumes: - postgres_data:/var/lib/postgresql/data/ ports: - "5432:5432" volumes: postgres_data: But my command 'docker-compose up --build' with this output : mbakop_polls-web-1 | connection = Database.connect(**conn_params) mbakop_polls-web-1 | File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect mbakop_polls-web-1 | conn = _connect(dsn, connection_factory=connection_factory, **kwasync) mbakop_polls-web-1 | django.db.utils.OperationalError: connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused mbakop_polls-web-1 | Is the server running on that host and accepting TCP/IP connections? mbakop_polls-web-1 | connection to server at "localhost" (::1), port 5432 failed: Cannot assign requested address mbakop_polls-web-1 | Is the server running on that host and accepting TCP/IP … -
How could I configure it so that the user who is logging in is a user of a PostgreSQL database manager?
I am developing a web application, I would like to know how I can configure it so that the user who is logging in is a user of the PostgreSQL database manager, generally there is a superuser who has permissions to freely manage all the databases, but other users with a lower hierarchy can be added, so I would like it to be possible to access as such with those users created in the DBMS. I use python as programming language and django as framework. I really have no idea how to achieve this functionality, I'm starting my studies, I want to surprise my database teacher with something different from the rest of the students, and I would like someone to help me with this, I don't expect a complete solution, just a guide and references to be able to achieve what is proposed -
How to insert data in specific category if it is not defined in Django model's field?
I have a Django project where I created two models: Category and Shop. Each shop might have only one category. If I didn't define a shop's category I want it to be in Without category section at template. How do I set a default value? My models: class Category(models.Model): name = models.CharField(max_length=100) position = models.IntegerField(unique=True) def __str__(self): return f'{self.name}' class DemoShop(models.Model): title = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='Cat') def __str__(self): return f"{self.title}" When I write: category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='Cat', default='Without category') It has no effect in my database and It doesn't show in Without category section at my template. If I haven't put a shop in a certain category I want it to be shown in Without category at the page, like: Products: -lorem; -testshop; Watch: -keram; -pollop; Without category: (All shop what I haven't define a category in DB) -
Why is Django check_password=True but authenticate=None
I'm trying to write a unit test for a login endpoint in Django using as much of the built in functionality as possible. There are existing tests that confirm that the account create endpoint is functioning properly. In the login view, however, the check_password() function will return True for this test, but the authenticate() function returns None. Is it safe to use the check_password() function instead? Otherwise, how do I update this code to use the authenticate() function? accounts.py class Account(AbstractUser): username = models.CharField(max_length=150, unique=True, null=False, default='') password = models.CharField(max_length=100) ... REQUIRED_FIELDS = ['email', 'password'] class Meta: app_label = 'accounts' db_table = 'accounts_account' objects = models.Manager() test_login.py def test_login(self): # Create account request_create = self.factory.post('/accounts/account', self.request_data, content_type='application/json') view = AccountView.as_view() response_create = view(request_create) # Login account request_login = self.factory.post('/accounts/login', self.request_data, content_type='application/json') view = LoginView.as_view() response = view(request_login) views.py class LoginView(View): def post(self, request): r = json.loads(request.body) email = r.get('email') password = r.get('password') cp = check_password(password, Account.objects.get(email=email).password) user = authenticate(username=email, password=password) P.S. I've checked this thread and is_active is set to true. -
NOT NULL constraint failed: tickets_ticket.name
I am creating a ticket app in my django project. When I try to create a ticket the NOT NULL constraint failed: tickets_ticket.name error shows up. I'm not sure why the value for ticket.name field won't pass correctly. How do I proceed? any help is much appreciated. Here's what i have so far models.py class Category(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name class Ticket(models.Model): STATUS = ( (True, 'Open'), (False, 'Closed') ) PRIORITIES = ( ('None', 'None'), ('Low', 'Low'), ('Medium', 'Medium'), ('High', 'High') ) TYPE = ( ('Misc', 'Misc'), ('Bug', 'Bug'), ('Help Needed', 'Help Needed'), ('Concern', 'Concern'), ('Question', 'Question') ) host = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True, related_name='host') category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='category') name = models.CharField(max_length=200, null=True) status = models.BooleanField(choices=STATUS, default=True) priority = models.TextField(choices=PRIORITIES, default='None', max_length=10) type = models.TextField(choices=TYPE, default='Misc', max_length=15) description = RichTextField(null=True, blank=True) # description = models.TextField(null=True, blank=True) participants = models.ManyToManyField(CustomUser, related_name='participants', blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-updated', '-created'] def __str__(self): return self.name views.py view for creating a ticket def createTicket(request): form = TicketForm() categories = Category.objects.all() if request.method == 'POST': category_name = request.POST.get('category') category, created = Category.objects.get_or_create(name=category_name) ticket = Ticket.objects.create( host = request.user, category=category, name=request.POST.get('name'), status=request.POST.get('status'), priority=request.POST.get('priority'), type=request.POST.get('type'), description=request.POST.get('description'), ) … -
Django ORM Cast() returning double quoted string from JSON field
I need to annotate a value that is saved in a json field in the same model. (Not the smartest but it is what it is). I am annotating the value as such: Model.queryset.annotate( reference=Cast( F("reference_numbers__some_id"), output_field=models.CharField(), ) ) I need it to be cast to text/char in the query because a subsequent search will only work on text/char (trigram similarity). It works, sort of, but the result adds an extra quote to my string. Like so: queryset[0].reference -> '"666999"' Any ideas on how to get the correct string from the query? I've also tried using just an ExpressionWrapper with the output field but since it doesnt cast the type in the SQL the code breaks afterwards when trying to execute the search because it uses the jsonb field still. -
Obtaining values from a foreign key Python model
Let's say I have these models/classes: class User(models.Model): id = models.AutoField. . . group = models.ForeignKey( Group, . . . ) . . . class Group(models.Model): id = models.AutoField. . . name = models.CharField. . . . . . In a custom logging function called when there is a change being made, I do this: obj = # object/model being updated; in this case: User old_values = {} new_values = {} for i in range(len(form.changed_data)): vname = obj._meta.get_field(form.changed_data[i]).verbose_name old_values.update( { vname: form[form.changed_data[i]].initial } ) new_values.update( { vname: form.cleaned_data[form.changed_data[i]] } ) That leads to this output: old_values = {'Group': 2} new_values = {'Group': <Group: New Group Name>} Looks like form.initial uses the id while form.cleaned_data uses some kind of unsightly object name format. Neither are desired. I want the output to look like this: old_values = {'Group': 'Old Group Name'} new_values = {'Group': 'New Group Name'} How do I do this? I cannot explicitly import the model name and use it. User and Group are merely two of dozens of models that must be treated non-explicitly in this generic logging function. I've tried apps.get_model(), get_object_or_404(), and other methods, but nothing has been working for me so far. -
Annotate performance Django
I've got the following models: class Match(models.Model): objects = BulkUpdateOrCreateQuerySet.as_manager() id = models.AutoField(primary_key=True) betsapi_id = models.IntegerField(unique=True, null=False) competition:Competition = models.ForeignKey(Competition, on_delete=models.CASCADE, related_name='matches') season:Season = models.ForeignKey(Season, on_delete=models.CASCADE, related_name='season_matches', null=True, default=None) home:Team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='home_matches') away:Team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='away_matches') minute = models.IntegerField(default=None, null=True) period = models.CharField(max_length=25, default=None, null=True) datetime = models.DateTimeField() status = models.IntegerField() opta_match = models.OneToOneField(OptaMatch, on_delete=models.CASCADE, related_name='match', default=None, null=True) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) class Season(models.Model): id = models.AutoField(primary_key=True) competition:Competition = models.ForeignKey(to=Competition, on_delete=models.CASCADE, null=False, blank=False, related_name='seasons') start_date = models.DateTimeField(blank=False, null=False) end_date = models.DateTimeField(blank=False, null=False) name = models.CharField(max_length=255, null=True, default=None) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) class Event(models.Model): objects = BulkUpdateOrCreateQuerySet.as_manager() id = models.AutoField(primary_key=True) betsapi_id = models.IntegerField(unique=True) name = models.CharField(max_length=255) minute = models.IntegerField() player_name = models.CharField(max_length=255, null=True, default=None) extra_player_name = models.CharField(max_length=255, null=True, default=None) period = models.CharField(max_length=255) team:Team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='events') match:Match = models.ForeignKey(Match, on_delete=models.CASCADE, related_name='events') updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) And I wrote the following annotations to a Match object: all_matches_qs = (Match .objects .filter(status=1) .select_related('home', 'away', 'competition', 'competition__country', 'season', 'opta_match') .prefetch_related( Prefetch("season", queryset=Season.objects.prefetch_related( Prefetch("season_matches", queryset=Match.objects.prefetch_related( Prefetch('statistics'))) )), Prefetch('events', queryset=Event.objects.select_related("team", "match").filter(name__in=["Corner", "Goal", "Substitution", "Yellow Card", "Red Card"])), ) .annotate(season_statistics_count=Count('season__season_matches__statistics')) .annotate(goals=Count('events', distinct=True, filter=(Q(events__name='Goal') & Q(events__team=F('home'))))) ) Executing this on about 25 records takes me about 3.75 seconds … -
Override a template of a Django package
How can I override a change_list.html template of a Django package e.g Django import export, in an existing Django app. E.g I want to override this package template, this is what I did in my project. path to the file : app/templates/import_export/change_list.html {% extends 'import_export/change_list_export.html' %} {% block object-tools-items %} <div> Hello there </div> {% endblock %} I get this error : -
How to render differently a django model object field on a html page?
My model object have a IntegerField but I want to be able to render it differently on my html page, like lets say the object IntegerField is 500000 I want to render it as 500 000$ on my html page. So Add a space before the last 3 number and add a $ at the end. I have a models with a IntegerField that look like this class Listing(models.Model): listing_price = models.IntegerField(max_length=100) In my view I extract the models like this def home(request): listing_object = Listing.objects.all() context = { "listing_object": listing_object, } return render(request, "main/index.html", context) I render the data like this {% for listing in listing_new_object %} {{listing.listing_price}} {% endfor %} -
I get TypeError: Response.__init__() got an unexpected keyword argument 'errors' when trying to send POST request
I have this view that creates a post when sending a POST request to the endpoint. class PostViewSet(viewsets.ModelViewSet): serializer_class = PostSerializer queryset = Post.objects.all() permission_classes = [IsAuthorOrReadOnly] def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) user = request.user if serializer.is_valid(): serializer.save(author=user) return Response(data=serializer.data, status=status.HTTP_201_CREATED) return Response(errors=serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
add regex in url in django
I have a url link in my template django like this http://localhost/ville/selectville/name/?&name=Paris+-+75002 I need to remove all characters that are before the character "+" to have a url like this http://localhost/ville/selectville/name/?&name=Paris this regex do the job myurl = "http://localhost/city/selectville/name/?&name=Paris+-+75002" re.sub(r'\+.*', '', myurl ) but how to integrate it in my urls.py file with this path path('selectville/<str:name>/', VilleSelect.as_view(), name='ville_select'), thank you -
'project.Account' has no ForeignKey to 'project.Object': How to link an account model to the objects of a project?
I am trying to create an announcement website (All) that can be visible to others (the Users, for which I added an Account). For this I wanted to modify a little the user profile to add fields like telephone, email address... So I modified admin.py: from django.contrib import admin from .models import Todo, Account from django.contrib.auth.models import User class AccountInline(admin.StackedInline): model = Account can_delete = False verbose_name_plural = 'Accounts' class TodoAdmin(admin.ModelAdmin): readonly_fields = ('created',) inlines = (AccountInline, ) admin.site.unregister(User) admin.site.register(Todo, TodoAdmin) But got back: <class 'todo.admin.AccountInline'>: (admin.E202) 'todo.Account' has no ForeignKey to 'todo.Todo'. So I added a ForeignKey to Todo with account = models.ForeignKey(Account, on_delete=models.CASCADE): from django.db import models from django.contrib.auth.models import User class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.CharField(max_length=100) firstname = models.CharField(max_length=30) lastname = models.CharField(max_length=50) company = models.CharField(max_length=5) def __str__(self): return self.user.username class Todo(models.Model): title = models.CharField(max_length=100) datetime = models.DateTimeField() memo = models.TextField(blank=True) created = models.DateTimeField(auto_now_add=True) datecompleted = models.DateTimeField(null=True, blank=True) important = models.BooleanField(default=False) user = models.ForeignKey(User, on_delete=models.CASCADE) account = models.ForeignKey(Account, on_delete=models.CASCADE) def __str__(self): return self.title But I still have the error. -
Django AccountActivationTokenGenerator login link works multiple times
I have been using AccountActivationTokenGenerator with Django SingIn and SignUp mechanism. class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.email_verified) ) account_activation_token = AccountActivationTokenGenerator() class PasswordResetTokenGenerator: ... def check_token(self, user, token): """ Check that a password reset token is correct for a given user. """ if not (user and token): return False # Parse the token try: ts_b36, _ = token.split("-") except ValueError: return False try: ts = base36_to_int(ts_b36) except ValueError: return False # Check that the timestamp/uid has not been tampered with if not constant_time_compare(self._make_token_with_timestamp(user, ts), token): # RemovedInDjango40Warning: when the deprecation ends, replace # with: # return False if not constant_time_compare( self._make_token_with_timestamp(user, ts, legacy=True), token, ): return False # Check the timestamp is within limit. if (self._num_seconds(self._now()) - ts) > settings.PASSWORD_RESET_TIMEOUT: return False return True I can successfully generate the link and email to user, and the user can use the link to login to the system. However the link works everytime the user clicks it. I just what the link to be valid only once, and when it is used, it should be invalidated for the next attempts. @api_view(['GET']) @renderer_classes((TemplateHTMLRenderer, JSONRenderer)) def activate(request, uidb64, token, project_uuid='None', backend='videoo.registration.views.EmailBackend'): try: uid = force_text(urlsafe_base64_decode(uidb64)) User = … -
Store very little Integer in DB( PostgreSQL )
How to store very little Integer (4 bite) integer in my database? Hi.🙌 In my model I want to store a very little integer in my DB and I don't want to use SmallIntegerField. Because Django will store 16 Byte data in DB and it is too much for my need. How can I store 4 bite integer or even less in PostgreSQL? Thanks for your help.🙏 -
Django not recognized in virtual environment altough already installed when inside virtual environment
I've created a virtual environment in my PC(Windows). I've pushed the project to my git repository and now cloned it into my Mac. I activated the virtual environment, and tried running : python3 manage.py runserver This error is raised : ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I understand that the message sent from above is defined inside the manage.py if an ImportError is raised. What I'm trying to understand is how to make the virtual environment to include the python packages inside my project. I will explain what I've tried doing below. AFTER cloning the project, I've changed line in my pyvenv.cfg ... include-system-site-packages = true //previously = false ... I'm not sure what I did wrong while setting up the virtual environment and installing the packages while being IN the virtual environment. -
Event tracking on Django
I want to implement the function of recording people for a certain event. By type: The registered user sees the desired publication -> the "mark" button on the publication -> the data is saved in the database. I can't imagine how to do it, I didn't really find a solution. I would be glad to explain how this can be done on Django I didn't find a solution :( -
Django Azure rest framework call 500 server error
I have an django app that is running fine locally, but deployed to azure app service I am getting a 500 error when when it requests data. The app is being deployed in a docker container on an azure app service: URLs.py path('primaryexams/', TemplateView.as_view(template_name='xxxDB/primaryexams.html'), name='primaryExams'), path('primaryexamsdata/', views.PrimaryExamsView.as_view(), name='primaryexam_data'), views.py class PrimaryExamsView(generics.ListAPIView): serializer_class = PrimaryExamSerializer template_name='xxxDB/primaryexams.html' def get_queryset(self): return xxxPrimaryExamData.objects.all() def filter_for_datatable(self, queryset): # filtering search_query = self.request.query_params.get('search[value]') if search_query: lookups = Q(xxxid__first_name__icontains=search_query)|Q(xxxid__last_name__icontains=search_query)|Q(xxxid__xx_id__icontains=search_query) queryset = xxxPrimaryExamData.objects.filter(lookups) return queryset def list(self, request, *args, **kwargs): draw = request.query_params.get('draw') queryset = self.filter_queryset(self.get_queryset()) recordsTotal = queryset.count() filtered_queryset = self.filter_for_datatable(queryset) try: start = int(request.query_params.get('start')) except (ValueError, TypeError): start = 0 try: length = int(request.query_params.get('length')) except (ValueError, TypeError): length = 25 end = length + start serializer = self.get_serializer(filtered_queryset[start:end], many=True) response = { 'draw': draw, 'recordsTotal': recordsTotal, 'recordsFiltered': filtered_queryset.count(), 'data': serializer.data, } return Response(response) serializers.py class PrimaryExamSerializer(serializers.ModelSerializer): xxx_id = serializers.ReadOnlyField(source='xxxid.xxx_id') last_name = serializers.ReadOnlyField(source='xxxid.last_name') first_name = serializers.ReadOnlyField(source='xxxid.first_name') program_institution = serializers.ReadOnlyField(source='program_institution.institution_id') program_institution_name = serializers.ReadOnlyField(source='program_institution.institution_name') test_center_institution = serializers.ReadOnlyField(source='test_center_institution.institution_id', default='none') class Meta: model = AbnsPrimaryExamData fields = ( 'id','xxx_id','last_name','first_name','medical_school','program_institution','program_institution_name','graduation_year','test_center_institution' ) When I try to load the data I get an ajax error, and when I look at the request its getting a 500 server error: https://xxxinternal.azurewebsites.net/xxxDB/primaryexamsdata/?draw=1&columns%5B0%5D%...blah...blahh I have other views set … -
add a menu at draw marker in Folium?
I just add a menu onche you clic on the draw maker in draw.py toolbar I modified the html of the map using this code {{ this._parent.get_name() }}.on('draw:drawstart', function(e){ var type = e.layerType, layer = e.layer; if (type === 'marker') { console.log('drawing starting... ' + e.layer) // Do marker specific actions var html = "<br><li class=''><a class='' title='Ubicacion de mujeres'>Ubicacion de mujeres</a></li><br>" + "<li class=''><a class='' title='Zona de Violencia'>Zona de Violencia</a></li><br>" + "<li class=''><a class='' title='Poblaciones diversas'>Poblaciones diversas</a></li><br>"; document.querySelector(".leaflet-draw-actions").innerHTML += html; } }); What i'm trying to do is to add a menu so the user can create a marker depending on what type of layer you choose previously my idea es in this image here When i do this, the "cancel operation" does not work anymore and also i dont know how to change the color of the marker draggable that it is displayed. Any idea will be so helpful Thank you and regards! -
Django yfinance historical data
I'm running a private Django project, that might be summarized as an html page with a form composed of an input search, and a submit button. I want to be able to write any stock ticker ('AAPL') in the input, and to generate a chart following the request. However, I made all my tests outside the django framework. Here comes the tricky part. My code related to the data scrapping designed previously, does not work when executed in the Django framework. from yahoo_finance import Share def checkview(request): yahoo = Share('YHOO') stock = yahoo.get_open() return HttpResponse(room) Here is the error code. enter image description here Also, I tried a different approach with this code: import yfinance as yf tsla = yf.Ticker("TSLA") hist = tsla.history(period='1y') import plotly.graph_objects as go fig = go.Figure(data=go.Scatter(x=hist.index,y=hist.Close, mode='lines')) fig.show() Can someone explain me, how can I solve the error ? And, how to install properly packages in the Django Framework. As an example, I will want to use Plotly going further in this project. Thanks ! -
How to generate a block of HTML code when submitting a form via Django
I would be grateful if someone explained to me how I could create a block of HTML Code when submitting a form with Django. For instance, if I want to upload an image, how could I automatically generate a HTML code block that puts the image inside a div with background and etc. Thanks! I searched a bit through documentation, and on the internet and couldn't find much about it. -
Psycopg2 error when i run my django project inside a container on windows
I have my django project in my pc (WIndows 11) and i want to put my project in a container, but when i am trying to run 'docker-compose build' in the terminal, i have always the same error. This is my Dockerfile FROM python:3.9-slim-buster ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN apt-get update && apt-get install -y libpq-dev RUN pip install --upgrade pip && pip install -r requirements.txt COPY . /code/ i am on that problem since monday. I have a 'pg-config' in my path and my django project works fine in my computer. I tried to use only 'psycopg2-binary' but i get a error that the 'psycopg2' package is not installed. I am on windows ! -
Django models: you need to display the menu and submenus
Can you please help. That's the question. I have a menu, the name of the menu is 'catr' and there is a submenu 'subcat' , I want to make the entire menu list output, and if the menu id matches the menu, then a subcategory is output, but I don't understand how to implement it.Help please.Sorry if I didn't explain it clearly, I hope you will understand, thank you in advance Here's what I tried to do enter image description here enter image description here -
Integrate pystray library with django in macOS
from documentation: run_detached(setup=None) Prepares for running the loop handling events detached. This allows integrating pystray with other libraries requiring a mainloop. Call this method before entering the mainloop of the other library. Depending on the backend used, calling this method may require special preparations: macOS Pass an instance of NSApplication retrieved from the library with which you are integrating as the argument darwin_nsapplication. This will allow this library to integrate with the main loop. source I do not understand this statement. How can I pass NSApplication instance to Icon class as argument. Where do I get this instance?. I am using macOS m1 -
How to properly run tests based on the APITestCase in Django?
When I use the python manage.py test command, in the console I see such a result: Ran 0 tests in 0.000s. How to run these UNIT tests? Also how to know the correctness of URLs which I use in the reverse function? project/urls.py: urlpatterns = [ path('', include('client.urls')), ] client/urls.py: urlpatterns = [ path('clients', ClientView.as_view()), path('clients/<int:pk>', ClientView.as_view()), ] client/tests.py: from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase from client.models import Client class ClientTestCase(APITestCase): def setUp(self): self.data = { "first_name": "Jimmy", "last_name": "Smith", "email": "jimmysmith@gmail.com" } self.response = self.client.post( reverse('client:client-list'), self.data, format="json" ) def create_client(self): self.assertEqual(self.response.status_code, status.HTTP_201_CREATED) self.assertEqual(Client.objects.count(), 1) self.assertEqual(Client.objects.get().first_name, 'Jimmy') def get_clients(self): response = self.client.get(reverse('client:client-list')) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(Client.objects.count(), 1) def get_client(self): client = Client.objects.get() response = self.client.get( reverse('client:client-detail', kwargs={'pk': client.id}), format="json" ) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertContains(response, client) def update_client(self): client = Client.objects.get() new_data = { "first_name": "Bob", "last_name": "Marley", "email": "bobmarley@gmail.com" } response = self.client.put( reverse('client:client-detail', kwargs={'pk': client.id}), data=new_data, format="json" ) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(Client.objects.get().first_name, 'Bob') def delete_client(self): client = Client.objects.get() response = self.client.delete( reverse('client:client-detail', kwargs={'pk': client.id}), format="json" ) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) self.assertEqual(Client.objects.count(), 0)