Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem with TypeError: a bytes-like object is required, not 'str'
recently I started with Django, and now I'm working on a website and I have an error. Note: I use Manjaro Linux. I have found a template online (calorietracker is the name)that I want to use some parts for my website but I cannot run this template. This is what I get when I try to run it... (calorietracker) [mahir@mahir-pc mysite]$ ./manage.py runserver Traceback (most recent call last): File "./manage.py", line 22, in <module> main() File "./manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/ma1bolg3s/.local/share/virtualenvs/calorietracker-UDGAzgdx/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/ma1bolg3s/.local/share/virtualenvs/calorietracker-UDGAzgdx/lib/python3.7/site-packages/django/core/management/__init__.py", line 345, in execute settings.INSTALLED_APPS File "/home/ma1bolg3s/.local/share/virtualenvs/calorietracker-UDGAzgdx/lib/python3.7/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/home/ma1bolg3s/.local/share/virtualenvs/calorietracker-UDGAzgdx/lib/python3.7/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/home/ma1bolg3s/.local/share/virtualenvs/calorietracker-UDGAzgdx/lib/python3.7/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/ma1bolg3s/calorietracker/mysite/mysite/settings.py", line 72, in <module> "default": django_cache_url.parse(os.getenv("MEMCACHED_URL")) File "/home/ma1bolg3s/.local/share/virtualenvs/calorietracker-UDGAzgdx/lib/python3.7/site-packages/django_cache_url.py", line 60, in parse if '?' in path and query == '': TypeError: a bytes-like object is … -
DRF - created_by and last_updated_by fields - how to make it work?
How to make created_by and last_updated_by fields work in Django REST Framework? Created by should be populated when the object is created and last_updated_by should be updated any time the object is updated. The usual way is to use CurrentUserDefault but that is not working on PATCH methods if the last_updated_by is not included in the payload. last_updated_by = serializers.HiddenField(default=serializers.CurrentUserDefault()) Do you know how to do that? Maybe the best way would be to modify the serializer data inside the ViewSet but I can't figure out how. -
Dynamically determine Django template tags file to be loaded inside {% load %} using a variable
I have a set of applications in a Django project all of which have similar templates. In each template for each application, I load the template tags file I have defined for that application: {% load <appname>tags %} But since appname is different for every application, it causes the templates (which are identical otherwise) to differ. I can determine appname programmatically inside a template, so all I need is a way to do something like this: {% load appname|add:'tags' %} Is such a thing possible? The idea above doesn't work because the result of the expression is parsed directly, rather than being interpreted the way other tags are. The end goal is to have the templates which are the same across all the applications to be shared via soft links, to reduce code duplication. -
I am getting cannot serialize error in django 3.1
I have created a new user model as shown below: In this, I am creating a new user model and an admin from abstract user and BaseUserManager. I have also added some extra fields like gender and phone number. from django.contrib.auth.base_user import BaseUserManager from django.db.models import Manager from importlib._common import _ from django.db import models from django.contrib.auth.models import AbstractUser from phone_field import PhoneField # Create your models here. class CustomUserManager(BaseUserManager): """Define a model manager for User model with no username field.""" def _create_user(self, email, password=None, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('Users must have email address.') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password=None, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Super user must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class User(AbstractUser): genders = ( ('m', _('Male')), ('f', _('Female')), ('o', _('Other')), ) username = None email = models.EmailField(_('email address'), unique=True) is_passenger = models.BooleanField(default=True) is_driver = … -
Cerbot error when completing challenges while running Django dockerized application with NGINX (and UWSGI)
When building and running my docker project with docker compose I get an error on the cerbot. The following errors were reported by the server: Domain: example.com Type: connection Detail: Fetching http://example.com/.well-known/acme-challenge/5bGuPxC5Bd-jqT6BOBS91XJg0cNjxc: Connection refused To fix these errors, please make sure that your domain name was entered correctly and the DNS A/AAAA record(s) for that domain contain(s) the right IP address. Additionally, please check that your computer has a publicly routable IP address and that no firewalls are preventing the server from communicating with the client. If you're using the webroot plugin, you should also verify that you are serving files from the webroot path you provided. My docker compose file part of the proxy is: proxy: build: context: ./proxy volumes: - static_data:/vol/static - ./proxy/default.conf:/etc/nginx/conf.d/default.conf ports: - "80:80" depends_on: - web And my docker file of the proxy is: FROM nginxinc/nginx-unprivileged:1-alpine COPY ./default.conf /etc/nginx/conf.d/default.conf COPY ./uwsgi_params /etc/nginx/uwsgi_params USER root RUN mkdir -p /vol/static RUN chmod 755 /vol/static RUN apk add --no-cache python3 python3-dev py3-pip build-base libressl-dev musl-dev libffi-dev gcc cargo sudo RUN pip3 install pip --upgrade RUN pip3 install certbot-nginx RUN mkdir /etc/letsencrypt RUN certbot --nginx -d example.com --email info@example.com -n --agree-tos --expand USER nginx My understanding is that the … -
post_save signal in django
I want to save the user IP address and the reference link in UserLog whenever the user performs any changes in the model. Currently, I am using post_save signal for this purpose. But the problem is, that it does not pass the request argument that's why I am unable to use request.META.get. Can anyone guide me to this or is there any other best practice to perform this. @receiver(post_save, sender=Session) def session_added_success(sender, instance, created, **kwargs): user = request.user action = "Logout" action_from_page = request.META.get('HTTP_REFERER') campus = request.user.campus remarks = f"{user} created a new session" login_ip = request.META.get('REMOTE_ADDR') if created: log = UserLog.objects.create( user=user, action=action, action_from_page=action_from_page, campus=campus, remarks=remarks, ip_address=login_ip) if created == False: print("Record Updated") -
Is there a way to set @csrf_exempt decorator to a view class?
I am trying to allow sending POST request without CSRF token, but getting an issue #view.py from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework import viewsets from .serializer import AuthorSerializer, MessageSerializer from .models import Author, Message @csrf_exempt class MessageViewSet(viewsets.ModelViewSet): queryset = Message.objects.order_by('-send_time') serializer_class = MessageSerializer def listMessages(self, page): per_page = 5 queryset = Message.objects.all()[page * per_page: page * per_page + per_page] return JsonResponse(queryset, safe=False) class AuthorViewSet(viewsets.ModelViewSet): queryset = Author.objects.all() serializer_class = AuthorSerializer AttributeError: 'function' object has no attribute 'get_extra_actions' Is there a way of getting this working? -
Will Django run on Windows Server 2019 or 2016?
I am trying to launch my app which i have created using flutter and django.I have started a server, the server provider is asking which OS i want in my server ,he is giving the option of Windows server 2016 and 2019. Which one should i choose? How will Django work in a Windows Server? -
Converting jsonb_each postgresql query to Django ORM
I have a query that joins on a jsonb type column in postgres that I want to convert to Django SELECT anon_1.key AS tag, count(anon_1.value ->> 'polarity') AS count_1, anon_1.value ->> 'polarity' AS anon_2 FROM feedback f JOIN tagging t ON t.feedback_id = f.id JOIN jsonb_each(t.json_content -> 'entityMap') AS anon_3 ON true JOIN jsonb_each(((anon_3.value -> 'data') - 'selectionState') - 'segment') AS anon_1 ON true where f.id = 2 GROUP BY anon_1.value ->> 'polarity', anon_1.key; Following are my models: class Tagging(BaseModel): class Meta: db_table = "tagging" json_content = models.JSONField(default=dict) feedback = models.ForeignKey("Feedback", models.CASCADE) class Feedback(BaseModel): class Meta: db_table = "feedback" feedback_text = models.TextField(blank=True, null=True) The json_content field stores data in the following format: { "entityMap": { "0": { "data": { "people": { "labelId": 5, "polarity": "positive" }, "segment": "a small segment", "selectionState": { "focusKey": "9xrre", "hasFocus": true, "anchorKey": "9xrre", "isBackward": false, "focusOffset": 75, "anchorOffset": 3 } }, "type": "TAG", "mutability": "IMMUTABLE" }, "1": { "data": { "product": { "labelId": 6, "polarity": "positive" }, "segment": "another segment", "selectionState": { "focusKey": "9xrre", "hasFocus": true, "anchorKey": "9xrre", "isBackward": false, "focusOffset": 138, "anchorOffset": 79 } }, "type": "TAG", "mutability": "IMMUTABLE" } } } What I want is to get count of the polarities per tag. … -
Pytest-django admin interface
I have been looking for sources where I would get some examples of testing Django admin interface using pytest. From this question, I got one of the examples that I am following now. However, it is not in pytest, it is also more advanced testing than I am looking for. PS: I am also new guy in testing and kind struggle some parts from there. Anyways, Here is my class in admin.py: class Sample(admin.ModelAdmin): readonly_fields = ("id",) list_display = ("id", "name", "report") list_filter = ("name", "report") search_fields = ("name", "report__name") save_as = settings.SAVE_AS_NEW I want to do something like this: assert readonly_fields == "id" for every field I have following setup in test_admin.py: class MockRequest: pass request = MockRequest @pytest.mark.django_db() class TestSampleAdmin: @pytest.fixture(autouse=True) def _setup_model(self) -> None: self.site = AdminSite() self.model = ModelAdmin(Sample, self.site) def test_recommendation_list_display(self) -> None: view = self.model print(view.readonly_fields) But my printout is empty, while I expect it to be "id" What am I doing wrong and how can I make it work? -
Django : Paginator page exceed max page
I'm currently working on CBV Paginator in Django redirecting last page when given page exceed maximum pages. So, let's say there's Post models that has 200 instances and ListView with paginated_by=10. Then maximum page is 20. So, when I enter URL with "?page=21", it return 404 Error Page. I want to redirect to maximum page. How can I do? -
django - iterate through model in create view & return inline formset
I'm trying to create a formset that will allow the user to set scores for each Priority when creating a new project with the CreateView. The Priority model already has data associated (3 values) foreach Priority that has been created I'm trying to return a char-field in the Project CreateView where the user can enter the score for the Priority. Currently I have the three char-fields showing up in the Project CreateView but I'm getting this error when trying save NOT NULL constraint failed: home_projectpriority.priority_id. I have done some testing & it looks like the ProjectPriority is never having the Project or Priority values set only the score value. I have been struggling for days trying to get this to work. I appreciate all the help. Views.py class ProjectCreateview(LoginRequiredMixin, CreateView): model = Project form_class = ProjectCreationForm success_url = 'home/project/project_details.html' def get_context_data(self, **kwargs): ChildFormset = inlineformset_factory( Project, ProjectPriority, fields=('score',), can_delete=False, extra=Priority.objects.count(), ) data = super().get_context_data(**kwargs) if self.request.POST: data['priorities'] = ChildFormset(self.request.POST, instance=self.object) else: data['priorities'] = ChildFormset(instance=self.object) return data def form_valid(self, form): context = self.get_context_data() priorities = context["priorities"] self.object = form.save() if priorities.is_valid(): priorities.instance = self.object priorities.save() return super().form_valid(form) Models.py class Priority(models.Model): title = models.CharField(verbose_name="Title", max_length=250) def __str__(self): return self.title class Project(models.Model): name … -
Django ListView how loop in one field in the template?
I have django ListView I know I can loop in it like this {% for i in object_list %} {% i.id %} {% endfor %} I want to loop in one field only {% for i in object_list.id %} {% i %} {% endfor %} -
Dockerize Django app failed with error "/bin/sh: [python3,: not found"
my docker-compose file as below: Django_2.2: build: context: . dockerfile: Dockerfile_Build_Django # Give an image name/tag image: django_2.2:iot container_name: Django_2.2 depends_on: - Django_Mongo_4.2.12 networks: sw_Django: ipv4_address: 192.168.110.12 ports: - 8000:80 restart: always volumes: - type: volume source: vol_django_codes target: /usr/src/app My docker file "Dockerfile_Build_Django" as below: FROM python:3.9.3-alpine3.13 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY . . RUN pip install -r requirements.txt # CMD ["python","./IoTSite/manage.py","runserver","0.0.0.0:80"] CMD python ./IoTSite/manage.py runserver 0.0.0.0:80 but when I run "docker-compose up", it failed with below errors, [root@Django]# docker logs Django_2.2 /bin/sh: [python3,: not found /bin/sh: [python3,: not found /bin/sh: [python3,: not found /bin/sh: [python3,: not found /bin/sh: [python3,: not found /bin/sh: [python3,: not found /bin/sh: [python3,: not found /bin/sh: [python3,: not found I have been searching for solution for a long time and tried many fixes found via google, no luck so far. any help is appreciated. I feel like getting involved in IT is a waste of life because coding according to guide/user manual for 5 mins then troubleshooting for hours or even days... -
Django template how to compare current item with the previous item in for loop?
My context is an integer array, I'm trying to make a table where every number is compared to the previous one and I will display an arrow indicating if this number has increased or decreased. This is what I'm trying to make {% for number in object_list %} {% if forloop.first %} {% set prev_number = number %} {%endif%}{%endfor%} {% for number in object_list %} {% if number > prev_number %} ... {% else %} ... {% endif %} {% set prev_number = number %} {% endfor %} I know there is not {%set%} tag in django is there any tag equivalent to it? something like {%with%} but doesn't require {% endwith %} or a template tag that does it or I should do it in the views. -
Send email from Django in docker container
I have deployed an existing application inside a docker container. The email service is now working any more. I have exposed the email server port (587), but still not working. This is my django email configuration: # EMAIL handler EMAIL_HOST = "smtp.office365.com" EMAIL_PORT = 587 EMAIL_HOST_USER = "email@email.com" EMAIL_HOST_PASSWORD = "pssword" these are my container exposed ports: docker run -d -p 8001:8020 -p 587:587 --name ... 587/tcp -> 0.0.0.0:587 8020/tcp -> 0.0.0.0:8001 -
whenever i write django-admin,i get this error:ModuleNotFoundError: No module named 'django.utils'
$ django-admin Traceback (most recent call last): File "c:\python\python38\lib\runpy.py", line 194, in _run_module_as_main return run_code(code, main_globals, None, File "c:\python\python38\lib\runpy.py", line 87, in run_code exec(code, run_globals) File "C:\Python\Python38\Scripts\django-admin.exe_main.py", line 4, in File "C:\Users\Asus\AppData\Roaming\Python\Python38\site-packages\django_init.py", line 1, in from django.utils.version import get_version ModuleNotFoundError: No module named 'django.utils' -
Django Encrypt the URL (PK and ID)
I am trying to find best solution for encrypting my URL, I have found some old versions, for python 2.2. I need to set my URLs, not to display like this: petkovic.com/AddPost/1/ and petkovic.com/PostDetail/40. But something like this:petkovic.com/AddPost/DMQRzZWMDdGQtbndzBHNsawN0aXRsZQR0ZXN0AzcwMQR3b2UDMjQwMjEwNQ That you can not guess what PK is and access that page: URLs: urlpatterns = [ path('PostDetail/<int:pk>', PostDetail.as_view(), name ='post_detail'), ] view.py: class PostDetail(DetailView): model = Post template_name = 'post_detail.html' def get_context_data(self, *args,**kwargs): post = Post.objects.all() context = super(PostDetail,self).get_context_data(*args,**kwargs) stuff = get_object_or_404(Post,id=self.kwargs['pk']) total_likes=stuff.total_likes() context['total_likes'] = total_likes return context -
CSS Referencing many stylesheet and scalability
I'm having some problem with my multiples stylesheet references. Basically the classes defined on style.css are not acting on my index.html. Might be that as there are multiple stylesheet someone of these are overwriting the file style.css? Last time I was having a similar problem and I asked a question here but after a couple of hours the file was working fine... Now I have restarted and all but still style.css still do nothing... myapp/static/style.css h1 { color: blue; text-align: center; } .box { width:30%; height:30%; background-color: blue; } On my layout.html have been defined multiples stylesheet references on the following way <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user- scalable=no"> <!-- Estilos de la master --> <link rel="stylesheet" href="{% static 'myapp/style.css' %}" type="text/css" > <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}" type="text/css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'js/sss/sss.css' %}" type="text/css" media="all"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <!-- Estilos de los recursos adicionales --> <link rel="stylesheet" href="{% static 'fontawesome/web-fonts-with-css/css/fontawesome- all.min.css' %}"> <!-- Librerías adicionales --> <script src="{% static 'js/jquery.min.js'%}"></script> <script src="{% static 'js/sss/sss.min.js' %}"></script> <!-- Librerías de plugins --> <!-- Archivo personalizado de Javascript --> <script src=" {% static 'js/codejs.js' %}"></script> <title>{% block title %}{% endblock %}</title> </head> and … -
Using DRF Serializer/Model to find different combinations of relationships
Using Django Rest Framework, I have a feature that shows the users that the logged-in-user is following. It works as expected. I now want to be able to show the users who FOLLOW the logged-in-user. Would this be possible using the same model and serializer somehow, is this where I would use a reverse look up? I want to avoid writing a new model if possible. Here is my model class UserConnections(models.Model): user = models.ForeignKey(User, related_name="following", on_delete=models.CASCADE) following_user = models.ForeignKey(User, related_name="followers", on_delete=models.CASCADE) Here is the serializer class UserConnectionListSerializer(serializers.ModelSerializer): class Meta: model = UserConnections fields = ['user','following_user'] class UserConnectionSerializer(serializers.ModelSerializer): class Meta: model = UserConnections fields = '__all__' depth = 2 And here is the view: class FollowingViewSet(viewsets.ModelViewSet): serializer_class = serializers.UserConnectionListSerializer queryset = UserConnections.objects.all() def get_serializer_class(self): if self.request.method == 'GET': return serializers.UserConnectionSerializer return self.serializer_class def get_followers(request): if request.method == "GET": name = self.request.GET.get('username', None) return UserConnections.objects.filter(user__username=name) -
Django: 'Q' object is not iterable
I have following APIView: class SubmitFormAPIView(APIView): def put(self, request, pk): # some other codes form = Form.objects.get(id=pk) tu_filter, target_user = self._validate_target_user(request, form) user_status, created = UserFormStatus.objects.get_or_create( tu_filter, form_id=pk, user_id=request.user.pk ) # Some other codes. def _validate_target_user(request, form): if some_conditions: return Q(), None else: try: target_user_id = int(request.GET.get('target_user_id)) except ValueError: raise ValidationError() target_user = get_user_model().objects.get(id=target_user_id) return Q(target_user_id=target_user_id), target_user but when django wants to execude get_or_create method, raises following error: 'Q' object is not iterable Note: If _validate_target_user() returns Q(), None, no errors raised and view works fine. I know, question information is not completed, just I want to know, what may cause this error? -
Django not loading global static files in only one app
I have a Django project with multiple apps. Every app has a 'static/' dir to store some CSS and JS in their respectives folders. In addition, the project has a global '/static' dir to store the global assets that aren't attached to an app in particular. The structure of the project is the following one: monitor (project root) clients static assets css js scheduler static assets css js monitor static (global static dir) assets css js I'm not sure about this structure, but this is how it generates when use startproject and startapp commands from Django. If I put the global assets in the path /monitor/assets instead of /monitor/monitor/assets, then none of the apps can load them. The problem comes when loading assets from the global static dir. The app scheduler loads them perfectly. However, the app clients can't find them. But I'm loading them exactly the same way!!! Seriously, I'm going mad with this. I have put staticfiles in the installed apps, and have set up STATIC_URL and STATICFILES_DIR parameters: INSTALLED_APPS = [ 'scheduler.apps.SchedulerConfig', 'clients.apps.ClientsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "monitor/static", ] This is the way I'm loading the … -
I changed the session cookie name in my django project and I am unable to login
I want to change the SESSION_COOKIE_DOMAIN because it's set incorrectly on a production server. Due to this, I also need to change the SESSION_COOKIE_NAME to something else. Otherwise there'll be two cookies with the same name and different domains on the users side, because it's already in production. With these two cookies, the user will have trouble logging in. This would normally be fine, but now the problem. Just after I changed the SESSION_COOKIE_NAME (so I haven't even changed the SESSION_COOKIE_DOMAIN yet), I am unable to login into the admin console. I can see the cookie with the new name being set. The application itself has no problems and users can login without problems, which is strange because it's the same authentication. What I've tried: Deleting all session on the server site Private mode Other Browser Flushing all possible caches on the server but might have mist one. Checking for hardcoded session names, but there are not. What else could I possibly check? If I set the SESSION_COOKIE_NAME back to what it was, I can log in again. This issue only happens on the production server; not locally, and on not on the test server, which makes it hard to … -
How to get payment response from paypal as boolean in django?
I am using Paypal api for my Django website.I am able to make payment but don't know how to get payment response from paypal server as either True or False. -
TESTING a Django View
I am very new to testing, this is my first set of tests. I have followed few tutorials on how to go about testing and while the testing that I have made for models and URLs work perfectly, my views testing are not working properly. I have looked at some answers for similar questions on Stack but can't find a reason why this would not work. This is my View function: @csrf_exempt @login_required def profile(request, username): user = request.user profilepic = ProfilePic.objects.filter(user=user).first() username = User.objects.filter(username=username).first() usr = username following = FollowedCrypto.objects.filter(user=user.id) cryptos = [] for i in following: cryptos.append(i.cryptocurrency) return render(request, "PlanetCrypton/profile.html", { "following":following, "user": user, "usr" : username, "profilepic":profilepic, "crypto": cryptos, }) and this is my test for it: def test_profile(self): c = Client() user_b = User.objects.create(username="Fred", password="fred") user_b.save() profilepic = ProfilePic() profilepic.user = user_b profilepic.profile_pic = SimpleUploadedFile(name='test_image.jpg', content=open("/Users/michelangelo/Desktop/FP1/static/images/Jaguar.jpg", 'rb').read(), content_type='image/jpeg') profilepic.save() followedcryptos = FollowedCrypto() followedcryptos.user = user_b followedcryptos.cryptocurrency = "bitcoin" followedcryptos.save() l1 = [] l2 = [] l1.append(followedcryptos) l2.append(followedcryptos.cryptocurrency) data = { "following": l1, "user": user_b, "usr" : user_b.username, "profilepic": profilepic, "crypto": l2 } response = c.get(f"/profile/{user_b.username}", data, follow=True) self.assertEquals(response.status_code, 200) instead of using l1 and l2 to pass the data, I have also directly tried by writing …