Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django want to not show models class
i have one models in Models are some object for example Aries , Taurus and etc . In object are some fields image , title and etc . i want to not show some fields (image, title) in Django admin site ,because this fields is not static it's default. it's is possible ? Model.py from django.db import models class SignsList(models.Model): Title = models.TextField(blank=True, null=True) Image = models.TextField(blank=True, null=True) Date = models.TextField(blank=True, null=True) Daily = models.TextField(blank=True, null=True) Love = models.TextField(blank=True, null=True) Finance = models.TextField(blank=True, null=True) Views.py def singCategory(request,slug,cat): sign = SignsList.objects.get(Title=slug) args = {'sign':sign, 'cat':cat, 'slug':slug,'daily':daily} return render(request,'base3.html',args) Html.file <div class="full_descr"> {%if cat == 'Daily' %} {{ sign.Daily }} {% elif cat == 'Love' %} {{ sign.Love }} {% elif cat == 'Finance' %} {{ sign.Finance }} {% endif %} </div> -
How can a delete request be redirected to a specific url in django rest framework?
Currently, I have made a "Like" model and have implemented "Like" and "Uike" by post and delete requests, respectively. So after implementing Like, I want to implement Unlike, and I know that in order to implement it, I have to select the pk of that Like object, map it to url, and then send a delete request to that url. However, this method requires both url called "/post_id/like/like_id" and "/post_id/like_id", which I do not do, but try to redirect from views to "/post_id/like/like_id" when a delete request is sent to url called "/post_id/like/like". How can I make logic to proceed with the code as I think? Here's my code. views.py class CreateReadLikeView (ModelViewSet) : serializer_class = LikeSerializer permission_classes = [IsAuthenticated] queryset = Like.objects.all() is_saved = False def get_queryset (self) : return super().get_queryset().filter(post=self.kwargs.get('post_id')) def perform_create (self, serializer) : postId = self.kwargs.get('post_id') post = Post.objects.get(pk=postId) try : like = self.queryset.get(post=post, liked_people=self.request.user) except Like.DoesNotExist : serializer.save(liked_people=self.request.user, post=post) self.is_saved = True def create (self, request, *args, **kwargs) : super().create(request, *args, **kwargs) if self.is_saved is True : self.is_saved = False return Response({'success': '해당 게시물을 좋아요 했습니다.'}, status=200) return Response({'message': ['이미 해당 게시물을 좋아요 하였습니다.']}, status=400) def list (self, request, *args, **kwargs) : postId = self.kwargs.get('post_id') … -
Django Search Page with Query Pagination
Hello i have implemented a simple search form and search view to show search result. Now i want to paginate them. But there is a problem with the page in the url. My search url looks like ../search?q=Bla Now if i try to add pagination like: ../search?q=Bla?page=2 (at least thats how i understand it would work) it takes the whole string after q= to my database filter. I took a look at how stackoverflow handles searching and pagination and found out using '&' here is the view code: def search(request): # get query search parameters page = request.GET.get('page', 1) query = request.GET.get('q', '') # query none or empty if query is None or query == '': return redirect('home') # query valid else: # icontains make sure to ignore character sensitivity post_list = Post.objects.filter(title__icontains=query) paginator = Paginator(post_list, 5) try: posts_l = paginator.page(page) except PageNotAnInteger: posts_l = paginator.page(1) except EmptyPage: posts_l = paginator.page(paginator.num_pages) return render(request, 'search.html', {'post_list': posts_l, 'query': query}) and here the HTML Snippet: {% if post_list.paginator.num_pages > 1 %} <div class="pagination"> <span class="step-links mb-5 mx-auto"> {% if post_list.has_previous %} <a class="mr-3" href="?page={{ post_list.previous_page_number }}&q={{ query }}">zurück</a> {% endif %} <span>Seite {{ post_list.number }} von {{ post_list.paginator.num_pages }}</span> {% if post_list.has_next … -
Customize request made by Django drf-yasg
I want to change the request drf-yasg generates and executes in the 'Try it out' editor. My API endpoint accepts a request with query params like query_params = { data: [1, 2], field: "string_value" } <url>?data[]=1&data[]=2&field=string_value but when I have annotated my endpoint with @swagger_auto_schema( method="GET", manual_parameters=[ Parameter("data", IN_QUERY, type=TYPE_ARRAY, items=Items(type=TYPE_STRING)), Parameter("field", IN_QUERY, type=TYPE_STRING), ], ) the 'Try it Out' editor generates the request as <url>?data=1,2&field=string_value Is there any way I can cganhe the way drf-yasg generates the request for a specific type? -
Getting "Incorrect type. Expected pk value, received str." error with Django REST Framework when trying to POST data
While I am aware that there are several topics with the same general problem, I haven't been able to fix my problem using the solutions recommended in them. Most likely due to my total inexperience with Django REST, but nonetheless I am desperate for an answer at this point. I'm creating an application using TypeScript + React in the front and SQLite + Django + DRF on the back. In practice I am creating a questionnaire in which an user goes through questions and answers them. In the end I am trying to send the users answers to my server to be saved in my database. To this end I have an AnswerSet model that contains an array of Answer objects. Here are the models: class AnswerSet(models.Model): questionnaire = models.ForeignKey( Questionnaire, related_name='answer_set', on_delete=models.SET_NULL, blank=True, null=True ) class Answer(models.Model): value = models.CharField(max_length=1000, null=True, blank=True) answerSet = models.ForeignKey( AnswerSet, related_name='answers', on_delete=models.SET_NULL, blank=True, null=True ) question = models.ForeignKey( Question, related_name='answer', on_delete=models.SET_NULL, blank=True, null=True ) As you can see the AnswerSet also has a relation to one Questionnaire and the Answers have a relation to the AnswerSet they belong to as well as the Question they belong to (that's what I'm trying to do … -
Building wheel for psycopg2 ... error pip3 install psycopg2?
When I'm running pip3 install -r requirements.txt then show me errors I show you bellow I'm using python version 3.8 PostgreSQL 13.0 (Ubuntu 13.0-1.pgdg20.04+1) see my requirement.txt files here certifi==2018.4.16 chardet==3.0.4 click==6.7 croniter==0.3.24 Django==2.0.5 django-rq==1.1.0 et-xmlfile==1.0.1 idna==2.7 jdcal==1.4 lxml==4.2.3 openpyxl==2.5.4 #pkg-resources==0.0.0 psycopg2==2.7.5 psycopg2-binary==2.8.5 python-dateutil==2.7.3 python-decouple==3.1 pytz==2018.5 redis==2.10.6 requests==2.19.1 rq==0.12.0 rq-scheduler==0.8.3 six==1.11.0 Unipath==1.1 urllib3==1.23 so show me this error in terminal I share with you complete command message that i typed already pip3 install -r requirements.txt ✔ 2186 17:28:42 Requirement already satisfied: certifi==2018.4.16 in /usr/local/lib/python3.8/dist-packages (from -r requirements.txt (line 1)) (2018.4.16) Requirement already satisfied: chardet==3.0.4 in /usr/lib/python3/dist-packages (from -r requirements.txt (line 2)) (3.0.4) Requirement already satisfied: click==6.7 in /code/data/.local/lib/python3.8/site-packages (from -r requirements.txt (line 3)) (6.7) Requirement already satisfied: croniter==0.3.24 in /code/data/.local/lib/python3.8/site-packages (from -r requirements.txt (line 4)) (0.3.24) Requirement already satisfied: Django==2.0.5 in /code/data/.local/lib/python3.8/site-packages (from -r requirements.txt (line 5)) (2.0.5) Requirement already satisfied: django-rq==1.1.0 in /code/data/.local/lib/python3.8/site-packages (from -r requirements.txt (line 6)) (1.1.0) Requirement already satisfied: et-xmlfile==1.0.1 in /code/data/.local/lib/python3.8/site-packages (from -r requirements.txt (line 7)) (1.0.1) Requirement already satisfied: idna==2.7 in /code/data/.local/lib/python3.8/site-packages (from -r requirements.txt (line 8)) (2.7) Requirement already satisfied: jdcal==1.4 in /code/data/.local/lib/python3.8/site-packages (from -r requirements.txt (line 9)) (1.4) Requirement already satisfied: lxml==4.2.3 in /code/data/.local/lib/python3.8/site-packages (from -r requirements.txt (line 10)) … -
A Value Error As "attempted relative import beyond top-level package"
My Project looks like this : https://imgur.com/B7fHzb4 how do I import the views.py in the pages app onto urls.py file of the trydjango app? when I do : import pages.views gives ValueError: attempted relative import beyond top-level package. when i do: from ..pages import views it says no module pages as hint. -
How are many-to-many relationship handled in Django?
I have a shirt which can contain multiple colors, and multiple colors which can have multiple shirts. Normally I would express it the following way: In django I have the many-to-many (https://docs.djangoproject.com/en/3.1/topics/db/examples/many_to_many/) Example: publications = models.ManyToManyField(Publication) -- Can I create the table "Item_colors" consisting of 2 columns (no "ID" primary key) and design the models according to my diagram using the composite key: class Item_colors(models.Model): class Meta: unique_together = (('cloth_item_id', 'color_id'),) cloth_item_id = models.ForeignKey(Cloth_item, on_delete=models.CASCADE) color_id = models.ForeignKey(Color, on_delete=models.CASCADE) How is the many-to-many relation handled in a DB context, and does it yield better performance? -
Should I use environmental variables or decouple to store sensitive data in Django?
What would be the best option to store sensitive information in a Django project? What’s the difference between Environmental variables or decouple and when should I use each? -
Defining get_queryset in a view, attribute error
I'm trying to write a custom get_queryset function because I want to access the user's email from 'request.user.email', and use that to form another query, that i want to display using my view cartv(generic.ListView). First time asking a question here, scoured the site but haven't found anything similar, but if you do find something just direct me there i''l delete this asap Environment: Request Method: GET Request URL: http://192.168.24.169:8000/products/cart/ Django Version: 3.1.2 Python Version: 3.6.9 Installed Applications: ['products.apps.ProductsConfig', 'accounts.apps.AccountsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] 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'] Traceback (most recent call last): File "/home/nirman/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/nirman/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/nirman/.local/lib/python3.6/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/nirman/.local/lib/python3.6/site-packages/django/views/generic/base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "/home/nirman/.local/lib/python3.6/site-packages/django/views/generic/list.py", line 142, in get self.object_list = self.get_queryset() File "/home/nirman/Desktop/login/products/views.py", line 91, in get_queryset self.user = request.user Exception Type: AttributeError at /products/cart/ Exception Value: 'cartv' object has no attribute 'user' views: class cartv(generic.ListView): model = cart context_object_name = 'cart_list' template_name='products/cartview.html' def get_queryset(request): qs = cart.objects.filter(user__email=request.user.email) #error points here if qs.exists(): c = qs[0] return c.items.all() else: return redirect('failure') -
Django Admin Panel Choices from Database
I have a model that has a IntegerField and in the admin. I want to add choices to the widget as "University" field. There is no problem if i add the universities in list as "uniList". But I do not know how can add these universities from UniversityList Class. I want to add new universities to UniversityList on admin panel and then i want to choose these added universities in Mainland2 admin page. In this case i recieved error massage as "in get raise self.model.MultipleObjectsReturned(mainpage.models.MultipleObjectsReturned: get() returned more than one UniversityList -- it returned 5!" Thank you for in advance... from django.db import models from django import forms from django_countries.fields import CountryField from django.core.exceptions import ValidationError class UniversityList(models.Model): name = models.CharField(max_length=50) class Mainland2(models.Model): unilist = [ (0, "---"), (1, "Uni 1"), (2,"Uni 2"), (3,"Uni 3"), ] graduatedList=[ (0, "Diğer"), (1, "Lise"), (2, "Lise (Öğrenci)"), (3, "Ön Lisans"), (4, "Ön Lisans (Öğrenci)"), (5, "Lisans"), (6, "Lisans (Öğrenci)"), (7, "Yüksek Lisans"), (8, "Yüksek Lisans (Öğrenci)"), (9, "Doktora"), (10, "Doktora (Öğrenci)") ] def validate_digit_length(idName): if not (idName.isdigit() and len(idName) == 11): raise ValidationError('%(idName)s en az 11 karakter olmalıdır', params={'idName': idName}, ) name = models.CharField(max_length=20, verbose_name="Ad") midName = models.CharField(max_length=20, verbose_name="Orta Ad", null=False, blank=True) surName … -
full join 3 django models with ORM
I have following models Django: class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) nickname = models.CharField(max_length=48, blank=True) bio = models.CharField(max_length=60, blank=True) about = models.TextField(blank=True) class SocialItem(models.Model): """ Renders available social network icons and placeholders on UI. Can only be added by admins """ name = models.CharField(max_length=64, unique=True) icon = models.ImageField(upload_to='social_icons', unique=True) placeholder = models.CharField(max_length=128, unique=True) class AccountSocialLink(models.Model): """Adds social network url to user's account""" account = models.ForeignKey(Account, on_delete=models.CASCADE, related_name='social') item = models.ForeignKey(SocialItem, on_delete=models.PROTECT) url = models.URLField() I have an account endpoint that returns the account data in this way: { "id": 5, "nickname": "Constantine", "bio": "Bio", "about": "" "social": [ { "id": 1, "item": 2, "url": "https://www.youtube.com/constantine" }, { "id": 2, "item": 3, "url": "https://www.instagram.com/constantine" }, { "id": 3, "item": 5, "url": "https://www.twitter.com/constantine" } ] } The SocialItem model is used for rendering on UI like in a form. For example, there are 5 social items available, but user has only 3 like above. But I do need to give the user options to fill out the remaining 2. What I need is an aggregation of these 3 models in one output so that the user can update their account by one request. The desired output is: { "id": 5, "nickname": "Constantine", … -
Django manage.py failing. module not found but actually installed in virtualenv
This is a very weird situation. I've been using django and venv for a while and during my last pull of code, when trying to run python manage.py collectstatic I ran into a "module not found" problem. however, this module is installed and if I try to reinstall it pip tells me I already have it. The strange thing is I'm seeing importlib using my system python path ("/usr/lib/python3.6...") which I think it should be my virtualenv path... If I run which python I get the correct venv python path... please help. I attach the error below: File "/home/ubuntu/venv/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django-mailbox' -
How to use SQL database and noSQL database in the same django app?
Is there a good practice to use a SQL database like PostgresSQL with a No SQL database like MongoDB in the same Django app? I know I can define more databases in the settings.py, but how do I tell my models which database to use? Is it a good idea after all or should I use one database in a given Django app? -
Enable to login into the application in Django tests
I am writing the test cases to my application. Please find below code snippet of tests.py class TestGetDetailsPositive(SimpleTestCase): def setUp(self): self.credentials = { 'username': '****', 'password': '****' } @responses.activate def test_get_details(self): self.client.login(username='****', password='****') response = self.client.get('/accounts/selectdetails/') self.assertContains(response, 'National', status_code=200) self.assertTemplateUsed(response, 'accounts/select-details.html') def test_view_url_exists_at_desired_location(self): url = reverse('selectdetails') self.assertEquals(resolve(url).func.view_class, SelectDetails) I am getting below error as follows. AssertionError: Database queries to 'default' are not allowed in SimpleTestCase subclasses. Either subclass TestCase or TransactionTestCase to ensure proper test isolation or add 'default' to accounts.tests.tests.TestGetBanksPositive.databases to silence this failure. Database configuration looks like below DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '****', 'USER': '****', 'PASSWORD': '****', 'HOST': '****', 'PORT': '****', } } Where I am doing wrong? -
create foreignkey object w/ extra actions on post
I have a financials serializer and nested serializers for balancesheets, income statements and cashsflows statements which have their own serializers for each respective componennt I am trying to post through an extra action on the Stock object to create a Financials instance, but receive the error below. what am I doing wrong ? BalanceSheet Serializer 309 class BalanceSheetSerializer(WritableNestedModelSerializer): 310 assets = AssetsSerializer() 311 liab_and_stock_equity = LiabAndStockEquitySerializer() 312 313 class Meta: 314 model = BalanceSheet 315 316 fields = [ 317 # "ticker", 318 "periodicity", 319 "assets", 320 "liab_and_stock_equity", 321 "end_date", 322 "start_date", 323 ] Stock Extra Action 25 @action(detail=True, methods=["post", "get"]) 26 def financials(self, request, ticker=None): 27 if request.method == "GET": 28 stock = self.get_object() 29 financials = stock.get_financials() 30 financials = FinancialsSerializer(financials) 31 return Response(financials.data) 32 if request.method == "POST": 33 stock = self.get_object() 34 serializer = FinancialsSerializer(request.data) 35 Financials.objects.create(serializer.data) 36 Financials.save() ERROR web_1 | AttributeError: Got AttributeError when attempting to get a value for field `assets` on serializer `BalanceSheetSerializer`. web_1 | The serializer field might be named incorrectly and not match any attribute or key on the `str` instance. web_1 | Original exception text was: 'str' object has no attribute 'assets'. web_1 | [14/Oct/2020 11:23:26] "POST /stocks/aapl/financials/ HTTP/1.1" … -
'Select a valid choice' error in Dependent/Chained Dropdown List even if its valid
i'm trying to implement this tutorial:https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html on how to Implement Dependent/Chained Dropdown List with Django he said that we will get an error about select a valid choice i implemented the fix that he provided but the error still there i have been verifying my code from yesterday and it looks fine and the same as the tutorial here is my view class GlobalLessonView(CreateView): model = Lesson form_class = GlobalLessonForm success_url = reverse_lazy('globalform') def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs.update(request=self.request) return kwargs forms.py from django.conf import settings db_name = settings.DATABASES['default']['NAME'] class GlobalLessonForm(forms.ModelForm): class Meta: model = Lesson fields = '__all__' def __init__(self, request, *args, **kwargs): school_id = request.session['school_id'] super().__init__(*args, **kwargs) self.fields['subject'].queryset = Subject.objects.none() #change to .all() to see list of all subjects self.fields['level'].queryset = Level.objects.filter(school__id= school_id) if 'level' in self.data: try: level_id = int(self.data.get('level')) self.fields['subject'].queryset = Subject.objects.extra(where=[db_name+'.scolarité_subject.id in( select subject_id from '+db_name+'.scolarité_levelsubject where level_id='+level_id+')']) except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['subject'].queryset = self.instance.level.subject_set lesson_form.html <form method="post" id="globallessonform" data-subjects-url="{% url 'ajax_load_subjects' %}" novalidate> {% csrf_token %} <table> {{ form.as_table}} </table> <button type="submit">Save</button> </form> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("#id_level").change(function () { var url = $("#globallessonform").attr("data-subjects-url"); // get the url of the … -
"Cannot import ASGI_APPLICATION module %r" % path channels problem
I got this error: ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path) Here is my routing.py: from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from channels.auth import AuthMiddlewareStack from django.urls import path from messanger.contacts.consumers import ChatConsumer application = ProtocolTypeRouter({ # Empty for now (http->django views is added by default) 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( [ path('user-notification', ChatConsumer) ] ) ) ) }) When i remove this line of code, runserver work: from messanger.contacts.consumers import ChatConsumer But i don't understand what's wrong with my consumers file in contacts app: from channels.consumer import AsyncConsumer class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): await self.send({ "type": "websocket.accept", }) async def websocket_receive(self, event): await self.send({ "type": "websocket.send", "text": event["text"], }) -
Django compilemessages doesn't work with some uft-8 characters
I'm setting up internationalization in a Django project using i18n. In /landing/locale/es/LC_MESSAGES, I created a po file with phrases and started python manage.py compilemessages, it worked fine, but when starting the server I get this error: File ".../venv/lib/python3.6/site-packages/django/contrib/auth/forms.py", line 10, in <module> from django.contrib.auth.models import User File "...venv/lib/python3.6/site-packages/django/contrib/auth/models.py", line 33, in <module> class Permission(models.Model): File ".../venv/lib/python3.6/site-packages/django/db/models/base.py", line 111, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class django.contrib.auth.models.Permission doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. This occurs only in Spanish, or with the '`' symbol. If you delete the .mo translation file, the server starts normally. I think the problem is the encoding. Is there any way to set UTF-8 encoding for translation files? I use UTF-8 encoding for .po files -
Django: Duplicate in result API storing DB
I hope you're well. I'm using an API. Everything works well. Except one thing. When I try to store my category related to API result I got a duplicate... I've tried to add a .distinct() but that does not work. For each post I got got a duplicate Typerepas. Assume we got a salad (Typerepas: Main courses), If we click on Main courses we'll have two times the same post... I've tried to do it manually with Admin panel. There is no duplicate, so I guess the issue is in the code. class Typerepas(models.Model): name = models.CharField(max_length=20) ... class Post(models.Model): title = models.CharField(max_length=190) typederepas = models.ManyToManyField('Typerepas',blank=True, related_name='typederepas_posts') ... if result_title: response_title_data = result_title.json() try: for dishtypes in response_title_data['results'][0]['dishTypes']: if dishtypes == "main course" or dishtypes == "marinade" or dishtypes == "salad" or dishtypes == "main dish": current_post = get_object_or_404(Post, slug=self.slug) typerepas = Typerepas.objects.get(name="Main courses") current_post.typederepas.add(typerepas) elif dishtypes == "soup" or dishtypes == "fingerfood": current_post = get_object_or_404(Post, slug=self.slug) typerepas = Typerepas.objects.get(name="Starters") current_post.typederepas.add(typerepas) elif dishtypes == "beverage" or dishtypes == "drink": current_post = get_object_or_404(Post, slug=self.slug) typerepas = Typerepas.objects.get(name="Drinks") current_post.typederepas.add(typerepas) elif dishtypes == "side dish": current_post = get_object_or_404(Post, slug=self.slug) typerepas = Typerepas.objects.get(name="Trimmings") current_post.typederepas.add(typerepas) elif dishtypes == "dessert": current_post = get_object_or_404(Post, slug=self.slug) typerepas = … -
Setting a property into request in Django test client
I have a middleware (tenant_schemas.BaseTenantMiddleware) that will inject tenant property into the request object. I can't use that middleware when unit testing. In a view I can then get the tenant object from the request. This view is mapped to the URL "myapp:member_info". class MemberView(TemplateView): template_name = 'myapp/member.html' def get_context_data(self, member_id=None, *args, **kwargs): ctx = super().get_context_data(*args, **kwargs) tenant = self.request.tenant ctx['tenant_name'] = tenant.name return ctx This view works when the project is run normally as the middleware will set request.tenant correctly. Now, if I want to test this view I try to write following test: class MemberViewTest(TestCase): def setUp(self): self.tenant = Tenant(name="test tenant") self.member = Member.objects.create( first_name='Test', last_name='Person') def test_saldo(self): self.client = Client(tenant=self.tenant) # Here I try to inject the tenant into the request print(self.client.defaults) # This will print {'tenant': <Tenant: test tenant>} response = self.client.get(reverse('myapp:member_info', kwargs={ 'tenant': self.tenant, 'member_id': self.member.token })) This test fails to error: File "myapp/views.py", line xxx, in get_context_data tenant = self.request.tenant AttributeError: 'WSGIRequest' object has no attribute 'tenant' So, the django.tests.Client class is not injecting the defaults to the request. One thing I tried is to override the RequestFactory (https://github.com/django/django/blob/ac6c4260074de43a978e5c6553ef89441e1d6748/django/test/client.py#L308) so that it would inject the tenant. class TenantRequestFactory(RequestFactory): def request(self, **request): req = super().request(**request) … -
Why firstname and lastname fields are stored after fail validation which password doesn't
I have a registration form there are have few fields including first name, last name, password and password confirm. I'm wondering why first name and last name value still in the form after the form fail in validation while password field doesn't. What makes those fields behave differently from each other. -
how to test a graphene mutation with **kwargs on mutate function?
I am testing a mutation that creates a user something like this: def test_create_user(self): user_mutation = """ mutation($id: ID!, $group: GroupInput!, $address: AddressInput!){ createUser(id: $id, group: $group, address: $address) { user { id } } } """ group = { 'name': 'GroupA', 'contact': '1231323131' } address = { 'street': '123', 'city': 'Test City' } resp = self.client.execute(user_mutation, variable_values={ 'id': str(uuid.uuid4()), 'group': group, 'address': address }) The Mutation Class: class CreateUser(graphene.Mutation): class Arguments: id = graphene.String(required=True) group = GroupInput(required=True) address = AddressInput(required=True) ...more input here user = graphene.Field(UserType) def mutate(self, info, **kwargs): user = create_user(**kwargs) return CreateUser(user=user) The problem is that when I try to run this test is it return an error: test_create_user {'errors': [{'message': "create_user() got an unexpected keyword argument 'group'", 'locations': [{'line': 4, 'co lumn': 25}], 'path': ['createUser']}], 'data': OrderedDict([('createUser', None)])} I'm not sure how should I go about this and I use kwargs because there is much more input to be added here. Any ideas and suggestions is greatly appreciated! -
The submitted data was not a file. Check the encoding type on the form. This error showing up while submitting image through react hook forms
Hi guys I am getting this error while submitting this form with an image through react hook form. This is the error I am getting from the backend. {image: ["The submitted data was not a file. Check the encoding type on the form."],…} image: ["The submitted data was not a file. Check the encoding type on the form."] 0: "The submitted data was not a file. Check the encoding type on the form." But I am able to make it work without any problems through postman. I am new to react, can anyone help to solve this. I am using django in the backend and django rest framework for api endpoints. form. import React, { useState } from 'react'; import axiosInstance from '../../axios'; import { useForm } from 'react-hook-form'; //MaterialUI import Button from '@material-ui/core/Button'; import CssBaseline from '@material-ui/core/CssBaseline'; import TextField from '@material-ui/core/TextField'; import Grid from '@material-ui/core/Grid'; import Typography from '@material-ui/core/Typography'; import { makeStyles } from '@material-ui/core/styles'; import Container from '@material-ui/core/Container'; const useStyles = makeStyles((theme) => ({ paper: { marginTop: theme.spacing(9), display: 'flex', flexDirection: 'column', alignItems: 'center', }, form: { width: '100%', // Fix IE 11 issue. marginTop: theme.spacing(1), }, submit: { margin: theme.spacing(3, 0, 2), }, input: { display: "none", … -
only one slug provided but URL is taking two parameters
I am trying to test my application and found out the I provided only one parameter as a slug but the URL is using two. I have added slug in the urls.py and in the HTML form as well. Here is the code example: URLs: urlpatterns = [ ... path('edit/<slug:loanid>/', views.edit, name="edit"), path('edituser/<int:userid>/', views.edituser, name="edituser"), ] Views: def edit(requests, loanid): if (requests.user.is_authenticated and requests.user.userrank.userstatus == 'Agent'): loan = Loan.objects.get(loanid=loanid) history = loan.history.all() # print(history) loanstatus = Loan.objects.filter(loanid=loanid).values('loanstatus') if loanstatus[0]['loanstatus'] == 'Approved' or loanstatus[0]['loanstatus'] == 'Rejected': return JsonResponse({"message": "Loan is approved Cannot Edit"}) else: return render(requests, 'edit.html', {'loan': loan, 'history': history}) else: return HttpResponseForbidden() def edituser(requests, userid): if (requests.user.is_authenticated and requests.user.userrank.userstatus == 'Agent' or requests.user.userrank.userstatus == 'Admin'): user = User.objects.get(pk=userid) return render(requests, 'edituser.html', {'user': user}) else: return HttpResponseForbidden() Here are the templates and form used to render: <form action="/edituser/{{eachuser.id}}/" method="GET" class="status"> <input type="hidden" value="{{eachuser.id}}" name="loanid"/> <input type="submit" value="Edit" class="btn btn-primary"/> </form> <form action="/edit/{{eachloan.loanid}}/" method="GET" class="status"> <input type="hidden" value="{{eachloan.loanid}}" name="loanid"/> <input type="submit" value="Edit" class="btn btn-primary"/> </form> URLs that are showing in the browser: http://127.0.0.1:8000/edituser/19/?loanid=19 http://127.0.0.1:8000/edit/a38aa1b6-9158-4d71-a725-dc5406184aec/?loanid=a38aa1b6-9158-4d71-a725-dc5406184aec