Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
taggit.managers.TaggableManager how to use it with Django FilterSet Class and filter with __in all (every) items
unlike default __in filter, which return any records which matches at least one item in the list, I want to return all records who matches all items in the list using Django FilterSet Class and Django-taggit TaggableManager field -
How do I make two choice fields that will be saved as one value in the database in django?
I have created a Task model: class Task(models.Model): name = models.CharField(max_length=200, null=True) author = models.ForeignKey(User, on_delete=models.DO_NOTHING, blank=True, null=True) company = models.ForeignKey(Company, on_delete=models.DO_NOTHING) eta = models.CharField(max_length=20, null=True, blank=True) I want the eta to be saved as a CharField that will be inputed by the user via two fields: one field for the measurement, for example: months, days, minutes etc. and one field for the amount, for example: 1, 4, 10 etc... at the end I would like to have the eta field be '1 hour', '30 minutes', '2 weeks' etc... I want the user to input the fields and then have the backend save them in to the right format. can anyone help with how to do this? or maybe if someone has an idea on how to do this in a better way. I want to make an application that will detect when the ETA already passed and alert the user of that. -
How to store UInt8Array in django model
As the title said, How to store UInt8Array in django model? Hope you can help me out, thanks a lot. -
filter by category the subcategories belonging to the same category of different products in the django admin area
I want when am adding the products in the django admin, when I enter the category of the product to list only the subcategories belonging only to the category. Here is my models class Category(models.Model): category_name = models.CharField(max_length=50) slug = models.SlugField(max_length=100, unique=True) category_image = models.ImageField(upload_to = 'photos/categories', blank = True) created_at = models.DateTimeField(auto_now_add=True) class Sub_Category(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) sub_category_name = models.CharField(max_length=50) slug = models.SlugField(max_length=100, unique=True) In my admin area I want the subcategory to be filtered from the category when adding different products.... Like showing say Furniture(category) to show chairs, beds (subcategories) class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) sub_category = models.ForeignKey(Sub_Category, on_delete=models.CASCADE) product_name = models.CharField(max_length = 200, unique=True) slug = models.SlugField(max_length=200, blank=True) description = models.TextField(max_length = 1000) price = models.IntegerField() discount_price = models.IntegerField(blank=True) on_offer = models.BooleanField(default=False) -
Simplejwt don't appear on importation options
I had installed djangorestframework-simplejwt with pip, so had i configure settings.py file for to use it, but, when i try to import the package, it doesn't has showing in importable package list. 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', ), The importations list: Can anyone help me? -
ECDSA algorithm in netsuite
How can i use ECDSA encryption algorithm with a private key to generate a digital signature in suitescript. Does netsuite support it and if not can i use it as an external library? Thanks in advance -
ModuleNotFoundError even if module (app name) is installed
I want to start a project but when trying to makemigrations, I got ModuleNotFoundError even if my apps is "installed" in settings I have 2 apps: authentication and blog In authentication, I have override User model with AbstractUser and that all Python 3.8.3 / Django 3.2.3 I've try to re-install librairies in my virtual env but doesn't works I have checked for typ errors but there are no errors whats is wrong? -
What type of database field for a multiple choice Search filter with DRF?
What type of Database field is the most efficent one for a drf based search filter? I'm trying to build a search feature where i can search by a specific set of features. You could compare it to an hotel search were you filter by Amenities that you want. Are many to many fields the best choice for this? -
How to render images in Django
I am using the latest version of Django and I am having problems rendering my images. My img tag doesn't work so I googled it and the problem seems to be the static files. So I followed some tutorials online but none of them worked for me. It will be awesome if you could provide me with some guidance, thanks. Path of my static folder Do I need to move my static folder else where, do I need to add some line of code? Path of my index.html Below is my html code... {% extends 'landing/base.html' %} {% load static %} {% block content %} <!DOCTYPE html> <html> <head> <style> html,body{overflow-y: scroll; } h3 { font-weight: lighter; } .btn-space { margin-right: 5px; margin-left: 5px; } h1{ font-size: 75px; font-weight: bold; background: -webkit-linear-gradient(#00ffd0, #c493ff); -webkit-background-clip: text; -webkit-text-fill-color: transparent; padding-top:13%; justify-content: center; font-family: 'Lato', sans-serif; } p{ background: -webkit-linear-gradient(#ffffff, #4287f5); -webkit-background-clip: text; -webkit-text-fill-color: transparent; padding:15px; display: flex; justify-content: center; font-family: 'Lato', sans-serif; } .c{ font-size: 15px; background: -webkit-linear-gradient(#ffffff, #3c3b3d); -webkit-background-clip: text; -webkit-text-fill-color: transparent; } body { background-color: black /*background-image: url('a/circle.svg'); background-size: cover;*/ } .d { font-size: 25px; background: -webkit-linear-gradient(#ffffff, #c493ff); -webkit-background-clip: text; -webkit-text-fill-color: transparent; } .e { padding-left: 20%; padding-right: 20%; text-align: … -
Django Crispy forms Validators
I have Django and I use crispy forms to enter data about a user. Problem is, some new users have 'diacritic' symbols in their name. Then I get the following error: Enter a valid “slug” consisting of letters, numbers, underscores or hyphens. For example: 'Coric' is ok, but 'Čorić' gets the error. I can manualy write it into the database, so I think that the problem is with crispy forms. How can I include 'š/č/ć/ž' simbols in the input form? -
Django Queryset filter
My django table contains a field that contains comma-separated strings. class RawData(TimeStampModelMixin): id = models.UUIDField(primary_key=True) media = models.TextField() media column will hold values like 'Multimedia, TV', 'Multimedia, TV Station'. I need to filter Rawdata table rows such that media column contains 'TV' or 'Multimedia'. __icontains doesn't provide the accurate result. If I do Rawdata.objects.filter(media__contains='TV') then it will return both 'Multimedia, TV', 'Multimedia, TV Station' rows. But I need only the 'Multimedia, TV' row. Is there any way to achieve this via queryset API? -
Celery has DNS resolution problems?
I used Celery for email registration asynchronously, but when I trigger this asynchronous request, the following error will appear Traceback (most recent call last): File "d:\python3\lib\site-packages\dns\resolver.py", line 982, in nameservers raise NotImplementedError NotImplementedError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "d:\python3\lib\site-packages\celery\app\trace.py", line 451, in trace_task R = retval = fun(*args, **kwargs) File "d:\python3\lib\site-packages\celery\app\trace.py", line 734, in __protected_call__ return self.run(*args, **kwargs) File "E:\Exploit_blog\blog_index_html\tasks.py", line 9, in send_email send_mail( File "d:\python3\lib\site-packages\django\core\mail\__init__.py", line 61, in send_mail return mail.send() File "d:\python3\lib\site-packages\django\core\mail\message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "d:\python3\lib\site-packages\django\core\mail\backends\smtp.py", line 102, in send_messages new_conn_created = self.open() File "d:\python3\lib\site-packages\django\core\mail\backends\smtp.py", line 62, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "d:\python3\lib\smtplib.py", line 1034, in __init__ SMTP.__init__(self, host, port, local_hostname, timeout, File "d:\python3\lib\smtplib.py", line 253, in __init__ (code, msg) = self.connect(host, port) File "d:\python3\lib\smtplib.py", line 339, in connect self.sock = self._get_socket(host, port, self.timeout) File "d:\python3\lib\smtplib.py", line 1040, in _get_socket new_socket = super()._get_socket(host, port, timeout) File "d:\python3\lib\smtplib.py", line 310, in _get_socket return socket.create_connection((host, port), timeout, File "d:\python3\lib\site-packages\eventlet\green\socket.py", line 44, in create_connection for res in getaddrinfo(host, port, 0, SOCK_STREAM): File "d:\python3\lib\site-packages\eventlet\support\greendns.py", line 543, in getaddrinfo qname, addrs = _getaddrinfo_lookup(host, family, flags) File "d:\python3\lib\site-packages\eventlet\support\greendns.py", line 505, in _getaddrinfo_lookup answer = resolve(host, qfamily, … -
Django get last value for each forgin key values
In models.py class loan(models.Model): completed=models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True,null=True) application_id=models.CharField(max_length=100,unique=True) class topay(models.Model): loanapplication=models.ForeignKey(loan,on_delete=models.CASCADE,null=True) paymentdate=models.DateField(null=True, blank=True) How to get last paymentdate for every loan application In views.py topay.objects.filter().values().annotate(last=Max('paymentdate')) -
Everytime I install django for my virtual environment I end up installing it globally. How to install django for virtual environment only?
I am a beginner and trying to learn Django, for that I am working in virtual environment. Whenever I try to install Django in my virtual environment it is installed globally, which is I think I should avoid. Here is the picture of my command prompt.enter image description here -
How to establish a One to One relation in django model in mongo db?
I am using mongo db with djongo in django. I have two models Employee and PresentEmployee. Employee: class Employee(models.Model): employee_id = models.CharField(primary_key=True, max_length=10, null=False, blank=False) employee_name = models.CharField(max_length=200, null=False, blank=False) email = models.EmailField(max_length=500, null=True, blank=True) def __str__(self): return self.employee_name PresentEmployee: class PresentEmployee(models.Model): employee_id = models.OneToOneField(Employee, on_delete=models.CASCADE) present_id = models.IntegerField(null=False, blank=False) id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) def __str__(self): return str(self.employee_id) when I try to add a new object to PresentEmployee, I am getting the error web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 808, in __iter__ web_1 | yield from iter(self._query) web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 167, in __iter__ web_1 | yield self._align_results(doc) web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 269, in _align_results web_1 | if selected.table == self.left_table: web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/sql_tokens.py", line 133, in table web_1 | return alias2token[name].table web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/sql_tokens.py", line 133, in table web_1 | return alias2token[name].table web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/sql_tokens.py", line 133, in table web_1 | return alias2token[name].table web_1 | [Previous line repeated 917 more times] web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/sql_tokens.py", line 130, in table web_1 | name = self.given_table web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/sql_tokens.py", line 141, in given_table web_1 | name = self._token.get_real_name() web_1 | File "/usr/local/lib/python3.10/site-packages/sqlparse/sql.py", line 361, in get_real_name web_1 | … -
How to include package.tar.gz to Python project and install it
I have a Django project and it uses folium package, in wich I needed to add some code. Now I have that modded package.tar.gz in my project directory. How to install it upon deploing to Heroku and use instead of original one? -
AttributeError: 'AsyncResult' object has no attribute 'head'
AttributeError: 'AsyncResult' object has no attribute 'head' In my views.py file the error throwing at data = df.head(50) when i'm running and retrive the data as asynchronous background task. Could anybody help me here? task.py @shared_task def eda_flow_task(path, mode): sleep(30) try: with adls_client.open(path, mode) as f: df = pd.read_csv(f, low_memory=False) return 'data load success' except Exception as e: response_dict.update({'error': str(e)}) view.py def eda_flow(request): path = '/data/satyajit/us_amz.csv' mode = 'rb' df = eda_flow_task.delay(path, mode) data = df.head(50) json_records = data.reset_index().to_json(orient ='records') data = [] data = json.loads(json_records) context = {'data': data} return render(request, "home/tables-simple.html", context) -
EnvError during Heroku push
I added my gmail password to my .env file located in the root directory of my django project. Why is heroku raising an Env error when I push, is there something else I haven't done? My settings.py file import: from pathlib import Path from environs import Env env = Env() env.read_env() my .env file: DEBUG=True SECRET_KEY = Secretkeyyy DATABASE_URL=sqlite:///db.sqlite3 EMAIL_HOST_PASSWORD = passworddd my refence to the .env email variable in my settings.py: EMAIL_HOST_PASSWORD = env.str("EMAIL_HOST_PASSWORD") the error during heroku push: (.venv) PS C:\Users\user\Desktop\DJANGO_PROJECTS\diary_app> git push heroku HEAD:main Enumerating objects: 345, done. Counting objects: 100% (345/345), done. Delta compression using up to 4 threads Compressing objects: 100% (337/337), done. Writing objects: 100% (345/345), 1007.91 KiB | 79.00 KiB/s, done. Total 345 (delta 48), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-22 stack remote: -----> Using buildpack: heroku/python remote: -----> Python app detected remote: -----> Using Python version specified in runtime.txt remote: -----> Installing python-3.10.7 remote: -----> Installing pip 22.2.2, setuptools 63.4.3 and wheel 0.37.1 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting asgiref==3.5.2 remote: Downloading asgiref-3.5.2-py3-none-any.whl (22 kB) remote: Collecting black==22.8.0 remote: Downloading black-22.8.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl … -
django url error this problem is happening only when user is logged in
"Environment of the project: Request Method: GET Request URL: Django Version: 3.0.5 Python Version: 3.10.7" "error is with the template and url" "eg: more details about question ....................................." "error at line 12" "Reverse for 'customer' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['customer/(?P<pk>[^/]+)/$']" 2 : 3 : <div class="homeWrapper"> 4 : <header> 5 : <nav> 6 : <ul class="nav__links"> 7 : <li><a href="{% url 'home' %}">Home</a></li> 8 : <li><a href="{% url 'gallery' %}">Gallery</a></li> 9 : <li><a href="#faqs" class="scroll">About us</a></li> 10 : <!--page is in demo mode after deployment logic will be made here--> ##error is with line 12 11 : {% if user.is_authenticated %} 12 : <li><a href=" {% url 'customer' pk=current.id %} ">Customer</a></li> 13 : {% else %} 14 : <li><a class="scroll" href="#login">Login</a></li> 15 : {% endif %} 16 : {% if request.user.is_staff %} 17 : <li><a href="{% url 'graph' %}">Dash Board</a></li> 18 : {%endif%} 19 : <script src="https://cdn.jsdelivr.net/npm/darkmode-js@1.5.7/lib/darkmode-js.min.js"></script> 20 : </ul> 21 : </nav> 22 : #log " Traceback (most recent call last): File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/website/views.py", … -
window.close() stopped working after updating to Django 4
I updated packages in my project to latest version, and while testing in Firefox I encountered that window.open() assigned to variable returns Object - debugged with the code below: let test = window.open($(e.currentTarget).attr('href'), '_blank', "height=640,width=480,toolbar=0,location=0,menubar=0"); console.log(test); And, when I close test (this object) using .close() (test.close()) it works just fine, but after upgrading packages (django 3 to 4 version) it stopped working, and test variable returns Window, not Object. I'm not really sure why it works that way, does Django 4 set some custom headers that cause the window close mechanism not work properly? How I should fix that? -
Django Models to calculate discount
I am doing an ecommerce project as my first django project and I am having some trouble on how to calculate my actual price and my discount price if there is a discount price so what I want to do is that if the admin adds a discount to a product I want to add a value to a field inside a model called discount price and in that model I want to calculate how much discount percentage the admin has put in and what the discounted price would be after applying the discount percentage ps: English is my second language and I'm sorry if you were not able to understand tldr : I want to calculate the price and the discount percentage and make the value it to another field in the model called discount price this is my models for the product and discounts(please point out how I should improve and any of my mistakes) from django_extensions.db.fields import AutoSlugField from django.core.validators import MinValueValidator, MaxValueValidator # Create your models here. class Products(models.Model): product_name = models.CharField(max_length=200, unique=True) slug = AutoSlugField(populate_from=['product_name'], unique=True) description = models.TextField(max_length=500, blank=True) price = models.IntegerField(validators = [MinValueValidator(0)]) discount_price = models.IntegerField(validators = [MinValueValidator(0)],null=True) image1 = models.ImageField(upload_to='photos/Products') image2 = … -
Forking Django Oscar's static files doesn't work
I'm trying to fork default oscar's static. My folder structure is the following: myproject/ static/ oscar/ templates/ flatpages/ oscar/ myproject/ And I set the following settings: STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'static/' ] Forking templates works just fine, but the same thing doesn't work with static, default files are still served in HTML. To fork static I used this command: ./manage.py oscar_fork_static Any idea why is it so? -
Saving a form created with html as pdf
I have a registration form created with HTML and when I click the save as PDF button, I want the contents of that form to be saved in a certain way. I tried frameworks like jsPDF, but I couldn't solve the UTF-8 problem in them. Can you help with this issue? -
Collapse navbar in html issue
I am making a navbar in django using html, css and bootstrap. I want it to collapse if the view is narrow enough, i have achieved this but it makes a strange thing when you press the menu button, it opens but very widely and strange like this: This is before i click the menu button This is when i click, but automatically it closes the menu and gets back t the 1st image This is my code right now: <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <link rel="shortcut icon" type="image/png" href="{% static 'favicon.ico' %}" /> <title>{%block title%}Base{%endblock%}</title> </head> <body> <style> #github { margin-left: -4; margin-right: 10; } #busqueda { margin: auto; } #logout { margin-left: 5; } </style> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a id="github" href="https://github.com/pabsanort2/hongOS" target="_blank" rel="noopener noreferrer"><img src="{% static 'github.png' %}" alt="enlace github"></a> <a class="navbar-brand" href="/home">HongOS</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar" aria-controls="navbar" aria-expanded="false"> <span class="navbar-toggler-icon"></span> </button> <div id="navbar" class="navbar-collapse collapse"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="/home">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="/clasificar">Clasificar <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="/info">Info <span class="sr-only">(current)</span></a> </li> <!-- <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> --> <!-- <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" … -
Data in 'context' is not passed to HTML
The context within the first conditional statement is delivered well, but the context updated within the second conditional statement is not delivered in HTML. For example, 'MODEL_LIST' in first context is delivered well, but 'mape_val' in second context is not. I want it to be delivered. How Can I solve this problem ? <views.py function CODE> def csv_forecast(request): context = {} username = request.user if request.method == 'POST' and request.FILES.get('csvfile'): uploaded_file = request.FILES.get('csvfile') p_data = pd.read_csv(uploaded_file) p_data.reset_index(drop=True, inplace=True) columns_list = list(p_data.columns) columns_list = [column.lower() for column in columns_list] p_data.columns = columns_list os.makedirs('media/csv', exist_ok=True) p_data.to_csv(f'media/csv/{username}.csv', index=False) start_date = p_data.loc[0, 'date'] len_date = int(len(p_data)*0.8) end_date = p_data.loc[len_date, 'date'] datas = [] for i in range(1, len(columns_list)): datas.append(columns_list[i]) MODEL_LIST = ['ARIMA', 'EMA5', 'LSTM'] context = {'datas' : datas, 'd' : p_data, 'columns_list' : columns_list, 'MODEL_LIST' : MODEL_LIST, 'start_date' : start_date, 'end_date' : end_date} if request.POST.get('sendModel') and request.POST.get('sendPdata') and request.POST.get('sendRdata'): send_pdata = request.POST.get('sendPdata') send_rdata = request.POST.get('sendRdata') send_model = request.POST.get('sendModel') cleaned_pdata = re.split(r'[\[\],"]', send_pdata) cleaned_rdata = re.split(r'[\[\],"]', send_rdata) cleaned_model = re.split(r'[\[\],"]', send_model) selected_pdata = [i for i in cleaned_pdata if len(i) >= 1] selected_rdata = [i for i in cleaned_rdata if len(i) >= 1] selected_model = [i for i in cleaned_model if len(i) >= 1] …