Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery, Django and S3 Default Storage causes file reading issues
I have a process whereby a webserver injests a file (via an upload), saves that file to S3 using default_storages, then creates a task for that file to be processed by the backend via celery. def upload_file(request): path = 'uploads/my_file.csv' with default_storage.open(path, 'w') as file: file.write(request.FILES['upload'].read().decode('utf-8-sig')) process_upload.delay(path) return HttpResponse() @shared_task def process_upload(path): with default_storage.open(path, 'r') as file: dialect = csv.Sniffer().sniff(file.read(1024])) file.seek(0) reader = csv.DictReader(content, dialect=dialect) for row in reader: # etc... The problem is that, although I'm using text-mode explicitely on write and read, when I read the file it comes through as bytes, which the csv library cannot handle. Is there any way around this without reading in and decoding the whole file in memory? -
Django 1.7.11 :render_to_string() got an unexpected keyword argument 'context'
There are a few related questions, such as this one, but the answers do not appear to work. I have the following in my views.py def pilab(request): return render(request, 'pilab.html',{'foo':'bar'}) Running this and going to it's corresponding url returns the following error: Traceback: File "/data_nfs/opensurfaces2/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 111. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/data_nfs/opensurfaces2/server/home/views.py" in pilab 31. return render(request, 'pilab.html',{'foo':'bar'}) File "/data_nfs/opensurfaces2/venv/local/lib/python2.7/site-packages/django/shortcuts.py" in render 50. return HttpResponse(loader.render_to_string(*args, **kwargs), Exception Type: TypeError at /pilab/ Exception Value: render_to_string() got an unexpected keyword argument 'context' Strangly enough, removing the context string returns virtually the same error: Traceback: File "/data_nfs/opensurfaces2/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 111. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/data_nfs/opensurfaces2/server/home/views.py" in pilab 31. return render(request, 'pilab.html') File "/data_nfs/opensurfaces2/venv/local/lib/python2.7/site-packages/django/shortcuts.py" in render 50. return HttpResponse(loader.render_to_string(*args, **kwargs), Exception Type: TypeError at /pilab/ Exception Value: render_to_string() got an unexpected keyword argument 'context' How can this error be fixed? -
django formset with initial values from an iterator
I'm trying to generate a formset through the inlineformset_factory, with a initializing a field with a value from a (cycling) iterator. !pseudo code <form> <field foo/> <field bar/> <formset> <row> <field "day of week" value="MON"/> <field "formset_foo"/> <field "formset_bar"/> </row> <row> <field "day of week" value="TUE"/> <field "formset_foo"/> <field "formset_bar"/> </row> <row> <field "day of week" value="WED"/> <field "formset_foo"/> <field "formset_bar"/> </row> <row> <field "day of week" value="THU"/> <field "formset_foo"/> <field "formset_bar"/> </row> <row> <field "day of week" value="FRI"/> <field "formset_foo"/> <field "formset_bar"/> </row> <row> <field "day of week" value="SAT"/> <field "formset_foo"/> <field "formset_bar"/> </row> <row> <field "day of week" value="SUN"/> <field "formset_foo"/> <field "formset_bar"/> </row> </formset> <submit button/> </form> Basically, I ld like to initialize each rows of the formset with a different value, values are taken from a choices list, this list is passed to the formset field widget. I've tryed some different ways with this, mainly from http://stackoverflow.com/questions/622982/django-passing-custom-form-parameters-to-formset, adapting it with cycle as iterator function on my choices list. WORKING_DAY_CHOICES = (('MON', _('Monday')), ('TUE', _('Tuesday')), ('WED', _('Wednesday')), ('THU', _('Thursday')), ('FRI', _('Friday')), ('SAT', _('Saturday')), ('SUN', _('Sunday')),) days_iterator = cycle(WORKING_DAY_CHOICES) My problem is that I've to be sure the FIRST element of my choices list is called by the … -
Finding all objects that have the same type object in a ManyToMany relationship
I have a model that has a ManyToMany relationship with itself (a "following" list). I can pull the list of people any particular person is following (i.e. obj.following.all() ), but I am trying to figure out how to get a list of objects that contain this particular object within THEIR following list. In other words, I have a following list, and now I want to parse a followers list. -
Django models, set unqiue attribute for M2M field per object
Currently, have a database with an Item table and a Stock table. There is a many to many relationship between the two. A single item object can have many sizes. The next step is to assign an 'inStock' options to the item per size. Any thoughts on acheiving this? Current models.py class Stock(models.Model): size = models.CharField(max_length=30) stock = models.BooleanField(default=False) def __str__(self): return self.size class Item(models.Model): title = models.CharField(max_length=250, null=True, unique=True) price = models.DecimalField(max_digits=8, decimal_places=2) aw_product_id = models.CharField(max_length=11, null=True) # Removed because multiple products has similar identifer url = models.URLField(max_length=250) # Removed 'unique=True'as the aw_prod_id will throw an integrity error image = models.CharField(max_length=1000) retailer = models.CharField(max_length=250) category = models.CharField(max_length=100) featured = models.CharField(max_length=10, default='NO') gender = models.CharField(max_length=100, null=True) sizes = models.ManyToManyField(Stock) uniq_id = models.CharField(max_length=11, null=True, unique=True) # Removed because multiple products has similar identifer def __str__(self): return self.title -
Python server-agent application design with sockets or maybe REST?
I am currently trying to design a bit complex Python project that would consist of muliple applications/scripts. First, a central engine (server) that receives data from multiple remote and/or local agents, at the time when they process some tasks. The engine would be constantly connected with a database on the host, where the information about all remote tasks is stored. Plus, additional tools (like desktop client for the server or a web application) could connect to the engine or db to show current situation of the whole infrastructure. At first, I thought of using multi-threaded sockets, which I am going to discover more deeply. However, I have also come across the idea of REST API. Since I am fairly new to both of these subjects and I am still trying to find the right solution that would suit my project, what would be your opinion on using a REST API framework in such case? REST provides extra solutions in terms of security and it would be really flexible for the engine, database and mention tools to operate with. While with sockets, I would have to get known with a lot of network concepts i.e. how to utilize sockets in the … -
Django many-to-many reverse of the same model?
Is it possible to get the reverse of a django many-to-many of the same model? For example, I have a product that is called Product Range of XY that is part of Product Range X and Product Range Y. So far I have the following: model.py class HeadwallRange(Product, ContentTyped): child_ranges = models.ManyToManyField("HeadwallRange", blank=True, related_name="child_range_products") views.py range = HeadwallRange.objects.filter(child_range_products = page.id).first() I can go in the "normal" direction (i.e from Product Range X I can get Product Range XY) but given Product Range XY is there any way to get Product Range X? -
Django transaction atomic not save commit on exception
I have a function where I want to save some data in one transaction, but log messages i want to save directly with autocommit. I wrote this code: @transaction.atomic def sync_transactions(): wm_log = WMLog.objects.get(pk=1) wm_log.create_message(message='Test') sid = transaction.savepoint() try: with transaction.atomic(): some_func_with_creating_updating_objects() raise Exception('my test eception') except Exception as e: print(sid) transaction.savepoint_commit(sid) raise e create_message method: def create_message(self, message): wm_log_message = WMLogMessage.objects.create( wm_log=self, message=message ) wm_log_message.save() return wm_log_message But my log messages not created. I also tried savepoints, not helped. -
Django form as table td with readonly fields
I want to display all objects for model in a form with information as readonly fields in a table, with each field as a cell of the table. Currently I can render a table like I want like this... <form action="" method="POST">{% csrf_token %} <table> <thead> <tr> <th>Record</th> <th>Date</th> <th>Comment</th> <th colspan="2">Attached</th> </tr> </thead> {% for record in schedule_projects %} <tr> <td>{{record.projectname}}</td> <td>{{record.date_edited|date:"d-m-Y H:i"}}</td> <td>{% if record.project_details %}{{record.project_details}}{% else %}{%endif%}</td> <td>{{record.attached_files|default_if_none:'0'}}</td> <td><input type="checkbox" name="record" value="{{record.plan_delete}}"></td> </tr> {% endfor %} </table> <button type="submit" name="plan_delete">Add to delete schedule</button> Instead of doing it manually, I wanted to do it with ModelForm. I want the form to render each field without a label, and as readonly text fields, not as input fields. I also want the records that have the boolean field plan_delete=True to be activated with a tick if the value is true in the initial form, so that I can add more records with the plan_delete boolean in the view if the form is submitted. I've tried playing around with form as_table, and modelform, but it seems that something so simple gets really complicated quite quickly. So my question is, is my way the 'best' way to do it - or am … -
Show object ID (primary key) in Django admin object page
Assuming I have the following model.py: class Book(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=100, unique=True) I register this model in the admin.py using: admin.site.register(Book) When viewing an existing Book in admin, only the name field is visible. My question is: Can the ID also be visible in this page? Most of the answers I find are related to the admin list rather than the object instance page. One way to show the ID field is to make it editable by removing editable=False from the model definition. However, I would like to keep it read-only. -
Applying bootstrap to django forms not working on all fields
Applying widgets to class Meta in forms.py is not applying widgets to all fields in form The form is inherited from UserCreationForm. Fields like username, first_name, and last_name are getting styled by widgets but email, password1, and password2 are not getting styled. forms.py from django import forms from django.forms import TextInput, PasswordInput, EmailInput from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class SignupForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) widgets = { 'username': TextInput(attrs={'class': 'form-control', 'placeholder': 'Username'}), 'first_name': TextInput(attrs={'class': 'form-control'}), 'last_name': TextInput(attrs={'class': 'form-control'}), 'email': EmailInput(attrs={'class': 'form-control', 'placeholder': 'Email Address'}), 'password1': PasswordInput(attrs={'class': 'form-control'}), 'password2': PasswordInput(attrs={'class': 'form-control'}), } def save(self, commit=True): user = super(SignupForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user Signup.html <form class="form-signin" method="post"><span class="reauth-email"> </span> {% csrf_token %} {{form.as_p}} <button class="btn btn-primary btn-block btn-lg btn-signin" type="submit">Register</button> </form> -
Mathjax in django-template renders all of text .
I am building a quiz website in django which includes some mathematical word problems. example Simplify (14.2)²+ (16.4)² − (17.9)² = ? + 32.99 And I am using mathjax to render math in templates, the problem is it's not responsive and "Simplify" or any other text with math equations is also converted by mathjax beacause of a query like this $$ {{question}} $$ which includes the whole text and math from database .Now because of this, normal english text is also distorted and math is not responsive. I have tried linebreaks and other CONFIG variables in mathjax but it's not solving the problem. So is there a way to render only math and not other text with it and also make it responsive ? Thanks. -
Django: ForeignKey selected Data Query in Form
I am working with automated result system app.I have five models class in models.py file. class Student(models.Model): std_name=models.CharField('Student Name ', max_length=200) CLASS_NAME=( ('6','SIX'), ('7','SEVEN'), ('8','Eight'), ('9','Nine'), ('10','Ten'), ('Ex-10','EX-Ten'), ) std_class_name=models.CharField('Class Name', max_length=7, choices=CLASS_NAME) std_roll_number=models.IntegerField('Roll Number') GENDER=( ('Male','Male'), ('Female','Female'), ) std_gender=models.CharField('Gender', max_length=7, choices=GENDER) GROUP=( ('Science','Science Group'), ('B.Studies','Business Group'), ('Arts and Humatics','Arts and Humatics'), ('General','General'), ) std_group=models.CharField('Group', max_length=17, choices=GROUP) pub_date = models.DateTimeField('Published', auto_now_add=True) std_total_subject=models.IntegerField('Total Subject', default=0) def __str__(self): return self.std_name class ExaminationName(models.Model): examination_name=models.CharField('Examination Name ', max_length=100) exam_date=models.DateTimeField('Exam Date: ') pub_date = models.DateTimeField('Published', auto_now_add=True) def __str__(self): return self.examination_name class MainSubject(models.Model): main_subject_name = models.CharField('Main Subject Name', max_length=100) main_subject_code=models.DecimalField('Main Subject Code', decimal_places=0, default=0, max_digits=10) subject_full_marks = models.DecimalField('Subject Full Marks', max_digits=6, decimal_places=0, default=100) pub_date = models.DateTimeField('Published', auto_now_add=True) def __str__(self): return self.main_subject_name class SubjectName(models.Model): mainsubject = models.ForeignKey(MainSubject, on_delete=models.CASCADE) subject_name=models.CharField('Subject Name', max_length=100) subject_full_marks=models.DecimalField('Subject Full Marks',max_digits=6, decimal_places=0, default=100) pub_date = models.DateTimeField('Published', auto_now_add=True) subject_gpa_point=models.DecimalField('GPA in Subject',max_digits=4, decimal_places=2, default=0) subject_gpa_grade=models.CharField('GPA Grade',max_length=5, default='F') def __str__(self): return self.subject_name class SubjectPart(models.Model): mainsubject = models.ForeignKey(MainSubject, on_delete=models.CASCADE) subjectname = models.ForeignKey(SubjectName, on_delete=models.CASCADE) subject_part_name=models.CharField('Subject Part', max_length=100) subject_part_full_marks = models.DecimalField('Full Marks', max_digits=6, decimal_places=0, default=100) subject_part_pass_marks = models.DecimalField('Pass Marks', max_digits=6, decimal_places=0, default=100) pub_date = models.DateTimeField('Published', auto_now_add=True) def __str__(self): return self.subject_part_name class AddResult(models.Model): student=models.ForeignKey(Student, on_delete=models.CASCADE) examinationname = models.ForeignKey(ExaminationName, on_delete=models.CASCADE) mainsubject_name = models.ForeignKey(MainSubject, on_delete=models.CASCADE) subjectname = models.ForeignKey(SubjectName, on_delete=models.CASCADE) subjectpart = models.ForeignKey(SubjectPart, on_delete=models.CASCADE) … -
no such command django-admin.py
I have installed Django 2.0 with CMD by using py setup.py install (Note py not python) To get that command to work I had to add Python35 to the environment variables as it was saying python is not a command. C:\Users\Ryan\Desktop\django_test>py -c "import django; print(django.get_version())" 2.0 Im not able to run django-admin.py (or django-admin) I have to use the absolute file path or put it in the current folder. When I do this it returns Type 'django-admin.py help <subcommand>' for help on a specific subcommand. Available subcommands: [django] #list of commands Note that only Django core commands are listed as settings are not properly configured (error: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.). The command I am trying to run is django-admin.py startproject myproject I have also added django-admin the the environment variables but no luck. -
Manipulating request.FILES in django POST
I have a file upload view in django. I have a model form. In POST method request.FILES contains all the files. I want to do some extra work on the uploaded files in request.FILES. I saved the files locally and do some extra work. But I can not assign the files in request.FILES. I made a dictionary like - data_dict = { 'a_file': open(tmp_dir + "/a_repro.a", 'r'), 'b_file': open(tmp_dir + "/b_repro.b", 'r'), 'c_file': open(tmp_dir + "/c_repro.c", 'r'), 'd_file': open(tmp_dir + "/d_repro.d", 'r'), } But I can not assign like - form = MyUploadForm(request.POST, data_dict) or, request.FILES = data_dict But it does not work. How can I do it? -
django restframework token Authentication fail with "invalid token"
I have a problem with token authentication. I run my django app with django built in server. $python manage.py runserver My App's urls.py from rest_framework_jwt.views import obtain_jwt_token from .views import LectureCreateView urlpatterns = [ ... url(r'^api/user_auth/$', obtain_jwt_token), url(r'^api/lecture/create/$', LectureCreateView.as_view()), ] My App's models.py from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated class LectureStartView(APIView): permission_classes = (IsAuthenticated,) authentication_classes = (TokenAuthentication,) def post(self, request): ... and settings.py ... INSTALLED_APPS = [ ... # Rest framework 'rest_framework', 'rest_framework.authtoken', 'myApp', ] ... REST_FRAMEWORK = { # other settings... 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], } I want auth with token. I successfully issued token. POST '...api/user_auth/' { "username": "test", "password": "blahbalh123" } { "token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjIwMTMyMzA2Iiwib3JpZ19pYXQiOjE1MDk5NzA5NjcsInVzZXJfaWQiOjMsImVtYWlsIjoiaW50ZXJydXBpbmdAbmF2ZXIuY29tIiwiZXhwIjoxNTA5OTcxNTY3fQ.acwqAP4sBPZWYPC0GfgL3AZarNz4Opb_5P4RewZJYrI" } but I fail Auth with Token Request: POST ...api/lecture/create/ HTTP/1.1 Host: 127.0.0.1:8000 Authorization: Token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjIwMTMyMzA2Iiwib3JpZ19pYXQiOjE1MDk5NzA5NjcsInVzZXJfaWQiOjMsImVtYWlsIjoiaW50ZXJydXBpbmdAbmF2ZXIuY29tIiwiZXhwIjoxNTA5OTcxNTY3fQ.acwqAP4sBPZWYPC0GfgL3AZarNz4Opb_5P4RewZJYrI Response: Status: 401 Unauthorized Allow →GET, POST, HEAD, OPTIONS Content-Length →27 Content-Type →application/json Date →Mon, 06 Nov 2017 12:59:17 GMT Server →WSGIServer/0.1 Python/2.7.13 Vary →Accept WWW-Authenticate →Token X-Frame-Options →SAMEORIGIN { "detail": "Invalid token." } What's wrong with my code? sorry for my english skill. -
Create django File object from online url
So I want to save some images to my django models through the shell, with the added twist that the said images would come from an online resource, a url. As per the requests documentation I can get the file to disk thus: import requests img = requests.get("image_url", stream=True) with open("name.jpg", "wb") as fd: for chunk in img.iter_content(chunk_size=128): fd.write(chunk) I could write the file to disk, then convert to a django file object like so from django.core.files import File img = File(open(choice(IMAGES), "rb")) But I need a way to bypass the read and write to/from disk while still ending up with the django File object. I've tried io.BytesIO and io.StringIO but each time I end up with an exception. -
Django viewset call serlizerer
I am trying to call serlizerer to save object from viewset This is views.py class GroupViewSet(viewsets.ViewSet): .... @detail_route(methods=['post'], url_path='task') def get_task(self, request, pk=None): group = get_object_or_404(Group, pk=pk) data = {"group": group } log_serializer = LogSerializer(data=data) if log_serializer.is_valid(raise_exception=True): log_serializer.save() This is serializer.py class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ('id', 'name') class LogSerializer(serializers.ModelSerializer): group = GroupSerializer() class Meta: model = Log fields = ('group', 'created') The post responese; { "group": { "non_field_errors": [ "Invalid data. Expected a dictionary, but got group." ] } } -
Simple Boolean decorator from a model attribute
I have extended the user profile , and i would like to have a decorator @isaffiliate which can be used if the affiliate attribute is set to TRUE . I userprofile models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) affiliate = models.BooleanField(default=False) -
Validation error failed to display in template
Validation error failed to display in template and shows source code in other environment which uses Apache via mod_wsgi and has DEBUG=False. The same code works fine in local environment . Please help. Thank you. {% if form.errors %} <h4>Please fix the following errors</h4> <ul> {% for field in form %} {% if field.errors %} {% for error in field.errors %} <li><a href="#id_{{ field.name }}" >For {{ field.name }} {{ error|escape }}</a></li> {% endfor %} {% endif %} {% endfor %} </ul> {% if form.non_field_errors %} {{ form.non_field_errors }} {% endif %} {% endif %} -
How to use IN CONDITION in django Aggregation
How can't using IN condition (example: SELECT SUM(a) FROM b WHERE a IN (1, 2, 3)) by using Django Aggregation. Example: result = qs.aggregate( amount = SUM(Case(WHEN('a IN(1, 2, 3)', then=Value(a)), default=0)) ) -
How to use Django jchart
I am new to Django and there are a lot of things I have to learn. I started a project to learn while coding. As a part of the project I want to use jcharts. I want just to follow the guide here. In this step, I have to add some code for backend part, but I do Not know where that should be added. Is it in views.py, or apps.py, anywhere else? The guide talks about chart.py. Where should it be put exactly? -
Receiving parameters with APIView
I have this routing: url(r'^article/(?P<article_id>\d+)/', views.ArticleList.as_view()) which leads to this function: class RSSList(APIView): def get(self, request, *args, **kwargs): article_id = kwargs.get('article_id') But when I try to query something like /article/34 I get this error: TypeError: get() got an unexpected keyword argument 'article_id' How can I pass article_id to get()? Thank you -
DRF jwt unable login with provided credential
i have a DRF application, which using django-rest-framework-jwt for token based authentication. here is my setting.py : INSTALLED_APPS = [ ... 'rest_framework', 'rest_framework.authtoken', 'corsheaders', ] REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAUALT_AUTHENTICATION_CLASS': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ] } and when i create a new user like below: def post(self, request, format=None): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) and in my urls : url('^login/', obtain_jwt_token), which user model is coming from django auth user model. but whene i request to api-token-auth following error happen: { "non_field_errors": [ "Unable to log in with provided credentials." ] } -
Django REST Framework; Problems serializing User model with 'groups' field
I'm trying to add a REST framework to my existing project. However, whenever I add 'groups' to the fields in my UserSerializer class, I get this traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/api/users/ Django Version: 1.10.7 Python Version: 3.6.3 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'crispy_forms', 'allauth', 'allauth.account', 'allauth.socialaccount', 'blended_learning_portal.users.apps.UsersConfig', 'blended_learning_portal.taskapp.celery.CeleryConfig', 'blended_learning_portal.unit.apps.UnitConfig', 'blended_learning_portal.data.apps.DataConfig', 'debug_toolbar', 'django_extensions', 'graphos', 'ckeditor', 'ckeditor_uploader', 'webpack_loader', 'rest_framework'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.locale.LocaleMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware'] Traceback: File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/relations.py" in to_representation 378. url = self.get_url(value, self.view_name, request, format) File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/relations.py" in get_url 316. return self.reverse(view_name, kwargs=kwargs, request=request, format=format) File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/reverse.py" in reverse 50. url = _reverse(viewname, args, kwargs, request, format, **extra) File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/reverse.py" in _reverse 63. url = django_reverse(viewname, args=args, kwargs=kwargs, **extra) File "/home/michael/blportal/lib/python3.6/site-packages/django/urls/base.py" in reverse 91. return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))) File "/home/michael/blportal/lib/python3.6/site-packages/django/urls/resolvers.py" in _reverse_with_prefix 392. (lookup_view_s, args, kwargs, len(patterns), patterns) During handling of the above exception (Reverse for 'group-detail' with arguments '()' and keyword arguments '{'pk': 2}' not found. 0 pattern(s) tried: []), another exception occurred: File "/home/michael/blportal/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 42. response = get_response(request) File "/home/michael/blportal/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/michael/blportal/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/michael/blportal/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return …