Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Table order messed in Firefox, but works fine in other browsers
I have a table that I sort by date, it works fine in EDGE and Chrome, but the order is messed in Firefox. A series of rows that should be on top got moved down to the bottom. HTML: <div class="row mt-4"> <div class="col-12"> <div class="card"> <h6 class="card-header">Change Log Items</h6> <div class="card-body"> <table id="changes" class="table table-striped table-hover table-bordered table-sm"> <thead class="table-dark"> <tr class="sticky"> <th>Title</th> <th>Component</th> <th>Date Committed</th> <th>Jira Link</th> <th>Details</th> </tr> </thead> <tbody> {% for log in logs %} <tr> <td>{{log.title}}</td> <td>{{log.component}}</td> <td>{{log.date_added}}</td> <td>{% if log.jira_number %}<a class="general" href="https://jira.kinaxis.com/browse/{{log.jira_number}}" target="_blank">{{log.jira_number}}{% endif %}</a></td> <td>{% if log.details %}{{log.details}}{% elif not log.details and log.jira_number %}See Jira ticket{% endif %}</td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> </div> View: @login_required def change_log(request): logs = ChangeLog.objects.all().order_by('date_added') return render(request, 'help\changelog.html', {'logs': logs}) Any information helps! :) -
How to Fatch data from shutteratock api using django?
view.py: curl -X GET "https://api.shutterstock.com/v2/images/search" --header "Authorization: Bearer $SHUTTERSTOCK_API_TOKEN" -G --data-urlencode "query=hiking" --data-urlencode "image_type=photo" --data-urlencode "orientation=vertical" --data-urlencode "people_number=3" -
My python program can't find the path to insert a .ttf
I am using the FPDF library in python to create a report, it contains the Arial font, and it needs a .ttf to work correctly when generating the report. pdf = PDF(orientation = 'L', unit = 'mm', format = 'A4') pdf.add_font('Arial', '', "/var/www/johannasenvironment/JohannasEnviroment/JohannasEnviroment/treasuryEmails/mails/arial.ttf", uni=True) At the moment of executing the program, it does not find the arial.ttf file that is in the given path, I already tried with relative path and absolute path, and it still does not find the file. In windows it works correctly, I don't know what happens when you pass it to linux. I am doing something wrong? Should it be implemented differently when I work on linux? if so, how can i do it? I appreciate your collaboration -
Python/Django exclude running tests in subdirectory
I'm trying to run all tests in a Python project from a particular directory but need to exclude some test from a subdirectory. Would like input into how to exclude tests from a subdirectory. home/ --tests/ --views/ --/viewtest1.py --models/ --/modeltest1.py --test1.py I basically want to run everything under home except anything in tests/view. #This will execute all tests under home but would include views tests. ./manage.py test home EXCLUDE_DIRS from python is only ignoring top level directories and not a subdirectory. So this statement doesn't work. EXCLUDE_DIRS=views ./manage.py test home -
Problem PHP with Django, Take PHP like plain text
I have this code {% for h in lineas %} <tr> <?php> $hola=4 </?> <th scope="col"><a onclick="restar()">{{h}}</th> </tr> {% endfor %} but in the navigator i see the PHP code like Plain text: $hola=4 $hola=4 $hola=4 $hola=4 $hola=4 $hola=4 $hola=4 $hola=4 $hola=4 $hola=4 $hola=4 i cant find the problem. Can you help me please? -
Could not resolve URL for hyperlinked relationship with Django REST Framework
I am building a project in Django Rest Framework to interact with my React app, enabling users to signup and create a profile. However, when I run python manage.py runserver and click on the url appearing on API Root Page I get the following error message: ImproperlyConfigured at /profiles/ Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. Here is my models.py code: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=100, blank=True) location = models.CharField(max_length=100, blank=True) email = models.EmailField(max_length=150) signup_confirmation = models.BooleanField(default=False) def __str__(self): return self.user.username @receiver(post_save, sender=User) def update_profile_signal(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() My serializers.py: from rest_framework import serializers from .models import Profile class ProfileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Profile fields = ('user', 'name', 'location', 'email', 'signup_confirmation') urls.py: from django.urls import path, include from rest_framework import routers from .import views router = routers.DefaultRouter() router.register(r'profiles', views.ProfileViewSet) urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] and views.py from rest_framework import viewsets from .serializers import ProfileSerializer from .models … -
urlize colour change Django
I am using 'urlize' in django (4.0.1) as follows in a 'project description' field and it works great. <h6>{{ project.description | urlize }}</h6> Is there a simple way to include a different color style for the url that urlize identifies ? For example, standard text in black and the url in say blue Thank you. -
Django create file programatically on save
The goal with this is for the user to create an instance of the model where they populate a source URLField, and on save, it would fetch the URL and save it as a file. class ComicImage(UUIDModel): src = models.URLField('Comic URL', max_length=512, blank=True) img = models.FileField('Images', null=True, blank=True, upload_to='comics') def save(self, *args, **kwargs): img_data = BytesIO(requests.get(self.src).content) self.img.save(f'{self.hash}-i.webp', content=img_data) super().save(*args, **kwargs) But I keep getting an error ValueError: The 'img' attribute has no file associated with it. Which appears that it's not assigning a file to the field. Or rather, it doesn't until AFTER the model is saved. Alternatively: I also tried self.img.save(f'{self.hash}-i.webp', content=img_data, save=True) But it gets stuck in a loop of saving forever. If I set save=False, then it creates the model but not the file. Is there a way to create/populate/modify the file before it's saved? -
Filtering sequences of events in django
My django app stores the actions that players do during a game. One of the models is called Event, and it contains a list of all actions by players. It has the following 4 columns: game_id, player_name, action, turn. Turn is the number of the turn in which the action takes place. Now I want to count how often players behave in certain patterns. For example, I want to know how often a player takes decision A in turn 2 and that same player takes decision B in turn 3. I'm breaking my head over how I can do this. Can someone help? Note: Ideally the queries should be efficient, bearing in mind that some related queries are following. For example, after the above query I would want to know how often a player takes decision C in turn 4, after doing A and B in turns 2 and 3. (The goal is to predict the likelihood of each action, given the actions in the past.) -
making query for python with ajax
hey i want to make a query for a template.i have few buttons with names. as soon as I click this button, ajax ensures that I see the data behind these names. the ajax side is ready but python side fails. def check(request): is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest' if is_ajax: if request.method == 'GET': empinfo = Employe.objects.filter(id=is_ajax) return JsonResponse({'info': list(empinfo.values())}, safe=False, status=200) return HttpResponse("Ajax with Django Success!") index.html $(document).ready(function() { $(".info-employe").click(function(){ $.getJSON('/checks/', function(response) { for(var key in response.info) $('#name').append('<p> Name: ' + response.info[key].name + '</p>'); $('#surname').append('<p>Surname : ' + response.info[key].surname + '</p>'); $('#worknumber').append('<p> Work number: ' + response.info[key].work_number + '</p>'); $('#workplace').append('<p> Workplace: ' + response.info[key].workplace + '</p>'); $('#rank').append('<p> Rank: ' + response.info[key].rank + '</p>'); $('#email').append('<p> Email ' + response.info[key].email + '</p>'); }); }); }); main.js function checkEmp(id_s, action){ $.ajax({ url: "/checks/", type:"GET", headers: { "X-Requested-With": "XMLHttpRequest", 'X-CSRFToken': csrftoken, }, dataType: 'json', success: (data) => { console.log(data); } }) } -
ORM Query pulling objects outside date range due to Timezone change
I have a piece of legacy code that uses interpolated SQL with psycopg2 to perform a query. However I wanted to clean this up and make the code use the only the ORM. However I'm having an issue where my ORM query is pulling results outside of the given date range when the Timezone is set to non UTC. For example, given the following model: class Dinner(models.Model): eaten_at = models.DateTimeField() And giving the following arbitrary objects I have in my database: Dinner(id=1, eaten_at=2022-02-23 16:58:11+00:00) Dinner(id=2, eaten_at=2022-02-23 23:59:59+00:00) Dinner(id=3, eaten_at=2022-02-24 00:00:00+00:00) Dinner(id=4, eaten_at=2022-02-24 00:00:00+00:00) I wanted to run a query for Dinners eaten on or after 2022-02-24 eaten_after_date = datetime.datetime.combine(datetime.datetime.strptime("2022-02-24", "%Y-%m-%d"),datetime.time(0, 0, 0)) # datetime.datetime(2022, 2, 24, 0, 0) My Psycopg2 Code looked like this: cursor.execute("SELECT * FROM dinner WHERE dinner.eaten_at >= %s with time zone", eaten_after_date) As expected this results in two rows pulled with corresponding ID's 3 and 4. I've re-written this using purely the ORM as: Dinner.objects.filter(eaten_at__gte=eaten_after_date) And in some instances- this works. However- when I have the following in settings: TIME_ZONE = "Asia/Tokyo" I return objects before the 24th (in this specific example- it returns ALL rows). For instance getting the first result sorted returns an entry … -
Can't execute queries when insert multi related objects in Django migration file
I want to initiate basic data of 4 related model in migration file. This is list of my models: Test QuestionCategory(with `Test` FK) Question(with `QuestionCategory` and `Test` FK) And also this is my function that import data in migration file: def step3(apps, db_alias): import pandas as pd import os file_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'initial_data/PyTest-BasicData.xlsx') questions_df = pd.read_excel(file_path, sheet_name='Questions', engine='openpyxl', ) questions_list = questions_df.T.to_dict().values() QuestionCategory = apps.get_model("PsyTest", "QuestionCategory") Question = apps.get_model("PsyTest", "Question") for item in questions_list: category_title = None if pd.isna(item["category_title"]) else item["category_title"] category_type_choice = None if pd.isna(item["category_type_choice"]) else item["category_type_choice"] category_reference_title = None if pd.isna(item["category_reference_title"]) else item["category_reference_title"] reference = None int_test_pk =int(item["test_pk"]) if category_reference_title: try: reference = QuestionCategory.objects.using(db_alias).get(test_id=int_test_pk, title=category_reference_title) except QuestionCategory.DoesNotExist: reference = QuestionCategory(test_id=int_test_pk, title=category_reference_title, category=1) reference.save() try: category = QuestionCategory.objects.using(db_alias).get(test_id=int_test_pk, title=category_title) except QuestionCategory.DoesNotExist: category = QuestionCategory(test_id=int_test_pk, title=category_title, category=int(category_type_choice), reference=reference) category.save() try: _ = Question.objects.using(db_alias).get(test_id=int_test_pk, title=item["title"]) except Question.DoesNotExist: question = Question(test_id=int_test_pk, title=item["title"], row=int(item["row"]), is_active=item["is_active"], category=category) question.save() In another function I imported Test objects in migration file and all things goes well, But when I use multi models and relations in migration file -like above function-, I got this error: raise TransactionManagementError( django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. How can … -
Django ModelsConditional ForeignKey
i have 4 Django Models (Team, Player, Game, Throw): class Team(models.Model): team_id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) class Player(models.Model): player_id = models.AutoField(primary_key=True) team_id = models.ForeignKey(Team, on_delete=models.DO_NOTHING) name = models.CharField(max_length=50) class Game(models.Model): game_id = models.AutoField(primary_key=True) team1_id = models.ForeignKey(Team, related_name='team1', on_delete=models.DO_NOTHING) team2_id = models.ForeignKey(Team, related_name='team2', on_delete=models.DO_NOTHING) class Throw(models.Model): throw_id = models.AutoField(primary_key=True) game_id = models.ForeignKey(Game, on_delete=models.CASCADE) player_id = models.ForeignKey(???) score = models.IntegerField() Is there any option for the Throw model to set a condition on field player_id = models.ForeignKey(???), so that i can only select the players from the two teams in the game model ? -
Django: How do I change an image type to WebP in upload?
I have a website that has a blog, and the upload images are served just right but the image format slows down the website and I wanted to make them all be converted to WebP, which loads faster, on upload, is there any way to do that? my image field: from django_resized import ResizedImageField class Post(models.Model) image = ResizedImageField(size=[600, 500], quality=100, upload_to ='media/', default = 'media/placeholder.png') -
What is the difference between serializers in django-rest-framework and forms in django?
Just wanted to the difference between serializers.py in the Django-rest framework to forms.py in the Django app. I'm new to this concept and is not able to get a hold of it properly when I shifted to DRF from Django. Can Somebody Explain it? -
Updating serialized data's field Django
I have serialized data that was returned from a serializer and I want to update one field how can I do that? the first method which I am thinking of is to make another serializer that only updates the data and serialized it again. the second method which i am thinking to write a get method to fetch the serialized data and update by iterating a Response(serializer.data) can anyone help me on which method is good and how to proceed further? -
ManyToManyField makes an incorrect model
Please help me out my models.py # Create your models here. class Information(models.Model): id = models.CharField(max_length=200, primary_key=True) title = models.CharField(max_length=500) link = models.CharField(max_length=100) summary = models.CharField(max_length=1000) published = models.CharField(max_length = 100) def __str__(self): return self.title class Search(models.Model): id = models.CharField(max_length=100, primary_key=True) searched_titles = models.CharField(max_length=100) searched_topics = models.CharField(max_length=100) number_found_articles = models.IntegerField() def __str__(self): return self.id class Article_search(models.Model): id = models.CharField(max_length=100, primary_key=True) found_articles = models.ManyToManyField( Information) search_details = models.ManyToManyField( Search) In my mysql workbench i can see that the table article_search is filled. BUT When i go to the admin page of my django project, i also see different objects, when i try to read them i get a weird error: Table 'kcbbe2.database_article_search_found_articles' doesn't exist", '42S02') I add some pictures picture of the admin page in django so to make clear, when i click on the object here in the picture i get the error. What did i do wrong with setting up my models? -
Django 'User' object has no attribute 'userprofile'
I'm using Django allauth for authentication and have created a UserProfile model to store additional details which a user can updated at a later stage. I'm trying to use signals to have the UserProfile instance created whenever a User is first created and to only update the UserProfile if it already exists. The problem I face is the UserProfile instance is not created, giving out this error: Traceback (most recent call last): File "/Users/QP/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/QP/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/QP/env/lib/python3.8/site-packages/django/contrib/admin/options.py", line 622, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/Users/QP/env/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/QP/env/lib/python3.8/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/Users/QP/env/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 236, in inner return view(request, *args, **kwargs) File "/Users/QP/env/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/Users/QP/env/lib/python3.8/site-packages/django/views/decorators/debug.py", line 90, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/Users/QP/env/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/Users/QP/env/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/QP/env/lib/python3.8/site-packages/django/contrib/auth/admin.py", line 99, in add_view return self._add_view(request, form_url, extra_context) File "/Users/QP/env/lib/python3.8/site-packages/django/contrib/auth/admin.py", line 126, in _add_view return super().add_view(request, form_url, extra_context) File "/Users/QP/env/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1670, in add_view return self.changeform_view(request, … -
how to convert url() to path() in Django?
url_patterns=[ url(r'^(?P<postid>\d+)/preference/(?P<userpreference>\d+)/$', views.postpreference, name='postpreference'), ] I got this code from stackoverflow only but i know only path() but don't know url() I tried to understand and convert this url(r'^......) to path(...) using url() to path() but i also want to know how to use "\d+" in path() . If you know the answer do comment below whole path(....) -----> thanku in advance🙌 -
Django: join onto subquery without model
I'm looking to create a query that joins onto Postgres generate_series() function, to fill empty date intervals from a query. In essence I have a query like so: Select (case when DATE_TRUNC('week', foobar.date_key) is not null then DATE_TRUNC('week', foobar.date_key) else date.date end ) as "x_axis_time" from foobar left join ( select DATE_TRUNC( 'week', generate_series( some_start_date, some_end_date, '1 week'::interval ) AT TIME ZONE 'UTC') as "date" ) This creates a result set that has a entry for every week between 2 dates, with empty dates from FooBar filled by the left join onto DATE_TRUNC I'd like to do something similar in Django. I have a function for creating left join (subquery) which is fairly easy to do, but what I'm having trouble doing is creating a model that can generate the desired SQL for the select date_trunc(.... The Django Date_Trunc is as follows: join_subquery = Trunc( GenerateSeries( Cast(Value(datetime_start), output_field=DateTimeField()), Cast(Value(datetime_end), output_field=DateTimeField()), Cast(Value('1 week'), output_field=DurationField()), output_field=DateTimeField() ), 'week', output_field=DateTimeField() ) where GenerateSeries is: class GenerateSeries(Func): function = 'generate_series' def as_postgresql(self, compiler, connection, **extra_context): return super().as_sql( compiler, connection, function=self.function, template="%(function)s('%(expressions)s)", **extra_context ) This doesn't quite work though because it's just a Func, not a Queryset. Is there a way to create a model … -
How to do custom permission check for nested serializer with nested models having different permission in django
I'm building a webapp, where a user can create a team and add members and his/her projects. Everything is working fine, but now comes the permission part. One model will be Team and another Project. Right now i have written custom permission for both the models extending BasePermission. The operation/permission would be : User1 created a team Team1, can add any members and add his projects (no permission to add others project) members of Team1 can add their own projects and edit (CRU) projects added by others. No permission for the members to delete Team1, only creator can delete the team. A project can only be edited by the members of the team to which it is added. Others cannot. Only creator of the project can delete it. Permissions: from rest_framework import permissions from .models import Team,Project from rest_framework import serializers class ProjectPermission(permissions.BasePermission): message = "You do not have permission to perform this action with Project that doesn't belong to you or you are not a member of the team for this Project" def has_object_permission(self, request,view, obj): if not request.method in permissions.SAFE_METHODS: if request.method != "DELETE": if obj.team: #Team can be null when creating a project return obj.created_by == request.user … -
drf - trailing / in url throwing error while calling post api
views.py class FurnitureViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet): permission_classes = [AllowAny] serializer_class = FurnitureSerializer queryset = Furniture.objects.all() @nested_view_set(FurnitureViewSet, 'furniture_id') class TablesViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet): permission_classes = [AllowAny] serializer_class = TableSerializer queryset = Table.objects.all() class OrdersViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin, GenericViewSet): authentication_classes = [] permission_classes = [AllowAny] queryset = Orders.objects.all() urls.py router = ExtendedSimpleRouter() furniture_router = router.register('furnitures', FurnitureViewSet, basename='furnitures') furniture_router.register('tables', TablesViewSet, basename="tables",parents_query_lookups=['furniture_id']) order_router = router.register('orders', OrdersViewSet, basename="orders") urlpatterns = [ path('', include(router.urls)), ] I have created a few apis for third party integration in my project. Furniture and Tables apis are working fine when called from their testing portal. Order post api is called as someurl.url/orders which throws 500 error. You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to someurl.url/orders/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings. I can't change the settings for the whole project for just 3 apis. How can I solve the url issue while still using ExtendedSimpleRouter since I'm using nested viewsets? -
Django, set formset/object date manually
I want to make a simple app for car mechanics but i have a problem which i cant figure out on my own since im a newbie. From start, i have list of services made to a car, and parts used, grouped by day in bootstrap accordion (like this https://ibb.co/8XWJx1S). In my edit view i grab all of services and parts from one certain day. In edit template i can add formsets dynamically (https://ibb.co/qBKL4Tk). The problem is when i add new service or part while editing, it saves with different date and then in list view its not grouped with services i want since its date is different. Is there a way to set this date manually to be the same as the other objects? Second option, not wanted but acceptable would be to update DATE.FIELD of other objects based on the new one, ive tried but failed models.py class Service(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) car = models.ForeignKey(Car, on_delete=models.CASCADE) service_name = models.CharField(max_length=150, verbose_name='Service', default=None) service_price = models.DecimalField(max_digits=20, decimal_places=2, default=None) date_added = models.DateField(auto_now_add=True) def __str__(self): return self.service_name def save(self, *args, **kwargs): """Update parent model date_updated field whenever child object is added/edited""" self.car.save(update_fields=['date_updated']) super(Service, self).save(*args, **kwargs) class CarPart(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, … -
PDF random massive white space added between HTML blocks
I have a problem with making a HTML template for a generated PDF file. The problem I have is randomly generated massive white spaces between HTML blocks. There's no styles added that could make that happen. I tried tinkering with page-break but that also didn't have anything to do with it. The problem also is that this does not happen when I try to save the PDF using a script that opens browsers' print option with a destination to save as a PDF like this . It happens only when I try to generate the PDF file beforehand like this . You can see on the left the massive white space randomly generated like here. The PDF is generated using WheesyPrint. <div> <h2>Zdjęcia funkcji w standardzie:</h2> <p class='m-0 p-0'><small>*Zdjęcie podlądowe. Wyposażenie może się różnić w zależności od modelu wózka oraz producenta</small></p> <div style="display:flex;flex-wrap:wrap;justify-content:flex-start;align-items:center;page-break-before:avoid;"> {{ wheelchair|function_photos_pdf:'standards' }} </div> </div> <div> <h2>Zdjęcia funkcji w opcji:</h2> <p class='m-0 p-0'><small>*Zdjęcie podlądowe. Wyposażenie może się różnić w zależności od modelu wózka oraz producenta</small></p> <div style="display:flex;flex-wrap:wrap;justify-content:flex-start;align-items:center;page-break-before:avoid;"> {{ wheelchair|function_photos_pdf:'optionals' }} </div> </div> This is the code where the white spaces are generated and just so You know I tried using and not using the page-break-before. The first … -
FieldError when trying to build REST API with Django REST framework
I am trying to build a REST API with Django REST framework with the intention of using this to interact with my React front end app. This is the general structure of my project --django-project ----peerplatform manage.py ------accounts models.py serializers.py urls.py views.py ------reactApp ------signup urls.py settings.py This is what I have in my views.py from rest_framework import viewsets from .serializers import ProfileSerializer from .models import Profile from .forms import SignUpForm from .tokens import account_activation_token class ProfileViewSet(viewsets.ModelViewSet): queryset = Profile.objects.all().order_by('name') serializer_class = ProfileSerializer My models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField(max_length=100, blank=True) location = models.CharField(max_length=100, blank=True) email = models.EmailField(max_length=150) signup_confirmation = models.BooleanField(default=False) def __str__(self): return self.user.username @receiver(post_save, sender=User) def update_profile_signal(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() Serializers.py from rest_framework import serializers from .models import Profile class ProfileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Profile fields = ('user', 'full_ name', 'location', 'email', 'signup_confirmation') accounts.urls.py: from django.urls import path, include from rest_framework import routers from .import views router = routers.DefaultRouter() router.register(r'profiles', views.ProfileViewSet) urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] and signup.urls.py: from django.contrib import admin from django.urls import path, include from django.urls import …