Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save all incoming emails to a model
I want to save all incoming emails to a django model. django-mailbox has an email table but is inactive. django-anymail's AnymailInboundMessage looks like it would work well but it is not a django model class, just a generic python object for processing incoming emails, not storing them. I know I could cut and paste the source from AnymailInboundMessage into a django model class and then turn the members into Django fields, but I am wondering if there is a way to wrap or subclass a python class such as AnymailInboundMessage into a django model. TIA -
Is there a way to run a discord bot and django code through heroku?
Everything seems to work until i get to the build part on heroku, -----> $ python manage.py collectstatic --noinput Starting up None shards... 130 static files copied to '/tmp/build_a4988370/staticfiles', 8 unmodified, 361 post-processed. Connected to shard 0 Shard 0 ready -----> Timed out running buildpack Python ! Push failed This is what happens it runs the website code and it starts by bot (shard-ed bot), and then it wont continue the build and it just fails, does anyone have any ideas, here is some of my code #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys import asyncio from threading import Thread def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise 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?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': from discordbot.main import _main loop = asyncio.new_event_loop() loop.create_task(_main()) Thread(target=loop.run_forever).start() ^manage.py def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? … -
Django show loading indicator if no validation errors
Im doing a webapp with Django and I want to display a loading indicator while I wait for my Python function to do its calculations. However, the loading indicator gets displayed (forever) if there are input validation errors. How do I check if there are validation on submit and avoid the loading indicator displaying if there are input errors? My code below. HTML template: <div class="loader" style="display:none"></div> <form method="POST" id="content" ...> ... <div>{{ form.visible_fields.0 }} </div> <div class="form-errors errorlist"> {% for error in form.visible_fields.0.errors %} <div>{{error}}</div> {% endfor %} </div> ... <button type="submit" onclick="loading()">Submit</button> JS function in template: function loading(){ $(".loader").show(); $("#content").hide(); } -
Select from a dropdown list of users to assign them to a certain Room
I'm trying to create a dropdown list of users that can be changed and updated if the admin user desires. I am able to see the dropdown list of users but when I go to create the Room and try to select a user, it doesn't get saved and that field remains blank. I used a ModelChoiceField in my forms.py file to create the dropdown list of users. I think its because I didn't call it correctly in the views.py but I'm not sure how to proceed. Any help is much appreciated Here is my code so far forms.py class RoomForm(ModelForm): userList = forms.ModelChoiceField(queryset=User.objects.all()) class Meta: model = Room fields = '__all__' exclude = ['host', 'participants'] views.py @login_required(login_url='login') def createRoom(request): form = RoomForm() topics = Topic.objects.all() if request.method == 'POST': topic_name = request.POST.get('topic') topic, created = Topic.objects.get_or_create(name=topic_name) Room.objects.create( host=request.user, topic=topic, userList = request.POST.get('userList'), 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'), ) return redirect('home') context = {'form': form, 'topics': topics} return render(request, 'room/room_form.html', context) @login_required(login_url='login') def updateRoom(request, pk): room = Room.objects.get(id=pk) form = RoomForm(instance=room) topics = Topic.objects.all() if request.user != room.host: return HttpResponse('You are not allowed here!!') if request.method == 'POST': topic_name = request.POST.get('topic') topic, created = Topic.objects.get_or_create(name=topic_name) room.name = request.POST.get('name') room.topic = … -
Django ORM. Check that sum of additional field of m2m relation model equals 100
I want to implement a check on this relation, to ensure that all ticket's weight in sum gives me 100. class PortfolioTicker(models.Model): """ Helper model for M2M relationship between Tickers and Portfolios """ portfolio = models.ForeignKey(Portfolio, models.PROTECT, related_name="tickers") ticker = models.ForeignKey(Ticker, models.PROTECT) weight = models.FloatField(null=False) def __str__(self) -> str: return f"{self.portfolio} {self.ticker} {self.weight}" -
Django on Railway
I have fully tested on localhost Django app. When hosted on Railway I cannot login to app or admin. It is showing all migration ok, no database configuration errors, but when trying to login it is showing wrong user/password. Any ideas, please? Checked for errors but it is not showing any. -
Calculating functions with python / django
I'm building a python / django portfolio and i'm having a very hard time with one of my Gym / BMI calculator. I'm trying to have a user input their current Weight and Height, so they can have a BMI result that will be visible from the frontend, and then POST and saved from the Backend models. I just don't know how to include a .py class that i created that will allow the user to input those details from the models and have calculation done in the frontend from the input textfield. Please help...:-) ` from django.db import models # Create your models here. (<-- This is my Model, where i'll save the calculation) class BMI(models.Model): Name = models.CharField(max_length=50) Surname = models.CharField(max_length=50) Weight = models.IntegerField() Height = models.IntegerField() def __str__(self): return self.Name # Create your forms here. (<-- This is my form, where user will be inputting their Weight and Height) from django import forms from django.forms import ModelForm from . models import BMI class BMIForm(ModelForm): class Meta: model = BMI fields = ['Weight', 'Height'] ` from django.shortcuts import render from . models import BMI from . forms import BMIForm # Create your views here. def Home(request): BMIOutcome = … -
How can I acces to my AWS S3 bucket in django?
I am working for the first time with aws s3, where I have images to upload from the django admin, everything works perfect on localhost, but once deployed the images are uploaded but not displayed on the web My setting.py AWS_ACCESS_KEY_ID = 'my acceskey' AWS_SECRET_ACCESS_KEY = 'my secret key' AWS_STORAGE_BUCKET_NAME = 'mybucketname' AWS_DEFAULT_ACL = None AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} STATIC_LOCATION = 'static' PUBLIC_MEDIA_LOCATION = 'media' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/' DEFAULT_FILE_STORAGE = 'portfolio.storages.MediaStore' My models class Project(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=200) link = models.CharField(max_length=250) another_link= models.CharField(max_length=250, null= True, blank=True) image = models.ImageField(upload_to='media/') My views def project(request): projects = Project.objects.all().order_by('-id').values() return render(request, "works.html", {"projects": projects}) My template {% for project in projects %} {% csrf_token %} <div class="row"> <div class="col-md-12 col-md-offset-1"> <div class="row"> <div class="col-xs-12 col-md-6"> <h3>{{project.name}}</h3> <p style=> {{project.description}} </p> <a href="{{project.link}}" target="_blank" class="btn btn-default">Source Code</a> <a href="{{project.another_link}}" target="_blank" class="btn btn-default">See Live</a> </div> <div class="col-xs-6 col-md-4"> <img src="{{project.image.url}}" width="360" height="200" > </div> </div> </div> </div> {% endfor %} In the Html not return a asw link, return this <img src="" width="360" height="200"> Images are loaded perfectly in the S3 bucket but are not displayed in the HTML. -
How to convert excel file to json in specific format
I need a specific JSON output from excel in order to insert data to my database. Right now, the input must come from an Excel table. This is the output I want [ { "model": "client.Restaurant", "pk": 1, "fields": { "name": "KOPITAN CLASSIC WHITE COFFEE", "description": "An ideal place for students and employees to release stress.", "location_lon": 100.481, "location_lat": 5.17818, "operating_hours_start": "10AM", "operating_hours_end": "10PM", "owner_id": 18, "image_url": "kopitanClassic.jpg" } } ] This is the output that I get from using online excel to json converter. [ { "name": "KOPITAN CLASSIC WHITE COFFEE", "description": "An ideal place for students and employees to release stress.", "location_lon": 100.481, "location_lat": 5.17818, "operating_hours_start": "10AM", "operating_hours_end": "10PM", "owner_id": 18, "image_url": "kopitanClassic.jpg" } ] -
how to set foreign by post method in django?
models.py class Courses(models.Model): course_name=models.CharField(max_length=50) course_price=models.IntegerField() class Exam(models.Model): exam_name=models.CharField(max_length=101) course=models.ForeignKey(Courses,on_delete=models.CASCADE,default='python') exam_time=models.DateTimeField() views.py def Examadd(request): mycourses = Courses.objects.all() context = {'mycourses': mycourses} if request.method == 'POST': newexam = request.POST.get('examname') course = request.POST.get('courses') examtime = request.POST.get('time') new = Exam.objects.create(exam_name=newexam,course=course,exam_time=examtime) new.save() messages.success(request, "Course created successfully") return redirect('Courselist') return render(request,'addexam.html',context addexam.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Add New Exam</h1> <form method="post"> {% csrf_token %} <label>Examname:</label> <input type="text" name="examname"> <label>Course:</label> <select name="courses"> {% for i in mycourses %} <option value={{i.id}}>{{i.course_name}}</option> {% endfor %} </select> <label>Exam time and date:</label> <input type="text" name="examtime"> <button type="submit">Add</button> </form> </body> </html> I am doing a project elearning.I want a dropdown list with courses and pass its ids to Exam table.course id is a foreign key.I want to pass the courseid to course column in Exam table.By this code I gets error as,Cannot assign "'1'": "Exam.course" must be a "Courses" instance. -
How to save a wish icon checked after page refresh -Django
Trying to keep selected icon in product cards active after page refresh when the user refresh the page I want that the icon to remain a full heart and not an empty heart. How could I do that? views.py @login_required def add_wishlist (request): if request.is_ajax() and request.POST and 'attr_id' in request.POST: if request.user.is_authenticated: data = Wishlist.objects.filter(customer = request.user,product_id= int(request.POST['attr_id'])) if data.exists(): data.delete() else: Wishlist.objects.create(customer= request.user,product_id = request.POST['attr_id']) else: print("No Product is Found") return redirect("products:product_all") product_all.html <div id='alCarrito'class="like-container"> {% if product in wishlisted_list %} <span class="like heart " id="id" attr_id="{{product.id}}" action_url="{% url 'products:add_wishlist' %}"> <i class="fas fa-heart"></i> </span> {% else %} <span class="like" id="id" attr_id="{{product.id}}" action_url="{% url 'products:add_wishlist' %}"><i class="far fa-heart"></i></span> {% endif %} </div> wishlist.js $(document).ready(function(){ $(".like").click(function(){ var attr_id = $(this).attr('attr_id') var action_url = $(this).attr('action_url') var that = $(this) $.ajax({ url: action_url, type: "POST", data: {'attr_id': attr_id }, headers: { "X-CSRFToken": $.cookie("csrftoken") }, success: function (response) { console.log("Success") that.toggleClass("heart"); }, }); }); }); -
Django get_queryset has different signature for Admin and Generic views, how to prevent code duplication
I would like to write simple code to filter records in view based on request information (eg. organization the user belongs to). I started to implemented it as Mixin for Admin views. class OrganizationPermissionMixin: def get_queryset(self, request): query = super().get_queryset(request) if request.user.is_superuser: return query return query.filter( organization__in=request.user.organization_set.all() ) This works fine but when I tried to apply this Mixin on Generic views, I have a signature error as there is no request parameter passed to the get_queryset method: TypeError: OrganizationPermissionMixin.get_queryset() missing 1 required positional argument: 'request' If I adapt the Mixin to: class OrganizationPermissionMixin: def get_queryset(self): query = super().get_queryset() if self.request.user.is_superuser: return query return query.filter( organization__in=self.request.user.organization_set.all() ) It works for generic views such as ListView but now it indeed breaks for ModelAdmin view: OrganizationPermissionMixin.get_queryset() takes 1 positional argument but 2 were given This inconsistency in signature is somehow very frustrating because it requires to duplicate code simply because request passing mechanism is different between Generic and Admin views. My question is: how can I make this Mixin works both for Generic and Admin views. Is there something ready for that in Django? Is it normal it behaves like this or is it an unfortunate design choice? -
I am getting following error when try to upload Django project to Heroku
When I try to upload my Django project to Heroku I am getting following error Heroku Push error Could you please tell me what is the problem and how to resolve this Thank in advance tried to run push command multiple time change the python runtime in runtime.txt file switch to different Heroku instance -
nginx: [emerg] "http" directive is not allowed here in /etc/nginx/sites-enabled/default:22
whenever I tried to enter the code above in the Nginx config file I found this error.which is nginx: [emerg] "http" directive is not allowed here in /etc/nginx/sites-enabled/default:22. I tried in HTTP tag but can't solve it enter image description here -
django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable what you said in the previous question doesn't work
I can not run the project, I did what I was told in README.md as directed, but still gives an error. The Output is: Traceback (most recent call last): File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\environ\environ.py", line 403, in get_value value = self.ENVIRON[var_name] ~~~~~~~~~~~~^^^^^^^^^^ File "<frozen os>", line 678, in __getitem__ KeyError: 'SECRET_KEY' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\new-folder\manage.py", line 21, in <module> main() File "C:\new-folder\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\django\core\management\base.py", line 93, in wrapped saved_locale = translation.get_language() ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\django\utils\translation\__init__.py", line 210, in get_language return _trans.get_language() ^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\django\utils\translation\__init__.py", line 65, in __getattr__ if settings.USE_I18N: ^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\django\conf\__init__.py", line 92, in __getattr__ self._setup(name) File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\django\conf\__init__.py", line 79, in _setup self._wrapped = Settings(settings_module) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\django\conf\__init__.py", line 190, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File … -
Django unique slug field for two or more models
I have such structure: class Category(models.Model): name = models.CharField(max_length=255, validators=[MinLengthValidator(3)]) parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE ) slug = models.SlugField(max_length=255, null=False, unique=True) class Product(models.Model): name = models.CharField(max_length=255, validators=[MinLengthValidator(3)]) to_category = models.ForeignKey(Category, on_delete=models.SET_NULL, blank=True, null=True, ) slug = models.SlugField(max_length=255, null=False, unique=True) I have created one category with slug "test". When I try to create new category with slug "test" I got warning message and it is Ok. But If I try to create product with slug "test" I dont have warning and this is not good in my case. Is there a solution or method to validate slug field for uniqueness with Product and Category model? -
PyCharm 2022.1.2 does not hit the debug breakpoint with Django
I can't get Python debugger to work on PyCharm 2022.1.2 with Django 4. When I set the breakpoint inside the view function and then call this view in the browser, nothing happens when started in debug mode... breakpoint_selected However breakpoint is hit when I set it for import. breakpoint_hit I have 2 configurations, one for Python and one for Django Server, both don't work. config1 config2 Went through numerous JetBrains tickets with people reporting similar problem but didn't find the solution there. Also tried creating second run configuration, for Python instead Django Server, but this also didn't help. -
How to prevent end users from editing a hidden input value in a Django social website
In a website having a "Comment" and "reply to a comment" system. After each comment in the template, There's a "Add a reply" form which have a hidden input to carry the comment pk on its value attribute. How to prevent the end user from editing that hidden input value ? And If this is not possible, What would be the correct approach ? -
button 'pay now!' not working for redirect to payment-done view in payment-braintree and django
I am writing an online store based on the Django 3 By Example 3rd Edition book. I encountered a problem with the book's codes in the payment section, I searched the internet and updated some of the codes, but I still have a problem! After filling out the debit card form, when I click on the "pay now!" button, I am not redirected to the Don page! Thank you for your guidance. process.html {% extends "shop/base.html" %} {% block title %} Pay by credit card {% endblock %} {% block sidenavigation %} {% endblock %} {% block content %} Pay by credit card <form method="post" autocomplete="off"> {% if braintree_error %} <div class="alert alert-danger fade in"> <button class="close" data-dismiss="alert">&times;</button> {{ braintree_error|safe }} </div> {% endif %} <div class="braintree-notifications"></div> <div id="braintree-dropin"></div> <input style="background-color: #0783ca" id="submit-button" class="btn btn-success btn-lg btn-block" type="button" value="Pay now!"/> </form> <script> var braintree_client_token = "{{ client_token}}"; var button = document.querySelector('#submit-button'); braintree.dropin.create({ authorization: "{{client_token}}", container: '#braintree-dropin', card: { cardholderName: { required: false } } }, function (createErr, instance) { button.addEventListener('click', function () { instance.requestPaymentMethod(function (err, payload) { $.ajax({ type: 'POST', url: '{% url "payment:process" %}', data: { 'paymentMethodNonce': payload.nonce, 'csrfmiddlewaretoken': '{{ csrf_token }}' } }).done(function (result) { //do accordingly }); … -
Update user profile with user uuid
I want to update user profile passing user uuid as kwarg. Here is the url: path("profile/update/<uuid:pk>", UpdateProfile.as_view(), name="update_profile"), However, after I try to update my profile, it gives me an error. Here is my view: class UpdateProfile(LoginRequiredMixin, UpdateView): model = Profile user_type_fields = { "Buyer": ["photo", "first_name", "last_name", "city"], "Celler": ["photo", "name", "city", "address"], } def get(self, request, *args, **kwargs): print(kwargs) self.fields = self.user_type_fields[get_user_model().objects.get(pk=kwargs["pk"]).type] return super().get(request, *args, **kwargs) And here is the error itself: Page not found (404) No profile found matching the query As I understand, django tries to find profile with uuid as in url, doesn't find it and returns me this error. However, if I change model in my view to user, it wouldn't be able to find fields as they belong to profile model. The only working option was to pass profile id as kwarg, but I don`t find it preferrable due to security reasons. Could someone give me an advice on how to update profile with user uuid in kwargs? Thanks in advance! -
Authenticate serverless API against Django user pool
I would like to move an API from Django server on ec2 to serverless (AWS API gateway + Lambda) because of better scalability. I need authentication/authorization for this API against my Django user pool, but that would mean polling Django server because of auth.. and I am back where I was regarding scalability. What would be my option to deal with it in a scalable (lambda like scalable) way? I was thinking about creating Cognito user pool and duplicate users from Django there. Is there a better option? -
Django IntegrityError: UNIQUE constraint failed: pu_limity.zakazka_id
I am getting following error, when I try to import csv file and save data to database: IntegrityError at /limity/limity_csv_import UNIQUE constraint failed: pu_limity.zakazka_id models.py class Limity(models.Model): zakazka = models.ForeignKey(Zakazky, on_delete=models.CASCADE) p_el = models.DecimalField("E/L", decimal_places=2, max_digits=4, null=True, blank=True) p_ml = models.DecimalField("M/L", max_digits=6, decimal_places=4, null=True, blank=True) p_prispevek = models.DecimalField("Příspěvek", max_digits=10, decimal_places=2, null=True, blank=True) p_pu = models.DecimalField("PU", max_digits=10, decimal_places=2, null=True, blank=True) aktualizace = models.DateTimeField(auto_now=True, null=True) @classmethod def create_from_csv_line(cls, line): l = Limity() try: l.zakazka = Zakazky.objects.get(kod=line["Zakazka"]) except Zakazky.DoesNotExist: print(line["Zakazka"]) l.zakazka, _ = Zakazky.objects.get_or_create(kod=line["Zakazka"]) except: print(line["Zakazka"]) l.p_el = line["EL"] l.p_ml = line["ML"] l.p_prispevek = line["Prispevek"] l.p_pu = line["PU"] l.save() views.py class LimityCSVImportView(LoginRequiredMixin, SuccessMessageMixin, FormView): template_name = "limity/limity_csv_import.html" form_class = LimityCSVForm def test_func(self): return self.request.user.is_superuser def post(self, request, *args, **kwargs): form: LimityCSVForm = LimityCSVForm(request.POST, request.FILES) if form.is_valid(): csv_file = form.cleaned_data["uploaded_file"] decoded_file = csv_file.read().decode('utf-8-sig') io_string = io.StringIO(decoded_file) reader = csv.DictReader(io_string, delimiter=",", skipinitialspace=True) record_count = 0 for line in reader: Limity.create_from_csv_line(line=line) record_count += 1 context = self.get_context_data() my_text = ' nových limitů vloženo.' messages.success(request, str(record_count) + my_text) return render(request, self.template_name, context) else: return self.form_invalid(form) Error arises when data from form saved at line l.save() I red some answers for this error and I tried in @classmethod: el = (line["EL"]) if not el: l.p_el = 0 else: … -
Enabling browser link for django in visual studio 2022
Is it possible to enable browser link for django website in VS2022 ? Im using default template for building Django website in vs and its kinda annoying for every change to stop and start the project again and again. i know i can do this if i use the console and run "Python manage.py runserver" but i want to use VS2022 debug engines too. if i use Python manage.py runserver and change the code it will refresh browser for me. -
Can't authenticate a user in Django rest framework
im trying to get data of an authenticated user using token, im using postman to send a get request and get the data i need but im reciveing a response "detail": "Authentication credentials were not provided." this is the view ` class ReceiveMessagesView(viewsets.ModelViewSet): serializer_class = MessageSerializer permission_classes = [permissions.IsAuthenticated] http_method_names = ['get', 'post'] def get_queryset(self): user = self.request.user queryset = Message.objects.filter(receiver=user) return queryset` settings REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } In the postman request im sending in Authorizaion the key as "Token" and value as the user i want data about's token tried to send an authorized get request and recived authorized user's data -
pytest parametrize I am getting TypeError: missing required positional arguments
I'm trying to use pytest.mark.parametrize import pytest from rest_framework.test import APITransactionTestCase class TestBulkImport(APITransactionTestCase) @pytest.mark.parametrize('data, expected_response', [ ( {'body': 'data;to;validate'}, {'body': ['error response']} ), ]) def test_bulk_import_validations(self, data, expected_response): response = self.client.post(reverse('path:to:url'), data=data) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual(response.json(), expected_response) I'm running the testcase using following command: pytest path/to/test/file::TestBulkImport::test_bulk_import_validations I'm getting following error: def _callTestMethod(self, method): > method() E TypeError: test_bulk_import_validations() missing 2 required positional arguments: 'data' and 'expected_response'