Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
view count increase in DRF
I need to increase the view count with 1 on each refresh. I'm not sure about the method since I'm new to DRF. Thanks in advance. models.py class Module(models.Model): name = models.CharField(max_length=250, default="") view_count = models.IntegerField(default=0) serializers.py class ModuleSerializer(serializers.ModelSerializer): class Meta: model = Module fields = "__all__" views.py class ModuleView(generics.ListAPIView): queryset = Module.objects.all() serializer_class = ModuleSerializer def get(self, request): obj = self.get_object print(obj) obj.view_count = obj.view_count + 1 obj.save(view_count="view_count") return super().get(request) -
How to search models Django
Given: the id of the contract (eg 32812) get from the objects of the credit application model (!!!) unique id manufacturers of all goods that are associated with this contract in the performance of try to minimize the reference to the database class Credit(models.Model): """ Кредитная заявка. Только один контракт но несколько товаров """ name_credit = models.TextField(max_length=200, verbose_name='name_credit',null=True) contract = models.ForeignKey('Contract', verbose_name='contract', related_name='contract', on_delete=models.CASCADE) # product = models.ForeignKey('Product', # verbose_name='product', # related_name='product', # on_delete=models.CASCADE) date = models.DateField(verbose_name='date', blank=True, null=True) def __str__(self): return "%s" % self.name_credit class Meta: verbose_name = 'Кредитная заявка ' verbose_name_plural = 'Кредитные заявки' class Contract(models.Model): """ Контракт связан с кредитной заявкой """ #product = models.ForeignKey('Product', on_delete=models.CASCADE, related_name='product', null=True) contracts = models.TextField(max_length=200, verbose_name='contracts') date = models.DateField(verbose_name='date', blank=True, null=True) credit = models.ForeignKey(Credit, on_delete=models.CASCADE, null=True, blank=True,related_name='credit') manufacturer = models.ForeignKey('Manufacturer', on_delete=models.CASCADE, null=True) def __str__(self): return "%s" % self.contracts class Meta: verbose_name = 'Контракт ' verbose_name_plural = 'Контракты' class Product(models.Model): """ Товар имеет только одного производителя """ credit = models.ForeignKey(Credit, on_delete=models.CASCADE, null=True, blank=True) products = models.TextField(max_length=100, verbose_name='products') manufacturer = models.ForeignKey('Manufacturer', on_delete=models.CASCADE, related_name='manufacturer', null=True, blank=True) def __str__(self): return "%s" % self.products class Meta: verbose_name = 'Товар' verbose_name_plural = 'Товары' class Manufacturer(models.Model): """ Производитель производит только один продукт """ name = models.TextField(max_length=200, verbose_name='name') #product … -
Print subprocess stdout line by line in real time in Django StreamHttpResponse
I wrote an API in Django. It runs a shell script in the server and prints some logs. When the clients calls the API in the browser, I want the browser to print the logs line by line. So far, the snippet is like: from django.http import StreamingHttpResponse import subprocess import shlex def test(request): cmd = 'bash test.sh' args = shlex.split(cmd) proc = subprocess.Popen( args, cwd='/foo/bar', shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) return StreamingHttpResponse( (line for line in iter(proc.stdout.readline, '')), content_type="text/plain", ) And test.sh is like #!/bin/bash echo hello sleep 1 echo world sleep 1 echo love sleep 1 echo and sleep 1 echo peace sleep 1 The logs are not printed until bash test.sh is finished. How can I make it print the logs as if test.sh is run in the client? I'm using Python 2.7 and Django 1.11.29. I know they are old, but I still have to use them now. Thanks for help. -
How to change the value of a boolean in a model after a certain period of time in django?
I'm building a rental application in Django which has a boolean field rental_status. rental_status = models.BooleanField(default = False) rental_status describes if the product is already rented or is available to rent. the default value is true i.e is available for rent. Consider a situation where a person rents out the product for x amount of time and we change the rental_status to false. So, My question is how can we change rental_status to true after x time so that it can be rented again. (I understand if my way of implementation is not good or ideal but it is just for a project. Please suggest if there are any other better implementations) -
Why set value on select option from django form not work?
I have codes in django template like this <label for="exampleFormControlInput1" class="form-label text-primary">Jenis Kelamin</label> <div class="input-group mb-3"> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="jenis_kelamin_radio" id="inlineRadio1" value="laki-laki"> <label class="form-check-label" for="inlineRadio1">Laki-Laki</label> </div> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="jenis_kelamin_radio" id="inlineRadio2" value="perempuan"> <label class="form-check-label" for="inlineRadio2">Perempuan</label> </div> </div> call django form which widget is select {{ peserta_form.jenis_kelamin }} and Jquery code like this <script> $(document).ready(function(){ $('input:radio[name="jenis_kelamin_radio"]').change(function(){ if($(this).val() == 'laki-laki'){ $('#jenis_kelamin').val("Laki-Laki").change(); } else if($(this).val() == 'perempuan'){ $('#jenis_kelamin').val("Perempuan").change(); } }); }); </script> but not work, please help. thanks -
Django Rest framework how to create Family and assign members to that family while assigning roles to each member
I have my parishioner model like below (Only pasting relevant CODE) class Parishioner(models.Model): family = models.ForeignKey(Family, null=True, on_delete=models.PROTECT, related_name='members') role = models.ForeignKey(FamilyRole, null=True, blank=True, on_delete=models.PROTECT, related_name='role') Parishioner can have one Family and One role in that family So I'm trying to achieve this in my Family Serializer. class FamilySerializer(serializers.ModelSerializer): members = serializers.PrimaryKeyRelatedField( many=True, queryset=Parishioner.objects.all(), allow_null=True, required=False ) class Meta: model = Family fields = ('id', 'name', 'address', 'monthly_contribution', 'members', 'enabled') read_only_fields = ('id',) depth = 1 As you can see above I can clearly assign members to that Family. But I want to assign roles to Each family member as well. How can I do that in Django ? Examples for FamilyRole: Father, Mother, son, daughter My front end will be similar to this in my Create Family page (and I expect to send only one request to server to achieve this by using api/family/ endpoint) Simply I want to, Create a Family, Assign Members(Parishioners) to that Family, Assign Role to each of those Member(Parishioner), Through api/family/ endpoint. What is the best way to achieve above ? -
Get Local vars in Django
is there a way to print the Local Vars of the view in the template, like the one shown in the error page of django? I need it to be able to quickly see the contents of the variables during the debug and test phases like this -
Creating two different profiles in one application
I am building a BlogApp App and I have two different sections, One is Blog Section and another is Article Section. AND i am trying to create two different profiles for them. When a user register or signup then a Profile is successfully creating for Blog Section ( NOT Article section ). BUT i am trying to do :- When user click on Article section after signup then there will be option of creating another Profile for Article Section and both will be different profile. ( AND there will be no relation between Blog Profile and Article Profile BUT user will same ) Blog Profile is successfully creating BUT I am trying to make Article Profile. models.py class ArticleProfile(models.Model): user = models.ForeignKey(User,default='',null=True,on_delete=models.CASCADE) full_name = models.CharField(max_length=30,default='') views.py def create_profile(request): if request.method == 'POST': form = ArticleProfileForm(request.POST,request.FILES,instance=request.user) if form.is_valid(): custom_form = form.save(False) custom_form.save() messages.success(request, "Article Profile is Created") return redirect('dating:DatingSection') else: form = ArticleProfileForm(instance=request.user) context = {'form':form} return render(request, 'dating/create_profile.html', context) BUT when i create profile using this form then it is not saving in Admin. Any help would be Appreciated. Thank You in Advance. -
Django real time applications
is there a way to make real time applications in Django other than channels? I can't understand it and even copying the code isn't enough to make it work, is it possible to use react js to make chat app and integrate it into Django project? I really need to learn building real time applications but I can't find a tutorial -
Why is Docker not picking up code changes, despite 'prune all', 'build no cache' and then 'up force recreate'?
I'm dockerising a django app (webapp). However, when I make code changes they do not seem to be reflected when the container is rebuilt. I'm trying to test that I can hit 'app' but the name has changed to 'newapp'. testcase.py from django.test import TestCase import requests class TestServerUp(TestCase): def testhitendpoint(self): r = requests.get(host='app', port=1234) self.assertEquals(r.status_code, 200) Running the command sudo docker exec -it webapp python manage.py test tests.testcase fails because host should be 'newapp' requests.exceptions.ConnectionError: HTTPConnectionPool(host='app', port=1234): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fd97d430550>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')) I change the test case to: from django.test import TestCase import requests class TestServerUp(TestCase): def testhitendpoint(self): r = requests.get(host='newapp', port=1234) self.assertEquals(r.status_code, 200) I bring the containers down: sudo docker-compose -f ./deploy/docker-compose.yaml down I remove the containers from docker: sudo docker system prune --all --volumes -f, then sudo docker rm -f $(sudo docker ps -aq) just to be sure. I rebuild the containers: sudo docker-compose -f ./deploy/docker-compose.yaml build --no-cache I then spin the containers up: sudo docker-compose -f ./deploy/docker-compose.yaml up --force-recreate -d I run the tests again: sudo docker exec -it webapp python manage.py test tests.testcase (or sudo … -
Django forms difference, one works, the second one doesn't
I've got a kind strange problem. I've got two different (but almost the same forms and validation). The validation in first one works, in the second one doesn't. Can someone tell me why? 1) class SignUpForm1(forms.Form): test_value = forms.CharField( label='Your name', max_length=100, widget=forms.TextInput(attrs={'class': "input"}) ) def clean_test_value(self): data = self.cleaned_data.get('test_value') if data != "abc": raise forms.ValidationError("Error") return data class SignUpForm2(forms.Form): name = forms.CharField( label='name', max_length=100, widget=forms.TextInput(attrs={'class': "input"}) ) def clean_name_value(self): data = self.cleaned_data.get('name') if data != "abc": raise forms.ValidationError("Error") return data -
Django Models: Accessing Parent Object Attribute Within a Related Object Using OneToOneField
I am trying to access the username attribute of a Django User object from a Profile object that is related by a OneToOneField. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) username = models.TextField(default=user.username, primary_key=True) image = models.ImageField(upload_to='images/profile') header = models.CharField(max_length=64) slug = AutoSlugField(populate_from='x') bio = models.CharField(max_length=300, blank=True) The intent of this is to be able to get a Profile object using a ReactJS frontend by passing the username provided at login back to a profile detail endpoint in a Django API, where the username is the primary key for the endpoint. path('<pk>/profile/', ShowProfilePageView.as_view(), name='show_profile_page'), I've tried many different things for the default argument passed to the Profile username attribute, but nothing is working so far. Is this even possible? -
Request always returns unauthorized sent from React-Native to Django
i am trying to send a get request from my react-native app to a django api but i always get the error {"detail":"Authentication credentials were not provided."}. but when i try this same request on postman everything works, i tried getting the code from postman itself and copied it to my react-native app but its the same unauthorized error this is the code generated from the above postman request and i copy and pasted directly to my react-native app and it throws the above unauthorized message. also tried the generated code from postman for curl and it works, Please let me know what i am missing here var myHeaders = new Headers(); //you can assume the token is correct myHeaders.append("Authorization", "Token f38be1f33dbb5d6004108990a0a76"); var requestOptions = { method: 'GET', headers: myHeaders, redirect: 'follow' }; fetch("https://base_url/api/v1/endpoint", requestOptions) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error)); -
Django incorrect padding
so when I was creating my site and finished the frontend I wanted to open the admin dashboard and tada Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 3.0.14 Python Version: 3.6.8 Installed Applications: ['jazzmin', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main'] 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 "C:\Users\mohamd\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\sessions\backends\base.py", line 199, in _get_session return self._session_cache During handling of the above exception ('SessionStore' object has no attribute '_session_cache'), another exception occurred: File "C:\Users\mohamd\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\mohamd\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\mohamd\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\mohamd\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\sites.py", line 249, in wrapper return self.admin_view(view, cacheable)(*args, **kwargs) File "C:\Users\mohamd\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\mohamd\AppData\Local\Programs\Python\Python36\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\mohamd\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\sites.py", line 220, in inner if not self.has_permission(request): File "C:\Users\mohamd\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\sites.py", line 194, in has_permission return request.user.is_active and request.user.is_staff File "C:\Users\mohamd\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\functional.py", line 224, in inner self._setup() File "C:\Users\mohamd\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\functional.py", line 360, in _setup self._wrapped = self._setupfunc() File "C:\Users\mohamd\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\auth\middleware.py", line 24, in <lambda> request.user = SimpleLazyObject(lambda: get_user(request)) File "C:\Users\mohamd\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\auth\middleware.py", line 12, in get_user request._cached_user = auth.get_user(request) File "C:\Users\mohamd\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\auth\__init__.py", line 173, … -
Django IntegrityError UNIQUE constraint failed: plans_customer.user_id
I have a problem with my checkout view. After I added user verification via email, I am geting integrity error. I would like to know how to solve this issue. I have alredy checked some of the solutions from the internet but none of them works for me. Some basic info: Request Method: POST Request URL: http://127.0.0.1:8000/checkout Django Version: 2.2.3 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: plans_customer.user_id Here is my checkout view: @login_required def checkout(request): try: if request.user.customer.membership: return redirect('settings') except Customer.DoesNotExist: pass coupons = {'bank':25, 'city':25} if request.method == 'POST': stripe_customer = stripe.Customer.create(email=request.user.email, source=request.POST['stripeToken']) plan = 'price_1IC3TwL0fAQS9DO5lqZSmcew' if request.POST['plan'] == 'yearly': plan = 'price_1IC3TwL0fAQS9DO5IKzHz5ZI' if request.POST['coupon'] in coupons: percentage = coupons[request.POST['coupon'].lower()] try: coupon = stripe.Coupon.create(duration='once', id=request.POST['coupon'].lower(), percent_off=percentage) except: pass subscription = stripe.Subscription.create(customer=stripe_customer.id, items=[{'plan':plan}], coupon=request.POST['coupon'].lower()) else: subscription = stripe.Subscription.create(customer=stripe_customer.id, items=[{'plan':plan}]) customer = Customer() customer.user = request.user customer.stripeid = stripe_customer.id customer.membership = True customer.cancel_at_period_end = False customer.stripe_subscription_id = subscription.id customer.save() msg_plain = render_to_string('mails/email.txt') msg_html = render_to_string('mails/email.html') subject = 'Welcome to J & M Traders' recepient = str(request.user.email) send_mail(subject, msg_plain, EMAIL_HOST_USER, [recepient], html_message=msg_html) return redirect('home') else: coupon = 'none' plan = 'monthly' price = 9999 og_dollar = 99.99 coupon_dollar = 0 final_dollar = 99.99 if request.method == 'GET' and 'plan' … -
Unexpected aguments when saving a form in Django
I am trying to save form data using Django. My app is a very basic car maintenance app I am creating to learn Django. Here is my Views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.http import HttpResponse from service.models import Service from service.forms import oil_change # Create your views here. @login_required(login_url='/login/') def service(request): obj = User obj = Service.objects.filter(user=request.user) temp = list(Service.objects.all()) print("here") if temp: result = temp[0] return render(request, 'serviceT/service.html', {'object': obj, 'result': result}) return render(request, 'serviceT/service.html', {'object': obj}) @login_required(login_url='/login/') def update_miles(request): obj = User obj = Service.objects.filter(user=request.user) context = {'object': obj} if (request.method == 'POST'): Service.objects.all().delete() form = oil_change(request.POST) if (form.is_valid()): miles = form.cleaned_data["miles"] last_change = form.cleaned_data["last_change"] reminder = form.cleaned_data["reminder"] next_change = reminder + miles oil_change(user=request.user, miles=miles, last_change=last_change, reminder=next_change).save() return render(request, 'serviceT/service.html', context) else: form = oil_change() return render(request, 'serviceT/miles.html', {'form': form}) The issue in on the line where I try to save the form. oil_change(user=request.user....) Here is my forms.py and models.py from django import forms from django.core import validators from django.forms import ModelForm from service.models import Service class oil_change(forms.ModelForm): class Meta: model = Service fields = ['miles', 'last_change', 'reminder'] widgets = { 'miles': forms.NumberInput(), 'last_change': forms.NumberInput(), 'reminder': forms.NumberInput() } from … -
Template has_changed always true on page load with initial form value
I’m having an issue on understanding how to render a page with Django the correct way. I would like the initial page to load with the below form only. Then after posting and getting back data, display the results. The issue I’m having is when i add an initial end date, the page loads with anything in the if statement. forms.py class TrainingStatsForm(forms.Form): start_date = forms.CharField(label='Start Date', max_length=12, widget=DateInput()) end_date = forms.CharField(label='End Date', max_length=12, widget=DateInput(), initial=datetime.date.today) dog = forms.ModelChoiceField(queryset=k9Table.objects.all()) If I remove the initial=datetime.date.today. Then the page load correctly Views.py def trainingstats(request): if request.POST: date_data = TrainingStatsForm(request.POST) if date_data.is_valid(): start_date = date_data.cleaned_data['start_date'] end_date = date_data.cleaned_data['end_date'] dog = date_data.cleaned_data['dog'] requested_search_training = TrainingTable.objects.filter(date__gte=start_date, date__lte=end_date, dog=dog).order_by('-date') requested_search_detection = DetectionTable.objects.filter(date__gte=start_date, date__lte=end_date, dog=dog).order_by('-date') requested_search = sorted( chain(requested_search_training, requested_search_detection), key=lambda data: data.created, reverse=True else: date_data = TrainingStatsForm() requested_search_training = None requested_search_detection = None requested_search = None total_time = 0 content = { 'returned_data': returned_data, 'date_data': date_data, 'requested_search': requested_search, } return render(request, 'trainingstats.html', content) Template <form method="post"> {% csrf_token %} <div class="form-row"> <div class="form-group col-md-2 mb-0"> {{ date_data.dog|as_crispy_field }} </div> <div class="form-group col-md-2 mb-0"> {{ date_data.start_date|as_crispy_field }} </div> <div class="form-group col-md-2 mb-0"> {{ date_data.end_date|as_crispy_field }} </div> </div> <div class="form-row"> <input type="submit" value="Submit" class="btn btn-primary"/> </div> </form> {% … -
Django Rest Framework: XLSXRenderer -- How to check condition for queryset and return a Response
from rest_framework.viewsets import ReadOnlyModelViewSet from drf_renderer_xlsx.mixins import XLSXFileMixin from drf_renderer_xlsx.renderers import XLSXRenderer from .models import MyExampleModel from .serializers import MyExampleSerializer class MyExampleViewSet(XLSXFileMixin, ReadOnlyModelViewSet): serializer_class = MyExampleSerializer renderer_classes = [XLSXRenderer] filename = 'my_export.xlsx' def get_queryset(self): start_date = self.request.query_params.get('start_date', None) end_date = self.request.query_params.get('end_date', None) queryset = MyExampleModel.objects..filter(created__range=[start_date, end_date]) Return queryset # What I want to do # If not queryset: # Return Response({"message": "Exporting Fail"}) # Is there a way to check if queryset is None and return a Error Message instead of an empty Excel # I think that I not allow return Response in the get_queryset function Currently, I am trying to build a function to export excel file. I just want to know is there a way to check if the queryset is None and then I can return a Response({"message": "Exporting Fail, Empty"}) If you know where can I research it would help me a lot. Thank you so much -
PasswordResetForm change default protocol from http to htttps Three questions
this is whats written in the documentation protocol: http or https this is the link to documentation https://docs.djangoproject.com/en/3.2/topics/auth/default/#django.contrib.auth.forms.PasswordResetForm this is the link to the source code https://github.com/django/django/blob/ac2e6e686906810e9c24ca6c39cae6234ab25557/django/contrib/auth/forms.py#L316 three questions: first question(main question): how do u change the default protocol from http to https, So that the user will click the https link instead of http in their email to reset their password ps: i am using django default class based views second question(technical question): the django default reset pass link does not work on safari browser, works on all other browsers why? and is there anything i can do for that? third question(fundamental question): after all these years being an amateur programmer for fun, Its video explanation and stockoverflow copy and paste or Me trying and guessing, doc never helped, i still have no idea how to read the docs, its all there, i have the source code, i have the doc, it does say protocol: http or https and in the source code it does say def save(use_https=False) BUT it does not say how to use it, it does not say where to put protocol:http/https or is it protocol=http/https or is it def protocol..., theres no example, no DO … -
Django Database Routing
I am having 3 databases defined in the Settings.py and routers for two apps in the respective app folders. When I try to run manage.py migrate --database="app_db" respectively for apps, it only runs default and second database list item. If I change the order of database list it won't perform the last one but only second one. Settings.py INSTALLED_APPS = [ # django apps "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", # my apps "cred", "dms", # third party apps "rest_framework", ] DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "databases/db.sqlite3", }, "dms_db": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "databases/dms.sqlite3", }, "cred_db": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "databases/cred.sqlite3", }, } DATABASE_ROUTERS = [ "dms.routers.DMSRouter", "cred.routers.CredRouter", ] AUTH_USER_MODEL = "cred.User" CRED_DB_ROUTER = "cred_db" DMS_DB_ROUTER = "dms_db" if I put dms_db at list index 1 then it will migrate but cred_db won't. If I put cred_db at index 1 then it will migrate but dms_db won't. Cred.Router.py from django.conf import settings class CredRouter: route_app_labels = ["auth", "cred", "contenttypes"] def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return settings.CRED_DB_ROUTER return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return settings.CRED_DB_ROUTER return None def allow_relation(self, obj1, obj2, **hints): if ( obj1._meta.app_label … -
Django 'NoneType' object has no attribute '_meta'
any solution for this error 'NoneType' object has no attribute '_meta' Request Method: GET Request URL: http://127.0.0.1:8000/api/register/ Django Version: 3.1.2 Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute '_meta' Exception Location: /opt/anaconda3/envs/catermahalENV/lib/python3.8/site-packages/rest_framework/utils/model_meta.py, line 96, in _get_forward_relationships Python Executable: /opt/anaconda3/envs/catermahalENV/bin/python Python Version: 3.8.8 serializers.py class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'name', 'email', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user( validated_data['name'], validated_data['email'], validated_data['password']) return user views.py class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, 'token': AuthToken.objects.create(user)[1] }) -
Count branches in queryset
Django==3.2 At a breakpoint I have such queryset: <QuerySet [<UsingSemanticsLevelTwo: 2. Дубаец - 3. green_dubai_TR>, <UsingSemanticsLevelTwo: 2. Дубаец - 2. dubai_TR>, <UsingSemanticsLevelTwo: 1. Вас вызывает Дубай 1 - 4. dubai_COMP>]> Model: class UsingSemanticsLevelTwo(models.Model): branch = models.ForeignKey("clients.Branch", on_delete=models.PROTECT, blank=True, null=True, verbose_name=gettext("Branch"), related_name="%(app_label)s_%(class)s_related", related_query_name="%(app_label)s_%(class)ss", ) Problem I want to count distinct branches in a queryset. queryset.annotate(Count("branch"), distinct=True) It blows up: {TypeError}QuerySet.annotate() received non-expression(s): True. Could you help me? -
How to access the related objects using select_related
I have 3 models as stated below - orders class Orders(BaseModel): created_by = models.ForeignKey(User, on_delete=models.PROTECT, null=False, blank=False) property = models.ForeignKey(Properties, on_delete=models.PROTECT, null=False, blank=False) .... .... properties class Properties(BaseModel): property_long_name = models.CharField(max_length=255, blank=False) property_trading_name = models.CharField(unique=True, max_length=255, blank=False) .... .... property owners class PropertyOwners(BaseModel): property = models.ForeignKey(Properties, related_name='property_owners', on_delete=models.PROTECT, blank=False, null=False) owner = models.ForeignKey(User, on_delete=models.PROTECT, blank=False, null=False) .... .... I am trying to query on Orders and want to put a lock on the rows it will return. I also want to lock the related row of Properties model. Furthermore, those properties will have one or many owners which is stored in model PropertyOwners. I want to lock those rows of ProprertyOwners which are related to the property of that order. So far I have tried to do it like this, but it did not work and returned me an error - Queryset Orders.objects.select_related('property__property_owners').select_for_update().exclude(created_by=created_by).values('id', 'property', 'units', 'created_by', 'sell_price_per_unit', 'order_status').filter(property=order_obj.property, order_type__name=SELL, order_status__in=[PARTIALLY_COMPLETED[1], OPEN[1]], sell_price_per_unit__lte=order_price).order_by('sell_price_per_unit') error - django.core.exceptions.FieldError: Invalid field name(s) given in select_related: 'property_owners'. Choices are: property_type, created_by, approved_by, property_manager All the order returned by the queryset will belong to just one property. A property may have one or more many owners. -
How to Debug Django Javascript within VSCode?
I was wondering if there is a solution to Debug Django Javascript with in VSCode. VScode Chrome Debuger seems very popular. Is it possible to use that together with Django server enviorment? untill now i tried following setting in my config: { "name": "Launch Chrome", "request": "launch", "type": "pwa-chrome", "url": "http://localhost:8080", "webRoot": "${workspaceFolder}/path/to/static/files" }, webRoot is the same path as my STATIC_ROOT constant from settings.py Any Ideas? For me the solution does not to be nessesarly the VSChrome-Debugger, I just dont want to debug JS in Chrome directly all the time ^^. Thanks!! -
How to edit custom field in django TabularInline
I have a following inline model under company management. i want to make editable those custom field under company detail page. anyone has a suggestion that how to make editable field 'email', 'name' and 'role'. I will send it to API while submitting. so it's not concern that how to save it. Following is my inline model class CompanyUserInfoTAB(admin.TabularInline): model = Userrolemapping fields = ['id', 'email', 'name','role'] extra = 0 can_delete = False verbose_name = 'COMPANY USERs' verbose_name_plural = verbose_name def email(self, obj): return obj.user.email def name(self, obj): return obj.user.name def role(self, obj): return UserType.objects.get(usr_type_id=obj.role_id).name def company_id(self, obj): return obj.company.id def get_queryset(self, request): qs = super(CompanyUserInfoTAB, self).get_queryset(request) return qs.exclude(mod_id="PSS") Thanks In Advance.