Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Does django-saml2-auth support share tokens between service providers (SPs)?
First of all, SAML noob here. Does django-saml2-auth support tokens being shared between Service Providers (SPs)? Eg. Service provider A can perform an API request with a SAML token (issued by same IdP) to Service provider B, so the request is authenticated automatically (without needing to redirect the browser to IdP)? Some code is better than no code, but I am not familiar with the plugin so I am just gonna make up some imaginary settings that specified in both service providers: MUTUAL_AGREED_IdP = 'http://idp.example.com' By the way, is this called 'federation'? I read the wiki about SAML federation, it mentions about 2 different IdPs to form a federation, but in my example is just one IdP. -
Celery task is recieved but not executed when using gevent or eventlet (works with prefork)
I'm running celery to send requests to Google Firebase in the background. It works fine when I use prefork. However if I switch to a threading alternative like gevent or eventlet, the tasks do not execute (even though they are received). It seems like celery is unable to connect to the network when I use gevent/eventlet. 9-09-08 21:13:11,629: DEBUG/MainProcess] Task accepted: wallet.realtime.update_balance[783e2791-89ca-42eb-869e-64a04e8bff5b] pid:17399 [2019-09-08 21:13:11,662: DEBUG/MainProcess] Making request: POST https://oauth2.googleapis.com/token [2019-09-08 21:13:11,663: DEBUG/MainProcess] Starting new HTTPS connection (2): oauth2.googleapis.com:443 [2019-09-08 21:13:31,635: ERROR/MainProcess] Task wallet.realtime.update_balance[783e2791-89ca-42eb-869e-64a04e8bff5b] raised unexpected: ServiceUnavailable('Deadline Exceeded') google.api_core.exceptions.ServiceUnavailable: 503 Deadline Exceeded It works perfectly fine with prefork, so shouldn't be a connectivity issue. This is my celery config: celery --app=bosm2019 worker --pool=gevent --concurrency=100 -Ofair --loglevel=DEBUG What should I do? -
how to fix django staticfiles page not found in heroku?
static files are not working in production in Heroku.but when in development it works, since yesterday I couldn't solve it. please help me. settings.py STATIC_ROOT=os.path.join(BASE_DIR,'staticfiles') STATIC_URL = '/static/' MEDIA_URL='/media/' MEDIA_ROOT=os.path.join(BASE_DIR,'media') CRISPY_TEMPLATE_PACK='uni_form' LOGIN_URL='/login' LOGIN_REDIRECT_URL='/app' LOGOUT_REDIRECT='/' -
Passing variable from javascript to django views
Iam creating simple "rock paper scissors" game with some css animations and so on, where most of the stuff happens in javascript, as learning JS is what Iam focusing on mostly at the moment. User vs computer match also happens in javascript. When match is finished Iam assigning users earned exp(points) to new variable. What Iam trying to do now is sending that data(earned exp) to the views, so i can save it back in db(users.exp). I think jqery ajax or fetch api should do that if Iam right but after hours of trying I probably just dont get it. Any1 can give me some tips, explenation? not just solution please. Views: @login_required def profile(request): if request.user.is_authenticated: user = request.user userObj = Profile.objects.filter(user=user) usersLevel = userObj[0].level usersPoints = userObj[0].points context = { 'usersLevel': usersLevel, 'usersPoints': usersPoints, } return render(request, 'rps_app/game.html', context) else: print('No user logged in!') return render(request, 'rps_app/game.html') This is my template where Iam loading users data: <script type="text/javascript"> var usersLevel = '{{usersLevel|safe}}'; var usersPoints = '{{usersPoints|safe}}'; </script> js: let users_level = Number(usersLevel); let users_points = Number(usersPoints); progressbar.style.width = `${users_points}%`; ... -
In Python, is it possible to mock requests inside another request?
In Django, I have a view which makes a request to an external API. The view is in my_app. class ExternalAPIView(View): def get(self, request, *args, **kwargs): ... external_api_response = requests.get(settings.EXTERNAL_API_URL) ... For its unit tests, I use the following function for the side_effect parameter of the @patch decorator. def mocked_requests_get_for_external_api(*args, **kwargs): class MockResponse: def __init__(self, content, status_code): self.content = content self.status_code = status_code if args[0] == settings.EXTERNAL_API_URL: return MockResponse(json.dumps('{"value": 1}'), 200) return MockResponse(None, 404) ... and the unit test goes like this without an issue: @patch("my_app.views.requests.get", side_effect= mocked_requests_get_for_external_api) def test_external_api(self, mock_get): response = self.client.get(settings.EXTERNAL_API_VIEW_URL) assert response.status_code == 200 data = json.loads(response.content) assert data["value"] == 1 However, I have another view in the same project, which calls this ExternalAPIView as follows: class MainView(View): def get(self, request, *args, **kwargs): ... response = requests.get(request.build_absolute_uri(settings.EXTERNAL_API_VIEW_URL)) ... I'd like to create a unit test for this MainView, which will make the call to the ExternalAPIView through settings.EXTERNAL_API_VIEW_URL, but mock external API call inside the ExternalAPIView. Is it possible at the first place? And if so, how can I do that? -
Django request.user become AnonymousUser after third party redirect
test.html: <a href="https://auth.ebay.com/oauth2/authorize? ...">authorize</a> views.py: from django.contrib.auth.decorators import login_required @login_required def myview(req): user = req.user return render(req, 'test.html') For ebay's oauth process, you have to provide users with a link to ebay's server, which asks the user if they want to give credentials to you. If they accept, ebay redirects the user to a given url with a querystring containing the access key. The problem is, when I authorize my app with ebay, the user gets redirected to my login page (despite already being logged in). If I remove the @login_required decorator, req.user returns AnonymousUser instead. This is a problem since I don't know which user to assign the access token to. What am I missing here? Note that I am using ngrok to tunnel my server, and I have no problems rendering myview other than the fact that the user is Anonymous. -
Django: dynamic choice field for formsets
So I have a form class DownloadForm(forms.Form): title = forms.CharField() device_family = forms.ChoiceField(label="Device Family", widget=forms.Select(attrs={'class': 'form-control', 'data-toggle': 'select'}), choices=LOG_ENTRY_TYPES, required=True ) and in view.py I do LOG_ENTRY_TYPES = ( ('', 'All'), ('auth', 'Auth'), ('error', 'Error'), ('info', 'Info'), ('proxy', 'Proxy'), ) DownloadFormSet = formset_factory(DownloadForm) formsets = DownloadFormSet(initial=[ {'title': 'Django is now open source', 'device_family': LOG_ENTRY_TYPES}, {'title': 'Django source 2', 'device_family': LOG_ENTRY_TYPES}, {'title': 'Django source 3', 'device_family': LOG_ENTRY_TYPES} ]) This creates the device_family field but the LOG_ENTRY_TYPES choices are not generated. So how can I pass the LOG_ENTRY_TYPES choices to the device_family choices field so that the drop down shows the choices. -
How to put a breakpoint on django-rest-framework package in vscode to debug?
I want to put a breakpoint on Create method of serializer.py located in Django-Rest-Framework in visual studio code but i am shown unverified breakpoint. Is there a way to go deep into extrnal libraries in vscode ? My breakpoint changes to a gray breakpoint when i want to debug extrnal libraries like below. -
Prefetching unrelated model on arbitrary field equivalence
I have a code like this: for m in MyModel.objects.filter(...): mo = MyOtherModel.objects.get(myOtherField=m.myField) print("{:s}{:s}".format(m, mo)) This is inefficient because finding mo requires a new query to the database. To avoid this I was thinking to use either prefetch_related(Prefetch()) or .annotate(). The problem with the first is that Prefetch() would need a foreignkey relationship between the 2 models (they have none). Same thing .annotate: MyModel.objects.filter(...).annotate(moWithSameField=F('myField') == F(???)) ^ This would be also be wrong even if I knew what to write in ???. Is this possible to do? Can you prefetch something completely unrelated based on an arbitrary query? -
Auto_now_add = true fields don't appear in the admin section because they are not editable - can you make them appear though?
As the title says, the fields with auto_now and auto_now_add don't appear in the admin section, acoording to this: Django auto_now and auto_now_add Can you somehow make them appear though? It doesn't matter if they are not editable, I just want them there so I can see the whole entry. Or is there any similar function which would set the date to the current time but would make it editable? That would be okay too, because the date will appear in the admin panel. Thanks. -
How to collect information from nav tab and submit as single form
I am using NAV to collect information from user, instead of one single view, so thought to divide up into nav tab and at the end get all the data and submit. I'm using Django, with Model with define fields, View is get valid POST. Here is the HTML looks like: <div align="center" class="container"> <form id="collectINFO" role=form method="POST" class="nav nav-pills post-form" action="{% url 'collectINFO' %}">{% csrf_token %} <ul align="center" class="nav nav-pills nav-pills-rose"> <li class="nav-item"><a class="nav-link active" href="#pill1" data-toggle="tab">TAB1</a></li> <li class="nav-item"><a class="nav-link" href="#pill2" data-toggle="tab">TAB2</a></li> </ul> <div class="tab-content tab-space"> <div align="center"class="tab-pane active" id="pill1"> <br><br> <input name="input1" id="input1" class="form-control" type="text" maxlength="20" required /> <input name="input2" id="input2" class="form-control" type="text" maxlength="2" required /> </div> <!-- end of pill-1 --> <div class="tab-pane" id="pill2"> <div class="row"><div class="col"> <input id="data1" class="form-control" rows="1" type="text" name="hostname" maxlength="20" required></input> </div></div> <!-- end of pill-2 --> </div> <div align="center" class="container"> <div id="submit" class="row"> <div class=" col"> <button type="submit" class="btn btn-primary btn-lg">SAVE</button> </form></div> When I hit SAVE nothing happens no log also in the VIEW I have added print(form.error) and print(form) here is the VIEW looks like def CollectINFO(request, *args, **kwargs): template_name = 'CollectINFO.html' if request.method == 'POST': form = CollectINFO_Form(request.POST or None) print(form.is_valid()) print(form.error) if form.is_valid(): task = form.save() messages.success(request, 'SUCCESSFULLY!!!') else: … -
How to filter deeper in objects in django?
I want to filter on the fruit type in my django project. The problem is that I use many objects and the last one needs to get filtert. Here is an example of the structure. So I would like that my inputs only show the plots that are manytomany that have the fruit pear for example. I tried the following code to see what path I had to get to the fruit: Input.objects.get(pk=1).plot.get(pk=1).Fruittype.fruit this returns: <Fruit: pear> So this is the correct path but I don't know how i can filter all the objects to the fruit. Sorry if it is unclear what I mean, but this is not my native language. -
Prefetching manytomany field doesn't change execution speed
m = MyModel.objects.all().only("colA", "colB").prefetch_related("manyToManyField") for mm in m: print(mm.id) list(mm.manyToManyField.values_list('id', flat=True)) This code takes too long to execute. This takes virtually no time (no reference to manyToManyField in loop): m = MyModel.objects.all().only("colA", "colB").prefetch_related("manyToManyField") for mm in m: print(mm.id) And this takes nearly the exact same time as the first m = MyModel.objects.all().only("colA", "colB") for mm in m: print(mm.id) list(mm.manyToManyField.values_list('id', flat=True)) This makes me think that .prefetch_related("manyToManyField") is useless and it is not actually fetching anything and list(mm.manyToManyField.values_list('id', flat=True)) hits the database for every cycle. Why is this and how can I force to prefetch from a manytomany field? -
Form without submit button - Django
I see that forms without buttons are very popular (like here). How to create a form that will be automatically submit for two different fields in Django, after the user selects the field (example 1) or type in the text and clicks something (it means completes typing) (example 2): 1.) ChoiceField forms.py class Search(forms.Form): field = forms.ChoiceField(choices=MY_CHOICES) views.py if request.method == "GET": form = Search(request.GET) if form.is_valid(): print('it's work') template.html <form method="GET"> {% csrf_token %} {{ form }} </form> 2.) CharField forms.py class Search(forms.Form): field = forms.CharField(max_length=10) * other files like above Any help will be appreciated -
how to keep rows order from a pandas dataframe to a dict
i have a pandas dataframe which is already sorted by date, but i need to serialize this dataframe to a dict python structure keeping the rows order so i can later return a JSON. i use a dict where i have some keys and values and i need the dataframe to be a value. i used pd.to_dict() but this dont keep the rows order i've tried to use OrderedDict but i can't serialize this with json.dumps(). I'm using python 2.7 dic_data = { 'data':data.to_dict(), 'variable':variables[variable], 'unit':units[variable], 'limits':{ 'limite_superior':lim_sup, 'limite_inferior':lim_inf } } return HttpResponse(json.dumps(dic_data),content_type="application/json") this is the datraframe data that im trying to convert into rows ordered dict to later serialize it in json date_time values 202 2018-09-01 10:00 0,9 203 2018-09-01 11:00 0,1 204 2018-09-01 12:00 0,0 205 2018-09-01 13:00 0,0 206 2018-09-01 14:00 0,0 207 2018-09-01 15:00 0,0 208 2018-09-01 16:00 0,0 209 2018-09-01 17:00 0,0 the json object that im receving from de data dataframe has the following structure: { date_time:{ 0:"2018-09-01 20:00", 1:"2018-09-01 21:00", .... }, values:{ 0:20.54, 1:30.45, ..... } } and actually i need the same structure but with rows ordered pd: sorry for my bad english -
How to set filter range in backend in filter class in django
I'm building a REST API using DRF. I'm using django_filters for filtering result set. In one api I want user to send his coordinates(latitude, longitude) and in backend I create a range as (latitude+2 to latitude-2) and return results, I don't want take range field from user. So I can easily change the range in my backend. I've created two range filters in filter class that works fine but url looks like this: /posts/?latitude_min=22&latitude_max=28&longitude_min=80&longitude_max=84. And here user is responsible to decide range. I want user send latitude and longitude only, I decide about maximum and minimum range. class PostFilter(django_filters.FilterSet): latitude = django_filters.RangeFilter(field_name='latitude') longitude = django_filters.RangeFilter() class Meta: model = Post fields = ['latitude', 'longitude', 'country', 'state', 'district', ] -
Validate end_time is bigger than start_time django form
I have start_time and end_time datefields in models and I want to assign an error when start_time is later than end_time. forms.py class RentForm(forms.ModelForm): class Meta: model = Rent fields = ['start_time', 'end_time'] def clean(self): cleaned_data = super().clean() start_date = cleaned_data.get("start_time") end_date = cleaned_data.get("end_time") if start_time > end_time: raise forms.ValidationError("Error") views.py def rent_car(request): if request.method == 'POST': form = RentForm(request.POST or None) if form.is_valid(): form.save() return redirect('/') else: form = RentForm(request.POST) return render(request, 'rent.html', {'form': form) Unfortunetaly I had an error 'unsupported operand type(s) for -: 'NoneType' and 'NoneType'. Please help me solve the problem -
how to make complete django tables(update, delete,search) with (django_tables2)?
friends ... i'm new in django framework i show my table in django_tables2 and i want edit and search and delete from this table so i have no idea how and what i can do ?? can you help me please this is my tables.py import django_tables2 as tables from .models import Immob class ImmobTable(tables.Table): id = tables.Column(verbose_name= 'ID') immo_code=tables.Column(verbose_name='Code') immo_desig=tables.Column(verbose_name='Désignation') immo_qte=tables.Column(verbose_name='Quantité ') immo_datemes=tables.Column(verbose_name='Date mes ') immo_cptimmob=tables.Column(verbose_name='Compte comptable ') immo_dureevie=tables.Column(verbose_name='Durée de vie ') immo_origine=tables.Column(verbose_name='Origine ') immo_fournisseur=tables.Column(verbose_name='Fournisseur ') immo_nufact=tables.Column(verbose_name='N° facture ') immo_datefact=tables.Column(verbose_name='Date facture ') immo_valht=tables.Column(verbose_name='Valeur HT ') immo_monaie=tables.Column(verbose_name='Monnaie ') immo_tauxcvt=tables.Column(verbose_name='Taux de conversion ') immo_tauxctrval=tables.Column(verbose_name='Contre valeur/DA ') immo_frais=tables.Column(verbose_name="Frais d'approche ") immo_coutacq=tables.Column(verbose_name= "Cout total d'acquisition ") immo_refcmde=tables.Column(verbose_name='Référence commande ') immo_datecmde=tables.Column(verbose_name='Date commande ') immo_journee=tables.Column(verbose_name='Numéro de journée ') immo_cptanal=tables.Column(verbose_name='Compte Analytique') immo_local=tables.Column(verbose_name='Localisation ') immo_mode_amort=tables.Column(verbose_name= "Méthode d'amortissement ") immo_code_r=tables.Column(verbose_name= "Dernier plan d'amortissement ") immo_val_amort=tables.Column(verbose_name="Valeur à amortir ") immo_status=tables.Column(verbose_name='Code status') immo_code_bar=tables.Column(verbose_name='Code à barre ') service=tables.Column(verbose_name='Service ') cni=tables.Column(verbose_name='Code cni ') class Meta: model = Immob template_name ="django_tables2/bootstrap-responsive.html" -
How transfer a string (not from form) from HTML page to the server?
I'm doing the task about creating web-project "library". When you are on the main page, you can see list of all the library users. If you press on any of the users' name, the another page with list of user's books will open. And this task became a problem for me: I don't know how server can get the string with user's name from the main page. I thought about ajax, but I guess it works only for forms. And I don't want to turn my text list into form. It seems to be not optimal decision. Please tell me if there any any ways to do it? I will be grateful for any advice. -
Django heroku server : how to solve the responses' 30 seconds limit?
I work on a Django application which is an online newspaper. This app contains an administration that allows editors to write articles, etc... Sometimes, editors have to upload large pdf files, which are compressed and sent around the world on some CDN servers. The problem is that if pdf are too large, the responses takes more than 30 seconds to be returned and the server returns a H12 error. The documentation says that if just one bit is sent to the client during the loading, the limit is restarted to 55 seconds (https://devcenter.heroku.com/articles/limits#http-timeouts). So I have done this in my Django app : pool = Pool(processes=1) import time def my_generator(): response = pool.apply_async(handle_creation, (request.POST, request.FILES, node_model, node_model_name, available_objects_dict)) while True: if response.ready(): if response.successful(): yield "ready" break time.sleep(3) yield "pong" return StreamingHttpResponse(my_generator()) When I run this script on my local server, all works good, but on the heroku server the H18 error is raised. Have you idea to solve it ? -
Fielderror when doing make html in Sphinx of Django project
I'm trying to perform make html of Sphinx for my event management website built using django. My project runs perfectly fine when I do python3 manage.py runserver so I cannot fathom why this fielderror is occuring. If there was an error how is the website running then? How do I fix this error and perform make html Running Sphinx v1.8.5 Configuration error: There is a programmable error in your configuration file: Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/sphinx/config.py", line 368, in eval_config_file execfile_(filename, namespace) File "/usr/local/lib/python2.7/dist-packages/sphinx/util/pycompat.py", line 150, in execfile_ exec_(code, _globals) File "/home/afsara/.local/lib/python2.7/site-packages/six.py", line 709, in exec_ exec("""exec _code_ in _globs_, _locs_""") File "<string>", line 1, in <module> File "/home/afsara/Desktop/EventManagement_with_django_merged/EventManagement/docs/conf.py", line 23, in <module> django.setup() File "/home/afsara/.local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/home/afsara/.local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/home/afsara/.local/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/afsara/Desktop/EventManagement_with_django_merged/EventManagement/reg_group/models.py", line 6, in <module> class User(AbstractUser): File "/home/afsara/.local/lib/python2.7/site-packages/django/db/models/base.py", line 254, in __new__ 'base class %r' % (field.name, name, base.__name__) FieldError: Local field 'email' in class 'User' clashes with field of similar name from base class 'AbstractUser' Makefile:19: recipe for target 'html' failed make: *** [html] Error 2 -
How to use UserViewSet in djoser 2.0.3?
I am new to Djoser and I am struggling to use the functions UserView, UserViewCreate, UserViewDelete to update,create and delete users. The code I am using currently in url_patterns is: from django.conf.urls import re_path from djoser import views as djoser_views urlpatterns = [ re_path(r'^user/view/$', djoser_views.UserView.as_view(), name='user-view'), re_path(r'^user/delete/$', djoser_views.UserDeleteView.as_view(), name='user-delete'), re_path(r'^user/create/$', djoser_views.UserCreateView.as_view(), name='user-create'), ] When I use UserView, I am getting the error as : AttributeError: module 'djoser.views' has no attribute 'UserView' I read the djoser documentation and saw that: UserCreateView, UserDeleteView, UserView, PasswordResetView,SetPasswordView, PasswordResetConfirmView, SetUsernameView, ActivationView, and ResendActivationView These functions have all been removed and replaced by appropriate sub-views within UserViewSet. I searched but couldn't find any way to use UserViewSet. Is there any way to use UserViewSet in djoser 2.0.3? -
Automatic field creation on form submission
I am writing a simple blog app and I'm currently in the position where I need to implement comments on a blog post. So, I have two models: from django.db import models from django.shortcuts import reverse # Create your models here. class Article(models.Model): title = models.CharField(max_length=120) author = models.CharField(max_length=50) content = models.TextField() date = models.DateField(auto_now=True) def get_absolute_url(self): return reverse('articles:article-detail', kwargs={'id': self.id}) class Comment(models.Model): author = models.CharField(max_length=50) content = models.TextField() date = models.DateField(auto_now=True) post_id = models.IntegerField() and a ModelForm: from django import forms from .models import Article, Comment class CommentModelForm(forms.ModelForm): class Meta: model = Comment fields = [ 'content', 'author', ] ...when I submit the form, I want my Comment's post_id field to be automatically generated and correspond to my Article's id, i.e. the comment should be located on the page where it was submitted. Here is my views.py: def article_detail_view(request, id): obj = get_object_or_404(Article, id=id) comments = Comment.objects.filter(post_id=id) comment_form = CommentModelForm(request.POST or None) if comment_form.is_valid(): comment_form.save() comment_form = CommentModelForm() context = { 'object': obj, 'comments': comments, 'comment_form': comment_form } return render(request, 'articles/article_detail.html', context) Any ideas how can I do that? -
Aggregate correct values in view to pass as Django context to template
I am trying to pass the correct html content as context to the template. First I have the follow queryset results: <QuerySet [{'name': 'Gemäldegalerie Alte Meister', 'id': 1, 'piece_type': 'painting', 'count': 1}, {'name': 'Isabella Stewart Gardner Museum', 'id': 2, 'piece_type': 'painting', 'count': 1}, {'name': 'Kunsthistorisches Museum', 'id': 3, ' piece_type': 'painting', 'count': 1}, {'name': 'National Gallery of Art', 'id': 4, 'piece_type': 'painting', 'count': 3}, {'name': 'National Gallery of Art', 'id': 4, 'piece_type': 'sculpture', 'count': 1}, {'name': 'The Frick Collection', 'id': 5, 'piece_type': 'painting', 'count': 2}]> I'd like to pass from view to template with a context in the form of: context: 'name_official', 'id' and 'html excerpt' html excerpt for the Gallery of Art would be in the form of: <h2>Gallery of Art</h2><p>3 paintings</p><p>1 sculpture</p> How would I generate this context data? -
How to fix "Iterators should return strings, not bytes" in Django File Upload
I'm trying to add an option to upload CSV files for one of my models in my Django App. I followed this tutorial to set it up but couldn't get it working. When uploading the file I get the following error: "_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)" This is a sample of the file I'm trying to upload: https://pastebin.com/DMyudHav I have already tried the following answers: How can I handle the error "expected str, bytes or os.PathLike object, not InMemoryUploadedFile' in Python or Django? Getting a TypeError: expected str, bytes or os.PathLike object, not InMemoryUploadedFile My code looks like this right now: import csv ... class AttendantsCSVForm(forms.Form): event = forms.ModelChoiceField(queryset=Event.objects.all(), required=False) csv_file = forms.FileField() class PersonAdmin(admin.ModelAdmin): def import_csv(self, request): if request.method == 'POST': form = AttendantsCSVForm(request.POST, request.FILES) if form.is_valid(): event_id = request.POST.get('event') csv_file = request.FILES['csv_file'] reader = csv.reader(csv_file) for row in reader: # the error occurs here for text in row: print(text) self.message_user(request, _('CSV file imported successfully.')) form = AttendantsCSVForm() payload = {'form': form} return render(request, 'admin/attendants_csv_form.html', payload) How can I solve this? I've also read python's csv documentation but still can't find a solution to this problem. I'm running the …