Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django filter has_key generates wrong SQL
I need to filter some objects that have no specific value in the field. I tried to do it like this: MyModel.objects\ .filter(<some filters>)\ .exclude(json_field__has_key='some_field', json_field__some_field=True) But this code generates wrong SQL query: ... AND NOT ( "my_model"."json_field" ? some_field AND ("my_model"."json_field" -> 'some_field') = 'true' AND "my_model"."json_field" IS NOT NULL) ) ... On the first line some_field used without qoutes. I fixed it by adding single qoutes to the string like this: json_field__has_key="'some_field'" but I dont think it's a good solution. Does anyone have an idea why it works this way and how I should fix it? -
how to get local ip not public ip in django?
so i have this website to manage the local network of my business i have 2 project inside it one is the callback server one is the main app that manage the local network. so i want to restrict to only people that can access the technician router can access the main app. i already make the view to get the client ip address but it return public ip but what i want is my local ip that is in range "192.178.1.x ~ 192.178.50", can anyone help me?, if anyone have suggestion how can i used different method for this cases please just share it out. thanks :) here's code views.py def ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') print(ip) return HttpResponse(ip) -
How to create folders in django admin?
Currently, I want to create a folder whenever I try to add a new tag in Django admin. But I don't know how to realize this function. my model.py code is as below: class Tags(models.Model): Tag_name = models.CharField('Tag Name', max_length=10, default='NA') Description = models.TextField('Tag Description', max_length=100, blank=True) class Meta: verbose_name = 'Tags' verbose_name_plural = verbose_name def __str__(self): return self.Tag_name The function I want is, for example, if I create a tag named "test", the system will automatically create a folder named "test" in a specific place. -
Django drf-yasg ViewSet Error: AttributeError: 'list' object has no attribute 'items'
I am using ReadOnlyModelViewSet for my API and I keep on getting an error: My ViewSet: class CartItemViewSet(viewsets.ReadOnlyModelViewSet): """ ViewSet for Cart functions """ queryset = CartItem.objects.all() serializer_class = CartItemSerializer permission_classes = [IsAuthenticated] Serializer: class CartItemSerializer(serializers.ModelSerializer): # product = UserSerializer(read_only=True) model = CartItem fields = ['uuid', 'product', 'quantity', 'cart_item_price'] Error Message: File "/usr/local/lib/python3.8/site-packages/drf_yasg/inspectors/field.py", line 102, in make_schema_definition for property_name, child in serializer.fields.items(): AttributeError: 'list' object has no attribute 'items' -
Django state sharing between server processes
I am building a Django project that one the of the apps has a state that I want to keep (a complex rate limiter as a Python Object that is hard to implement through something like Redis). By making the server to spawn new processes like WSGIDaemonProcess localhost processes=2 threads=25 Will it cause to lose sync of the state between processes ? In standard python one will spin a Manager that proxies the state in multiple processes. -
Login with Token
The goal is to be able to authenticate users to our website just with a string of memorizable token. I'm thinking of using django-token, or django-rest-framework to create an authentication token, create a memorizable string related to each token, and use that string to login user. I'm not very sure if it is going to work. Please, suggest me the best approach to achieve this or any other alternative methods. -
How to perform detection of breast cancer on Wisconsin dataset using a web app in Django, especially implmenting the backend side?
This is my front end of the web app. -
Unable to Understand the below statements of models in Django
I am naive in Django, I have done a sample E-commerce application that is present online. I am unable to understand the highlighted statements, I searched online but unable to understand the statements. Can someone please explain me like below productitems = self.name_set.all() From where this name_set.all() came ????????? orderItems = self.orderitem_set.all() likewise from where orderitem_set.all() ????????? from django.db import models from django.contrib.auth.models import User # Create your models here. class Customer(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE, null=True,blank=True) name = models.CharField(max_length=200,null=True) email = models.CharField(max_length=200,null=True) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.DecimalField(max_digits=7,decimal_places=2) digital = models.BooleanField(default=False,null=True,blank=False) image = models.ImageField(null=True,blank=True) #image def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url @property def get_product_total(self): **productitems = **self.name_set.all()**** total = sum([item.get_total for item in productitems]) return total print('total:',total) class Order(models.Model): customer = models.ForeignKey(Customer,on_delete=models.SET_NULL,blank=True,null=True) date_ordered=models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False,null=True,blank=False) transaction_id = models.CharField(max_length=200, null=True) def __str__(self): return str(self.id) @property def shipping(self): shipping = False orderItems = **self.orderitem_set.all()** for i in orderItems: if i.product.digital == False: shipping = True return shipping @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item … -
Django crate custom reusable app that include some changes on manage.py
I'm following this documentation to create a reausable Django application, but the main implementation is on manage.py e.g: #!/usr/bin/env python import os import sys from foo import bar #Need to append this import if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'educat_erp.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc is_testing = 'test' in sys.argv ## This lines if is_testing: ## needs to append bar() ## when add the aplication execute_from_command_line(sys.argv) Theres any way to create a reusable package that only need to be added on INSTALLED_APPS and modify the manage.py or any other way to check if tests are running to change some test configurations before run. -
Replicate Production Django Server + Postgres Database to Identical Linode server as a backup
I am trying to make an identical copy of a production server hosted on Linode. This is a Python/Django/Postgres implementation with tenant model. I am quite new to the implementation done by another developer who has since left. Current site is live with tenant1.prodlive.info tenant2.prodlive.info The steps I have carried out to take a backup within the linode dashboard and then created a new linode instance with that backup. After logging in, I am seeing all files have been copied correctly. However, I am missing steps on configuring some specifics due to which the server is showing 404 error when I try to access tenant1.backup.info tenant2.backup.info. The DNS is setup correctly to have A records for both. Server does respond to the main server url www.backup.info. The only file that I have changed is the \project_dir\django_project\middleware.py and changed the mention of the domain name and IP address prodlive.info and ip.prod.live.info to backup.info and ip.back.up.info. I may be missing some configuration items hence need help with some pointers and best practices to maintain an exact copy of the live production. Thanks in advance for all your suggestions and help. Here's the exact message I get when accessing the subdomain URL. Page … -
Way to implement CI test to check if function argument is valid?
Let's say I have a python function and dictionary as follows: d = {"a": 1, "b": 2, "c": 3} def foo(input): return d[input] Is there a way when I push my code to GitHub (presumably with some sort of continuous integration) to check that all calls of foo only use one of the keys of d as the input argument, and if there is a call with an invalid argument, to flag it or raise an alert? For example: foo("a") # no flag foo("d") # flag/alert I know how I would raise an exception or ValueError at runtime, but I'm looking for a CI solution to include in our GitHub workflow. Right now we are using Travis-CI for our custom tests and the standard CodeQL tests provided by LGTM. I looked into using custom CodeQL via LGTM, but I couldn't quite figure it out. I'd be fine implementing it in either of those continuous integrations or implementing a third. -
Django inlineformset not validating forms correctly
I am using inlinemodelformset to create bunch of financing forms, simple enough. But, when I submit the forms without inputting any value for all the fields, the form clean method does not raise ValidationError. Even the browser does not require the fields to be populated when they are set to required = True in the forms.py # In models.py class Financing(models.Model): loan_name = models.CharField(max_length = 30, null = False, blank = False) loan_type = models.CharField(max_length = 25, choices = ( ('interest_only', 'Interest-only), ('mortgage', 'Conventional Mortgage') ), blank = False, null = False) loan_amount = models.PositiveIntegerField(null = True, blank = True) loan_ratio = models.DecimalField(max_digits = 4, decimal_places = 2, blank = False, null = False, default = 70) # This is how much of the total cost the loan is covering interest_reserve = models.PositiveIntegerField(null = True, blank = True) application_fee = models.PositiveIntegerField(null = False, blank = False) interest_rate = models.DecimalField(max_digits = 4, decimal_places = 2) term = models.PositiveIntegerField(null = False, blank = False) term_unit = models.CharField(max_length = 25, null = False, blank = False, choices = ( ('years', 'Years'), ('months', 'Months'), ), default = 'years' ) compounded = models.CharField(max_length = 20, choices = ( ('annually', 'Annually'), ('semi-annually', 'semi-annually'), ('quarterly', 'Quarterly'), ('monthly', … -
Django Admin: Dropdown selecting ContentTypes & Generic Relationships
I have a generic relationship in my model: class Foo(models.Model): content_type = ... object_id = ... content_object = ... admin.site.register(Foo, FooAdmin) I understand with GenericTabularInline I could insert this as an inline generic object into a different admin form. To clarify, this is not what I am looking for. My question is: Given a FooAdmin above, now can I have the detail admin view provide a dropdown selector for object_id/content_object instead of having it as a raw ID field (which is very inconvenient)? -
Manually adding property removes records in django query
I am writing a Django application where I have model like this: ModelA(models.Model): text = models.TextField() ModelB(models.Model): a = models.ForeignKey(ModelA, on_delete=models.CASCADE) text = models.TextField() When querying I am adding, ModelB records as a property on ModelA records to use for rendering in template. a_records = ModelA.objects.filter() for a_record in a_records: b_records = ModelB.objects.filter(a=a_record) a_record.b_records = b_records But doing this is removing a lot of records from a_records so I don't see all of the ModelA records when I render it in a {% for a in a_records %} {{ a.text }} {% endfor %} in template. Any idea why this is happening? -
Django Rest Framework djoser activation problem
I know there is lots of questions like this problem but i really need your help.I am trying to activate account with email verification but i cannot activate the account the link that i am sending,is not activating the account. urlpatterns = [ path('admin/', admin.site.urls), path('auth/', include('authapp.urls'))] This is my main url.Inside authapp i wrote these urls. urlpatterns = [ path('', include('djoser.urls')), path('', include('djoser.urls.authtoken')), path('activation/<str:uid>/<str:token>/', UserActivationView.as_view()),] My settings are like this: DJOSER = { 'LOGIN_FIELD':'email', 'USER_CREATE_PASSWORD_RETYPE':True, 'SERIALIZERS':{ 'user_create':'authapp.serializer.UserCreateSerializer', 'user': 'authapp.serializer.UserCreateSerializer', }, "ACTIVATION_URL": 'auth/request_activate/{uid}/{token}', "SEND_ACTIVATION_EMAIL": True, } And this is my view.py: from rest_framework.response import Response from rest_framework.views import APIView import requests class UserActivationView(APIView): def get (self, request, uid, token): protocol = 'https://' if request.is_secure() else 'http://' web_url = protocol + request.get_host() post_url = web_url + "/auth/users/activation/" post_data = {'uid': uid, 'token': token} result = requests.post(post_url, data = post_data) content = result.text() return Response(content) I tried almost every solution but it didn't work.I hope you can help me guys.Thanks. -
can't deal with this association - django app
hope you are doing well ! I don't know what to do in this case, this is the association I want to create an activity itself can have 0 till many activities , this is models.py the attribute are just an examples class Activity(models.Model): name = models.CharField() a_id = models.Foreignkey(a, on_delete=models.CASCADE) can anyone guide me ?, thank you in advance :) -
How do i use user_passes_test view specific page?
My User Model SELLER = "SELLER" CUSTOMER = "CUSTOMER" USER_TYPE_CHOICES = ( ('SELLER' , 'Seller'), ('CUSTOMER' , 'Customer'), ) class User(AbstractBaseUser,PermissionsMixin): email = models.EmailField( max_length=255, unique=True) user_type = models.CharField(max_length=200,choices=USER_TYPE_CHOICES,null=True) last_login = models.DateTimeField( blank=True, null=True) is_staff = models.BooleanField( default=False) is_superuser = models.BooleanField( default=False) is_active = models.BooleanField( default=True) date_joined = models.DateTimeField(default=timezone.now) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: ordering = ['email'] def clean(self): super().clean() self.email = self.__class__.objects.normalize_email(self.email) def get_full_name(self): return self.email def get_short_name(self): return self.email I have two user_types one seller and one customer how i can use user_passes_test decorator to see if the user.user_type is seller so he can see the seller view only seller can see the seller view def seller_home(request,pk): try: seller = Seller.objects.get(id=pk) except User.DoesNotExist: raise Http404("Seller Does Not Exisit") sellerproducts = Product.objects.filter(seller=seller) totalsellerproducts = sellerproducts.count() context = {'seller':seller,'sellerproducts':sellerproducts,"totalsellerproducts":totalsellerproducts } return render(request,"seller_home.html",context) -
how to connect model instance in django
Code Description I have a model called Hospital who is the the user having OneToOne relationship with the user model. the Hospital Model is like a profile for the user. I have another model called patient which has a Foreginkey relation with the User like a One to many relationship. This means the user model can have many patient. I have another model called Card which has a OnoToOne relationship with the Patient and a foreignKey relationship with the Usermodel. this means a patient can have one card and that particular card can only belong to one patient and also the card belongs to the hospital not just the patient thats why i added a foreign key to relationship to the user model. I have another Model called Diagnoses which also have a ForiegnKey relation with the PatientModel and a foreignkey relationship with the User model because the diagnoses is not just for the patient but also the hospital. This means a patient has a card, and can have many diagnoses. Using this method, successfully, a user can have many patient. Now my problem is, when a user want to create a new card or diagnoses for a specific patient, … -
Updating scikit-learn: 'SVC' object has no attribute '_probA'?
We updated to Python 3.8.2 and are getting an error with scikit-learn: Traceback (most recent call last): File "manage.py", line 16, in <module> execute_from_command_line(sys.argv) File "/home/ubuntu/myWebApp/.venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/ubuntu/myWebApp/.venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ubuntu/myWebApp/.venv/lib/python3.8/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/home/ubuntu/myWebApp/.venv/lib/python3.8/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/home/ubuntu/myWebApp/server_modules/rss_ml_score/management/commands/rssmlscore.py", line 22, in handle run.build_and_predict(days=options['days'], rescore=options['rescore']) File "/home/ubuntu/myWebApp/server_modules/rss_ml_score/utils/run.py", line 96, in build_and_predict predict_all(filename) File "/home/ubuntu/myWebApp/server_modules/rss_ml_score/models/predict_model.py", line 135, in predict_all voting_predicted_hard, voting_predicted_soft = predict_from_multiple_estimator(fitted_estimators, X_predict_list, File "/home/ubuntu/myWebApp/server_modules/rss_ml_score/models/train_model.py", line 66, in predict_from_multiple_estimator pred_prob1 = np.asarray([clf.predict_proba(X) File "/home/ubuntu/myWebApp/server_modules/rss_ml_score/models/train_model.py", line 66, in <listcomp> pred_prob1 = np.asarray([clf.predict_proba(X) File "/home/ubuntu/myWebApp/.venv/lib/python3.8/site-packages/sklearn/svm/_base.py", line 662, in _predict_proba if self.probA_.size == 0 or self.probB_.size == 0: File "/home/ubuntu/myWebApp/.venv/lib/python3.8/site-packages/sklearn/svm/_base.py", line 759, in probA_ return self._probA AttributeError: 'SVC' object has no attribute '_probA' Do I need to use another library in addition to sci-kit learn to access _probA? -
Django Channels middleware use ORM
I have troubles checking the user token inside of middleware. I'm getting token from cookies and then I need to query database to check if this token exists and belongs to user that made a request. routing.py from channels.routing import ProtocolTypeRouter, URLRouter import game.routing from authentication.utils import TokenAuthMiddlewareStack application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': TokenAuthMiddlewareStack( URLRouter( game.routing.websocket_urlpatterns ) ), }) middleware.py from rest_framework.authentication import TokenAuthentication from rest_framework.exceptions import AuthenticationFailed from rest_auth.models import TokenModel from channels.auth import AuthMiddlewareStack from django.contrib.auth.models import AnonymousUser from django.db import close_old_connections ... class TokenAuthMiddleware: """ Token authorization middleware for Django Channels 2 """ def __init__(self, inner): self.inner = inner def __call__(self, scope): close_old_connections() headers = dict(scope['headers']) if b'Authorization' in headers[b'cookie']: try: cookie_str = headers[b'cookie'].decode('utf-8') try: # no cookie Authorization=Token in the request token_str = [x for x in cookie_str.split(';') if re.search(' Authorization=Token', x)][0].strip() except IndexError: scope['user'] = AnonymousUser() return self.inner(scope) token_name, token_key = token_str.replace('Authorization=', '').split() if token_name == 'Token': token = TokenModel.objects.get(key=token_key) scope['user'] = token.user except TokenModel.DoesNotExist: scope['user'] = AnonymousUser() return self.inner(scope) TokenAuthMiddlewareStack = lambda inner: TokenAuthMiddleware(AuthMiddlewareStack(inner)) And this gives me django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. I also tried the following … -
How to get total amount per year-month for certain category in DetailView, Django?
I have a table with expenses categories and when I click on the certain category it redirects me to this DetailView page. Then I want to show the year-month costs summary for chosen category to look similiar to this what I already got (summary per year-month but not for certain category). How can I achieve that? This is what I got for now and got stucked: def category_summary(): summary_by_year_month = Expense.objects.annotate( month=TruncMonth('date')).values('date').annotate( amount=Sum('amount')).order_by() return summary_by_year_month MODELS.PY class Category(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return f'{self.name}' class Expense(models.Model): class Meta: ordering = ('date', '-pk') category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=50) amount = models.DecimalField(max_digits=8, decimal_places=2) date = models.DateField(default=datetime.date.today, db_index=True) def __str__(self): return f'{self.date} {self.name} {self.amount}' The most confusing part about this problem for me is how can I retrieve this information only for chosen category and show it to user in DetailView? Thank you in advance for any help. -
Pass request.user to dispatch method
Env: Python 3.6, Django 3.0, DRF 3.11, JWT Authorization Hello everybody. I have a simple class in my API where I want to check user permissions in each method get, pass etc. I planned to check user privileges at dispatch but it doesn't work. Simplify code, my current class looks more or less like this: class ExampleClassName(APIView): can_do_sth = False def dispatch(self, request, *args, **kwargs): print(request.user) # Here is AnonymousUser if request.user.username == "GreatGatsby": self.can_do_sth = True return super(ExampleClassName, self).dispatch(request, *args, **kwargs) def get(self, request): print(request.user) # Here is correctly Logged user if self.can_do_sth: return Response("You can do it") return Response("You can't") def post(self, request): print(request.user) # Here is correctly Logged user if self.can_do_sth: return Response("You can do it") return Response("You can't") How can I pass request.user to dispatch method? -
413 Request Entity Too Large - Regular Fix Not Working
I'm deploying a Django application online using AWS Elastic Beanstalk. It worked fine for a while, but some change is causing the application to throw a '413 Request Entity Too Large nginx/1.18.0' error when I try to upload a file. Here are my logs: stdout log: ---------------------------------------- /var/log/web.stdout.log ---------------------------------------- Sep 8 19:59:39 ip-172-31-16-39 web: Bad Request: / Sep 8 21:27:14 ip-172-31-16-39 web: Not Found: /static/tinymce/css/prism.css Sep 8 21:27:14 ip-172-31-16-39 web: Not Found: /static/tinymce/js/prism.js Sep 8 21:27:14 ip-172-31-16-39 web: Not Found: /favicon.ico Sep 8 21:27:16 ip-172-31-16-39 web: Not Found: /static/tinymce/css/prism.css Sep 8 21:27:16 ip-172-31-16-39 web: Not Found: /static/tinymce/js/prism.js access log: ---------------------------------------- /var/log/nginx/access.log ---------------------------------------- 192.241.237.101 - - [07/Sep/2020:09:35:44 +0000] "GET /hudson HTTP/1.1" 400 59666 "-" "Mozilla/5.0 zgrab/0.x" "-" 3.134.93.214 - - [07/Sep/2020:10:07:18 +0000] "HEAD /robots.txt HTTP/1.0" 404 0 "-" "-" "-" 189.39.247.131 - - [07/Sep/2020:11:25:33 +0000] "GET / HTTP/1.1" 400 59689 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/601.7.7 (KHTML, like Gecko) Version/9.1.2 Safari/601.7.7" "-" 195.54.160.21 - - [07/Sep/2020:12:20:29 +0000] "GET /solr/admin/info/system?wt=json HTTP/1.1" 400 60308 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36" "-" 195.54.160.21 - - [07/Sep/2020:12:21:47 +0000] "GET /?XDEBUG_SESSION_START=phpstorm HTTP/1.1" 400 60242 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 … -
How do I return custom response/status code in Django?
I want to return status code different from 100 <= self.status_code <= 599, as written in Django's HttpResponseBase class. Is there are any easy way to bypass this restriction? -
Django: Use JSON and requests in my django app
I am using JSON, re and requests to get the number of followers from an instagram page: import json import re import requests PROFILE = 'espn' response = requests.get('https://www.instagram.com/' + PROFILE) json_match = re.search(r'window\._sharedData = (.*);</script>', response.text) profile_json = json.loads(json_match.group(1))['entry_data']['ProfilePage'][0]['graphql']['user'] print(profile_json['edge_followed_by']['count']) I am wondering how I can then add this to my django project to use that number to display on my website, updating each time someone vists the page to reflect the dynamic number. I had a look around but I dont really understand where you would add this code. I would image it would be added in the views section to then be rendered in the html page but not sure what the format would be. The view for the page I would like it to be used for example is View.py: def index(request): post = Post.objects.all()[0] recent_posts = Post.objects.all()[1:4] latest_posts = Post.objects.all()[:5] data = {"post":post, "recent_posts":recent_posts, "latest_posts":latest_posts} return render(request, 'index.html', data) Also as an extra question - how would the process differ if I was using a Generic Class-Based view vs a function view. Thank you very much.