Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why decorator @property return id in Django
In my models.py I have @property decorator - but it returns me id of model. I wrote method in this decorator but it is does not work: @property def replace_name(self): if not self.name: if self.middle_name: return self.full_name if not self.middle_name: return self.address My html template: {{ object.person.replace_name }} What does it wrong here? -
Deploying a full-stack web application (Django and Angular)
I built a nice full-stack application using Django as back-end and Angular as front-end with login functionality. I feel like it would help me tremendously in landing a full-stack developer position if I was able to deploy it and show it during the interview. However, I am finding trouble finding the documentation on how I would do so. Any suggestion would be greatly appreciated. Thank you!!! -
Django not able to locate static files
i am frustrated now ..been trying this for 2 days now.. tried every thing Django is not importing static files My settings STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'my_blog'/'static', ] my imports href="{% static 'css/bootstrap.css' %}" rel="stylesheet" type="text/css" /> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet" type="text/css" /> <script src="{% static 'js/bootstrap.min.js' %}"></script> <link href="{% static 'base.css' %}" rel="stylesheet" type="text/css" /> -
Django: error_messages not overriding default error messages
I am a beginner in Django, so sorry if this is a dumb question. I am trying to override the default error messages with custom messages, that I define in error_messages={...}. But the error messages are not overriding Here is my form.py using ModelForm. My model is a custom User model. class SignupForm(ModelForm): password = CharField( min_length=6, required=True, label='Password', help_text='Password should be minimum 6 characters long, including alpha numeric value', widget=PasswordInput(attrs={ 'class': 'input--password', 'type': 'password', 'aria-label': 'Enter a password', 'placeholder': 'Enter password', 'title': 'Enter password' }), error_messages={ 'required': _('Password is required'), 'min_length': _('Password is too short') } ) class Meta: model = User fields = ('username', 'email_address', 'password') labels = { 'username': _('Username'), 'email_address': _('Email Address'), 'password': _('Password') }, error_messages = { 'username': { 'unique': _('username has already been taken'), 'required': _('username is required'), 'max_length': _('username is too long') }, 'email_address': { 'unique': _('Email address has already been taken'), 'required': _('Email address is required'), 'invalid': _('Please enter a valid email address') }, }, widgets = { 'username': TextInput(attrs={ 'class': 'input--username', 'placeholder': 'Enter username', 'aria-label': 'Enter a username', 'title': 'Enter username', 'type': 'text' }), 'email_address': TextInput(attrs={ 'class': 'input--email', 'placeholder': 'Enter email', 'aria-label': 'Enter a email', 'title': 'Enter email', 'type': 'email' }) … -
Why is my_task.delay() working from shell but not apache/wsgi
Celery worker and beat are working fine. Site loads fine except when I call a url that passes a task to Celery. This is my WSGI file. import os import sys import dotenv from django.core.wsgi import get_wsgi_application dotenv.load_dotenv() def addpath(path): if path not in sys.path: sys.path.insert(0, path) addpath('/opt/ada') os.environ['DJANGO_SETTINGS_MODULE'] = 'ada.settings' os.environ['PYTHONPATH'] = '/opt/ada' os.environ['CELERY_LOADER'] = "django" I don't understand this error. mod_wsgi (pid=2547): Exception occurred processing WSGI script '/opt/ada/ada/wsgi.py'. Traceback (most recent call last): File "/opt/ada/venv/lib/python3.8/site-packages/kombu/utils/objects.py", line 42, in __get__ return obj.__dict__[self.__name__] KeyError: 'tasks' Also, I can try and call the same task from the shell and it works. The problem only manifests when calling a url that and so must be related to my apache2 site conf file, wsgi.py, or something related What am I missing? -
Django List ID to Form
I apologies if this question has been asked, but I couldnt find anything that could help me solve a small issue. Ive managed to create a django frame work, and created a model and a form containing data from a csv file. Basically what im trying to do is: Ive created a "Home Page", that looks like this(Its just basic to get the idea running): Which contains a list of IDS(With username) from the model/form. what I want to be able to do, is that when i click on one of the id's, for it to open my form page,which relates then to only the data of that ID... I hope that makes sense. So lets say i create a form.html file, and id like it to show all the info in the form/model pertaining to that ID i click on. Maybe it has something to do with Href link? I apologies if im not too clear, but please feel free to ask me anything and il do my best to help These are my files: Model.py: class datas(models.Model): country = models.CharField(_('country'),max_length=200,default='Null') qs_login = models.CharField(_('qs_login'),max_length=200,default='Null') Status = models.CharField(_('Status'),max_length=200,default='Null') seller_id = models.CharField(_('seller_id'),max_length=200,default='Null') Task_ID = models.CharField(_('Task_ID'),max_length=200,default='Null',primary_key=True) associate_queue = models.CharField(_('associate_queue'),max_length=200,default='Null') associate = models.CharField(_('associate'),max_length=200,default='Null') … -
Where can I put user input to Func, and avoid sql injection?
I want to calculate levenstein distance using a custom django function. https://docs.djangoproject.com/en/3.2/ref/models/expressions/#django.db.models.Func lev_dist=Func(F('name'), function='levenshtein', template=f"%(function)s(%(expressions)s, '{symptom.name}')") The problem is that when there is a quote in symptom.name I get an error. The documentation says that you should not put user input into template= because it causes sql injections. If so, where should I put the user input? -
Daphne does not find *server* on production server
I am trying to use django-eventstream to implement SSE events. My code runs perfectly using manage.py runserver on the local PC. However, when I run daphne config.asgi:application on the production server I get the error File "./config/asgi.py", line 21, in <module> url(r'', get_asgi_application()), File "/home/bidforga/virtualenv/bfg/bfg_wag/3.7/lib/python3.7/site-packages/django/core/asgi.py", line 12, in get_asgi_application django.setup(set_prefix=False) File "/home/bidforga/virtualenv/bfg/bfg_wag/3.7/lib/python3.7/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/bidforga/virtualenv/bfg/bfg_wag/3.7/lib/python3.7/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/home/bidforga/virtualenv/bfg/bfg_wag/3.7/lib/python3.7/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/home/bidforga/virtualenv/bfg/bfg_wag/3.7/lib/python3.7/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/home/bidforga/virtualenv/bfg/bfg_wag/3.7/lib64/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'server' This is my config/asgi.py import os import django from django.core.asgi import get_asgi_application from django.conf.urls import url from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack import django_eventstream os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings") application = ProtocolTypeRouter({ 'http': URLRouter([ url(r'^events/', AuthMiddlewareStack( URLRouter(django_eventstream.routing.urlpatterns) ), { 'channels': ['test'] }), url(r'', get_asgi_application()), ]), }) I assume it's looking for server.settings but … -
Problem downloading files in django template
I'm trying to download a file from a local directory in a Django template, but when I click and download it, I get a File Not Found error on my browser. As soon as I click download, the file explorer to choose the folder opens, but when I save the file I get that error. The path to the file I'm sure is right. index.html <a href="path_to_file" download target="_blank">Download</a> -
Request takes too long to Django app deployed in AWS Lambda via Zappa
I have recently deployed a Django backend application to AWS Lambda using Zappa. After the lambda function has not been invoked for some time, the first request to be made takes from 10 to 15 seconds to be processed. At first I thought it would be because of the cold start but even for a cold start this time is unacceptable. Then, reading through Zappa's documentation I saw that it enables by default the keep_warm feature that sends a dummy request to the lambda function every 4 minutes to keep it warm; so this excessive delay in the response to the first request to the lambda is not due to a cold start. Then, I started using tools such as AWS X-Ray and Cloudwatch Insights to try to find the explanation for the delay. Here is what I found out: The invokation that takes a very long time to be processed is the following: Crossed out in red are the names of the environment variables the application uses. They are all defined and assigned a value directly in the AWS Console. What I don't understand is, first of all, why it takes so long, and secondly, why it says the … -
how to name the folder where model images are uploaded
I have model Hotel where is image and name data. class Example(models.Model): image = models.ImageField(upload_to='images', default="images/default.jpg") name = models.CharField(max_length=50) I need to divide the uploaded images into folders that will be named name data in hotel model, as in the case of dating picture = models.ImageField(upload_to='images/%Y/%m/%d/', default="images/default.jpg", blank=True) this picture data is making folder where images are going to be saved. -
what authentication do I choose in discord bot with django rest framework
I have discord quiz bot that is sending questions and collecting data about user and his completed, created, questions. What authentication should I choose? I want only my bot to have access to the api (get, post, put), Token authentication require to have an User model (or no? Im not sure tbh) and I kinda dont want to add it. class UserProfile(models.Model): name = models.CharField(max_length=100) score = models.IntegerField() discord_id = models.IntegerField() attempts = models.IntegerField(default=0) successful_attempts = models.IntegerField(default=0) def __str__(self): return self.name class Meta: ordering = ('-score', ) -
Django-Bootstrap5 form validation error not displaying
I have a form in a modal that needs to be validate. Since Django doesn't do too well with forms in modals and I not rendering the view after the POST but instead using ajax/js to determine the behaviour. I cannot get the invalid-feedback div to show even though I have followed the documentation which states: For invalid fields, ensure that the invalid feedback/error message is associated with the relevant form field using aria-describedby (noting that this attribute allows more than one id to be referenced, in case the field already points to additional form text). Additionally, I can view on the console that the "aria-describedby" attribute is set correctly in the input. index.html <div class="modal-body"> <form class="needs-validation" id="address_form" method="post" novalidate> {% csrf_token %} <div class="mb-3 row"> <label for="id_applicantStreet1" class="col-sm-4 col-form-label">Address Line 1</label> <div class="col-sm-8"> {{form.applicantStreet1}} </div> <div class="invalid-feedback" id="invalid-street1">This is required</div> </div> ..... some more other form fields below index.js $("#address_submit").click(function(){ $.ajax({ type: 'POST', data: $("#address_form").serialize(), url: '/ajax/validate_address_modal', success: function(data){ if(data.status == 200){ window.location.reload(true); } else { responseObj = data.form; for (const key in responseObj){ var id_selector = "#id_"+ key; var message = ""; for (let i = 0; i < responseObj[key].length; i++){ message = responseObj[key][i] + "<br>" + … -
cannot unpack non-iterable ModelBase object in django
i want to view a single in item list with the help of its id but unable to achieve that i am using cbv it is showing me above mention error i am creating a ecommerce website where i want to load only that item detail which he clicking from all the items but unable to achieve showing me above error my models.py class Item(models.Model): categories = models.ForeignKey(Categories, on_delete=models.CASCADE, related_name='our_items') subcategories = models.ForeignKey(Subcategories, on_delete=models.CASCADE, related_name='products') can_buy = models.ForeignKey(For, on_delete=models.CASCADE, related_name='for_wearing') name = models.CharField(max_length=200, blank=False) contain_size = models.CharField(max_length=50, blank=True) brand_name = models.CharField(max_length=100, blank=False, default='Bagh') first = models.ImageField(upload_to='items', blank=False) second = models.ImageField(upload_to='items', blank=False) third = models.ImageField(upload_to='items', blank=True) fourth = models.ImageField(upload_to='items', blank=True) fifth = models.ImageField(upload_to='items', blank=True) item_vedio = models.FileField(upload_to='item_vedio', blank=True) offered_price = models.FloatField(blank=False,) actual_price = models.FloatField(blank=False) about = models.TextField(blank=False, default="about" ) offer = models.CharField(max_length=4, blank=True) def __str__(self): return self.name here is my views.py class Product_detail(View): def get(self, request, products_id): item = Item.objects.get(Item, pk=products_id) category_list = Categories.objects.all() print(item) return render (request, 'products.html',{"item_list" : item, 'category_list': category_list }) my urls.py path('<int:products_id>/details',Product_detail.as_view(),name='detail') my href tag <a href="{% url 'products:detail' products.id %}"> any suggestion will be appreciated thank you for your time -
Django. Create a popup window
In django admin we have popup windows. They do their work when we hit little green plus on some admin pages. For example when we want to create another sample of our model. My question is the following: can I utilize somehow this mechanics in order to create my own popup window when some link or button is hit? Right now a new tab opens. I would like to have a popup window. I saw a boolean option which i can render in the context, which is called is_popup. Maybe i should use it? Unfortunately when i just set it to True right now, it does not toggle a popup window. Just another tab. -
Django : Temporary table or views to create flattened JSON
Can we create a temporary table or views to store the data from 3 or 4 different tables and send a flattened JSON instead of nested JSON to the frontend in Django? My model is: class Place(models.Model): id = models.IntegerField(primary_key=True) location = models.CharField(max_length=100) class Meta: db_table = 'place' managed=False class Session(models.Model): id = models.IntegerField(primary_key=True) place = models.ForeignKey(Place,related_name='session',on_delete=models.CASCADE, null=True) start = models.DateField(auto_now=True) counts = models.IntegerField() class Meta: db_table = 'session' managed=False class Animal(models.Model): id = models.IntegerField(primary_key=True) sess = models.ForeignKey(Session,related_name='details',on_delete=models.CASCADE, null=True) type = models.CharField(max_length=100) is_active = models.BooleanField() length = models.DecimalField(max_digits=6, decimal_places=2) class Meta: db_table = 'animal' managed=False The flatten output I am trying is: [ { "location": "Loc 1", "session_start": "2021-01-01", "session_count": 900, "session_details_id": 1, "session_details_length_max": "22.00", "session_details_length_min": "10.00", "session_details_length_avg": "16.43", "session_details_length_std": "16.00", "session_details_is_active": false, "session_details_type": "dog" }, "location": "Loc 1", "session_start": "2021-01-02", "session_count": 400, "session_details_id": 2, "session_details_length_max": "19.00", "session_details_length_min": "12.00", "session_details_length_avg": "15.43", "session_details_length_std": "13.00", "session_details_is_active": false, "session_details_type": "dog" } ] Instead of nested JSON data that I am currently getting The nested JSON data is [ { "location": "Loc 1", "session": [ { "start": "2021-01-01", "count": 600, "details": [ { "id": 1, "length_max": "15.00", "length_min": "10.00", "length_avg": "12.00", "length_std": "13.00", "is_active": false, "type": "dog" } ] }, { "start": "2021-01-02", "count": … -
Django queryset count total of same foreign key
I'm trying to count and order the total number of the same foreign key for a model. I have two models linked by a foreign key: class CustomerAnalytic(models.Model): product = models.ForeignKey("products.Product", on_delete=models.DO_NOTHING) And I want to know how to get the total number of each foreign key link to this model. For instance: {"product": 1, "customer_analytic_total": 10, "product": 2, "customer_analytic_total": 15,} For now I get the values in a dict and manually do the calculations. I want to optimize this part of the code. I tried to play with aggregate and annotate functions with no success. Is there a way to do it with Django ORM functions? -
how send notification to user when admin model save function in django admin site
i am preparing an e commerce site where i want to send notification on orders like ( processing , dispatched, on the way etc. ) these items are filled by the admin in their site. now my query is to send notification to the user when the admin fills the field and saves it. class orders(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) pid=models.ForeignKey(products,on_delete=models.CASCADE) amount=models.FloatField() isaddfilled=models.BooleanField(default=False) ispaymentdone=models.BooleanField(default=False) delivered=models.BooleanField(default=False) status=models.CharField(max_length=255,blank=True) when the admin fills the status and saves it. the status should be sent as the push notification to the user. -
How to search a Django database using a field saved in the model?
I am trying to create a search bar that searches for users in my Journal app. I want to redirect the search to the appropriate page if the user exists. I have created the view function, template and URL for the feature. As a test, I imported the User class from django.contrib.auth.models and I was able to display a personalised message if the user existed. def search_user(request): """Search for users.""" if request.method == "POST": searched = request.POST["searched"] usernames = User.objects.filter(username__icontains=searched) context = {"searched": searched, "usernames": usernames} return render(request, "journals/search_user.html", context) In the main model, the Journal class has a ForeignKey relation with User and it is saved to a field called "owner". I would like to somehow check if the searched username matches with this "owner" field. When I try to make a search this way, it cannot find any data. The reason I want the search to refer to "owner" is so that I can access the other fields in the table. Could someone point out the mistake I am doing here? from django.db import models from django.contrib.auth.models import User class Journal(models.Model): """A particular subject the user may want to write about.""" name = models.CharField(max_length=100) date_added = models.DateTimeField(auto_now_add=True) owner … -
How to write a variable of a model by index
Assuming a model class MyModel(models.Model): id_pk = models.AutoField(primary_key=True) prop_a = models.CharField(max_length=200, blank=True, null=True) prop_b = models.CharField(max_length=200, blank=True, null=True) prop_c = models.CharField(max_length=200, blank=True, null=True) I want to access the variables (=columns) per index (integer) like: my_model = MyModel() my_model[2] = 'my text' I know one can do this "statically" by using the variable name: g = MyModel.objects.get(id_pk=id) g.prop_b = 'my text' g.save() But I want to do it "dynamically". Using _meta seems also not be possible: MyModel._meta.fields[2] = 'my text' reports AttributeError: The return type of 'fields' should never be mutated. and g = MyModel.objects.filter(id_pk=id) list(g.values()[0])[2] = 'my text' just changes at in a copy. -
Where to load Tensorflow model in Django application
I am working on a Django project that should load a saved Tensorflow model from a file. Where should I run this code to have a global model variable? Currently, I am just loading in the model in the views.py file outside of all functions and it is working, but I am unsure if this runs only once and if it is a clean solution. -
Python, Django Celery job interface upgrade to ubuntu 20.04 celery jobs not running
Very New to Celery/Django Over the weekend, we upgraded the ubuntu server to 20.04, and while the web interface is up and running and I can see the defined jobs when I attempt to run any job the job does not run. I am not seeing any errors in the logs (assuming I am looking at the correct apache logs). Everything is down and I am not sure where to debug celery. If I could find out where the jobs are located then I would try to run using the celery CLI. Any help/pointers is much apprecited. -
Django html button is not opening web browser with selenium
I want a button on my django project home page that when clicked runs a .py file and opens a new browser using selenium. Following is my code but it is not working - html - <form method="post"> {% csrf_token %} <button type="submit" name="run_script">Generate Challan</button> </form> views - # import function to run from .generate import Generate def Generate(request): if request.method == 'POST' and 'run_script' in request.POST: # call function GenerateChallan() Python script in generate.py - from selenium import webdriver import time from selenium.webdriver.common.action_chains import ActionChains class Generate(): def GenerateChallan(): driver = webdriver.Chrome() driver.get('https://onlineservices.tin.egov-nsdl.com/etaxnew/tdsnontds.jsp') driver.set_window_size(1920, 1012) driver.implicitly_wait(5) driver.execute_script('javascript:sendRequest(281)') There is no error but the browser is not opening. Please help -
Django looking for variable i can use in object.filter
I am using a for loop to get data from a database and a html page shows every db entry as a different card, with a button under it. If i click the button, it should show me a html page with more information. On that page i use <a href="receptinfo?{{recepten.name}}" class="btn btn-info knop">Meer Info</a> and this works. The url shows : localhost/receptinfo?Babi%20pangang In views.py try to setup a filter for objects.filter( ) which uses a variable. I tried: recepten = Recept_Info.objects.filter(name='{{recepten,name}}'), it doesn't show any errors, but also it shows no data. When i try: recepten = Recept_Info.objects.filter(name={{recepten,name}}), i get UnboundLocalError: local variable referenced before assignment error. If i write: recepten = Recept_Info.objects.filter(name='Babi pangang') it works. My question is how can i use the name i get from {{recepten.name}} as object.filter(......) recept.html <div class="container"> {% for recepten in recepten %} <div class='row'> <div class="data-aos="zoom-in" data-aos-delay="200"> <div class="card-deck"> <div class="card"> <div class="card-body"> <h4 class="card-title">{{recepten.name}}</h4> <ul> <li><p class="card-text">Menugang: {{recepten.menugang}}</p></li> <li><p class="card-text">Keuken: {{recepten.keuken}}</p></li> <li><p class="card-text">Bereidingstijd: {{recepten.bereidingstijd}} min.</p></li> <li><p class="card-text">Personen: {{recepten.aantal_personen}}</p></li> <li><p class="card-text">Vegetarisch : {{recepten.Vegetarisch |yesno:"Ja,Nee" }}</p></li> <ul> </div> <a href="receptinfo?{{recepten.name}}" class="btn btn-info knop">Meer Info</a> </div> </div> {% endfor %} </div> </div> <div class="end"> </div> Views.py def receptinfo(request): recepten = Recept_Info.objects.filter(name='{{recepten,name}}') return render(request, … -
What JSESSIONID cookie when connecting to Spotfire server?
I am embedding a Spotfire visualization into my Django webpage. I am using the following JS API: https://community.tibco.com/wiki/spotfire-tipstricks-embed-spotfire-visualizations-webpages The API works well except that it gives me a cookie error like the following: How can I solve this?