Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Process Data within WTForms Submission
I would like to reformat the data submitted via WTForms by utilizing the process_data function. I am able to successfully submit the form, however, the data is not modified in the output as expected. I've included a simplified example of my forms.py file below. The goal of this form would be to input the value of "10,000" and return the string "10000". from flask_wtf import FlaskForm from wtforms import StringField class SimpleForm(FlaskForm): price = StringField('price') def process_price(self, price): price.data = str(price).replace(',','') -
How to create a startup service of django for ubuntu server?
I am creating a project where I am using an ubuntu server for production. I need to run the server in the background even though I log out. So, as a solution I am using screen but however if I restart it won't work as we all know and I have to rewrite the screen commands. So, I want to use the startup service but somehow I am lost in that as I have no idea how to do that.here is the one way to write the script and I love it but how to add the command python manage.py runserver [IP Address] in this service. Sorry if I sound so silly but I need a quick and useful solution, so I thought to be here. Thanks if anyone can guide me on it. -
Django authentication for custom user, user object always return none if the credential is correct
this is my custom user code class CustomUser(AbstractUser): phone_number = models.CharField(max_length=12 , unique=True) Full_name = models.CharField(max_length=55) email = models.EmailField(max_length=60,null=True , blank=True) username = None first_name = None last_name= None USERNAME_FIELD = 'phone_number' REQUIRED_FIELDS = [] def __str__(self): return self.Full_name object = CustomUserManager() this code is to authenticate user in views.py user = authenticate(request,phone_number=username,password=password) -
how to separate sentences and assign each sentence to a list element on template
how do I separate the list of strings by "." and render them into separate "li" elements on the template. Currently, it just displays everything in one "li" element. I would really appreciate it if someone can help, thx! models.py class Product(models.Model): benifits = ArrayField(models.CharField(max_length=800), blank=True) @property def benifits_slicing(self): benifit = self.benifits for point in benifit: test = point.split(".") return point views.py def described_view(request, slug): products = Product.objects.get(slug=slug) context = {"products": products} HTML <div id="BENIFITS"> <li class="benifits-style">{{ products.benifits_slicing }}</li> </div> what it looks like rn: -
How to decrement a list in jinja 3
I am working on creating a hexagon grid with Django. Here is part of the code in the .html template that I am using for this specific loop: {% for item in vertical_list_hex %} {{ form.board }} {% endfor %} Where vertical_list_hex is a list such as [0, 1, 2, 3, 4] and form.board are the individual cells. At the moment it ends up like this: O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O My goal is to decrement the list with -1 in each loop so that it would end up in a hexagon shape: O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O I found some suggested solutions but they are outdated (jinja2). -
Celery jobs not running on heroku (python/django app)
I have a Django app setup with some scheduled tasks. The app is deployed on Heroku with Redis. The task runs if invoked synchronously in the console, or locally when I also have redis and celery running. However, the scheduled jobs are not running on Heroku. My task: @shared_task(name="send_emails") def send_emails(): ..... celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab # set the default Django settings module for the 'celery' program. # this is also used in manage.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_app.settings') # Get the base REDIS URL, default to redis' default BASE_REDIS_URL = os.environ.get('REDIS_URL', 'redis://localhost:6379') app = Celery('my_app') # Using a string here means the worker don't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() app.conf.broker_url = BASE_REDIS_URL # this allows you to schedule items in the Django admin. app.conf.beat_scheduler = 'django_celery_beat.schedulers.DatabaseScheduler' # These are the scheduled jobs app.conf.beat_schedule = { 'send_emails_crontab': { 'task': 'send_emails', 'schedule': crontab(hour=9, minute=0), 'args': (), } } In Procfile: worker: celery -A my_app worker --beat -S django -l info … -
Django/Bootstrap: some basic styles are not working as expected (nav-tab, button)
Using Django with Bootstrap(v5) it seems the "nav-tabs" class is not being styled as tabs, and gray buttons are not being styled as pills. Why is this? I tried using Bootstrap v4 and v5 with no change. <!DOCTYPE html> {% load static %} <html> <head> <meta charset="utf-8"> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <script src="{% static 'js/bootstrap.min.js' %}"></script> </head> <body> <div class="text-center bg-primary text-white"> <h3>My Site!</h3> </div> <div class="container-fluid text-center"> <ul class="nav nav-tabs"> <li class="active"><a href="#">Home</a></li> <li><a href="#">Menu 1</a></li> <li><a href="#">Menu 2</a></li> <li><a href="#">Menu 3</a></li> </ul> </div> <div class="container"> <div class="row"> <div class="col-sm-4"> <h3>Filter</h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p> <button type="btn btn-outline-primary">Reset</button> <button type="btn btn-outline-primary">Filter</button> <div class="alert alert-success alert-dismissible"> <button type="button" class="close" data-dismiss="alert">&times;</button> <strong>Success!</strong> </div> </div> <div class="col-sm-4"> <h3>Select View</h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p> </div> <div class="col-sm-4"> <h3>Chart</h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p> </div> </div> </div> </body> </html> -
How can I memory profile a django command?
How can I memory profile a django command? I tried using the profile decorator from memory_profiler And then I tried to invoke it with: python -m memory_profiler manage.py create_new_bhpt_records 1976020 "2022-04-14 00:00:01+00:00" -batch-size 10000 But the output logs did not include the memory profiling. Note: I added the profile decorator on my handle Command method. -
waitress-serve using local host and then using it in the procfile, But how to change the locasthost variable/dynamically before pushing to heroku?
Need help! I am stuck at the final stage of my first django app deployment on Heroku. Earlier when i used the command "waitress-serve --port=8000 project folder name.wsgi: application" This dint work stating server can't be reached. So i used "waitress-serve --listen=localhost:8000 project folder name.wsgi: application" And it worked. I then added this code inside a procfile _ " web: waitress-serve --listen=localhost:8000 project folder name.wsgi: application " Now when it's time to push to heroku ...as per the process port should be set dynamically by giving a $ sign but in my case, i have used localhost so how to set it in a Dynamic way before pushing to heroku -
How to 301 redirect django url with multiple slashes on url path?
I am trying to figure out how to redirect properly some urls that contain multiple slashes and create a permanent 301 redirect whenever the slug changes. For example: A - https://example.org/category/subcategory/article-name-A B - https://example.org/category/subcategory/article-name-B I want to redirect the A to B. I tried the default redirects app from django but did not work with multiple slashes. What is the correct approach here?! -
In django how can I run a query that (fielda, and fieldb) are in an allowed set of pairs (1, 2), (3, 4)?
In django how can I run a query that (fielda, and fieldb) are in an allowed set of pairs (1, 2), (3, 4)? It doesn't look like this is possible using filter or Q queries. Is it? Or do I need to do this with a raw sql query? -
Celery error received unregistered task of type
I am trying to add celery to my Django-Docker project environment. I have an error: received unregistered task of type 'create_task'. I was trying ideas from Celery Received unregistered task of type (run example) but didn't sucseed (was trying to specify task name, e.g. @app.task(name= ) How can I fix this error? MY project structure . ├── docker-compose.yml ├── project │ ├── core_app └── celery.py ... │ ├── nginx-conf.d │ │ └── nginx-conf.conf │ ├── parser_app ... celery.py from __future__ import absolute_import import os from celery import Celery from core_app.settings import INSTALLED_APPS os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core_app.settings') app = Celery("core_app") app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: INSTALLED_APPS) #@app.task(name='core_app.celery.create_task') # doesn't help @app.task(name='create_task') def create_task(task_type): period = int(task_type) * 10 print("SLEEP ", period) time.sleep(period) return True docker-compose.yml services: django: build: ./project # path to Dockerfile command: sh -c " python manage.py makemigrations && python manage.py migrate && gunicorn --bind 0.0.0.0:8000 core_app.wsgi" volumes: - ./project:/project - ./project/static:/project/static expose: - 8000 environment: - DATABASE_URL=postgres://postgres:post222@db:5432/lk_potok_4" - DEBUG=1 db: ... nginx: ... celery: build: ./project command: celery -A core_app worker --loglevel=info volumes: - ./project:/usr/src/app environment: - DEBUG=1 - DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1] - CELERY_BROKER=redis://redis:6379/0 - CELERY_BACKEND=redis://redis:6379/0 depends_on: - django - redis redis: image: redis:5-alpine -
how to collect the pk of the model that you are currently viewing (django)
hey I'm trying to make a question and answer project for django, how do I get the pk of the question that I am viewing right now to send an answer? I already set it up so that the url of the answer has /answer/pk of the question but I dont know how to get that info so the code knows where to post the model, how do I do that? also here is my code, thanks! views: class AnswerForm(SuccessMessageMixin, CreateView): template_name = 'forum/answer-question.html' model = Answer form_class = AnswerForm success_message = 'Success!' def form_valid(self, form, pk=None): form.instance.question_id = Question.objects.only('id') form.instance.user = self.request.user form.save() return super().form_valid(form) forms: class AnswerForm(ModelForm): class Meta: model = Answer fields = ['detail'] exclude = ('user', 'add_time') urls: from django.urls import path from . import views urlpatterns = [ path('questions/', views.QuestionsView.as_view(), name='questions'), path('ask/', views.AskForm.as_view(), name='ask'), path('answer/', views.AnswerForm.as_view(), name='answer'), path('answer/<pk>', views.AnswerForm.as_view(), name='answer_with_pk'), path('question/<pk>', views.QuestionDetailView.as_view(), name='detail'), path('save-text', views.WriteCommentAnswerView.as_view(), name='save-text'), path('save-vote', views.SaveVoteView.as_view(), name='save-vote'), ] models: class Answer(VoteModel, models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) detail = models.TextField() add_time = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return f"/questions/" def __str__(self): return self.detail -
Django Queryset with multiple joins and filtering
I need a list of jobs joined with houses joined with owners Results row should contain: job_id, job_worker_role1, job_worker_role2, job_worker_role3, house_id, *owner_name, owner_status_name, owner_assigned_user Given that there is a many to many relationship between houses and owners it is acceptable to have multiple result rows for each job, with each owner. class Worker: name = models.CharField() class OwnerStatus: name = models.CharField() class Owner: name = models.CharField() status = models.ForeignKey(OwnerStatus, related_name='owners') assigned_worker = models.ForeignKey(Worker, related_name='assigned_user_owner') class House: owners = models.ManyToManyField(Owner, related_name='assets') class Job: house = models.ForeignKey(House, related_name='jobs') worker_role1 = models.ForeignKey(Worker) worker_role2 = models.ForeignKey(Worker) worker_role3 = models.ForeignKey(Worker) updated_at = models.DateTimeField(auto_now=True) Also, I need to filter by: owner status name or owner status id owner name as string owner assigned worker name as string I am using Django 4.0.1 with postgres -
How to fully test Django ImportMixin via excel
I have an admin model that uses django-import-export via an excel file typically. I want to test it as thoroughly as I can. I can test the file format & headers should be as expected, as well as the widgets used by the resource that controls the import validation. However, I do some changes to the data when its saved & imported, I can't figure out how to test that with the below method or via selenium since it involves an excel file. Tips? I would just like to test that when we import via excel, the things I do in the resource take effect, namely I upload users & add them to groups, but the test method below only tests the dataset is properly setup, it doesn't create any records. I also use Selenium to test user functionality, but didn't find how I could mimic an excel file. from import_export.admin import ImportMixin class CustomUserAdmin(ImportMixin, UserAdmin): # this resource controls the custom checks for the import mixin resource_class = UserResource A snippet of the resource I use, uses several widgets to control validation class UserResource(resources.ModelResource): id = fields.Field(column_name='id', attribute='id') # only here to keep the id on the left, preference … -
Whats wrong with my search string? I am not getting proper data
I want to implement search on my django project. On my following queryset, with else condition its passing correct data. But with if condition whatever I search, it shows nothing. def get_queryset(self): category = self.request.GET['category'] query = self.request.GET['q'] if category == 'all': products = Products.objects.filter(Q(name__icontains=query) | Q(category__name__icontains=query)).all() else: products = Products.objects.filter(Q(category__slug=category), Q(category__slug__icontains=self.request.GET['q']) | Q(name__icontains=self.request.GET['q'])) -
Django Admin Login Form
How do I change the login form used by django admin (want to add a captcha field)? I am using the cookiecutter template and have followed the suggestions in other SO answers, and guides: forms.py class AuthAdminForm(AuthenticationForm): captcha = ReCaptchaField(widget=ReCaptchaV3) show_something_different = forms.TextInput() class Meta(AuthenticationForm): fields = ('email', 'password', 'show_something_different', 'captcha') urls.py from django.contrib import admin from myapp.forms import AuthAdminForm admin.autodiscover() admin.site.login_form = AuthAdminForm admin.site.login_template = 'admin/login.html' urlpatterns = [ # Django Admin, use {% url 'admin:index' %} path(settings.ADMIN_URL, admin.site.urls), ...] I was able to add admin/login.html to my templates dir and extend it. This works to add the google js to the header (can see it in source). But the captcha field and my dummy extra field don't show up. -
How do I make the QuerySet filter use an overloaded comparison operator?
I have a model with a OneToOneField pointing to a parameter model. The latter overloads the python comparison operators, such as <. models.py: class SomeComplexParameter(models.Model): fid = models.UUIDField(primary_key=True, default=uuid.uuid4) value = models.PositiveIntegerField(default=10) def __lt__(self, other): return self.value < other.value class SomeModel(models.Model): ... param = models.OneToOneField(SomeComplexParameter,on_delete=models.CASCADE, null=True) ... When I try to filter SomeModel querysets by chaining param__lt, the overloaded __lt__ method does not get invoked! For example: If I define a threshold SomeComplexParameter instance p_threshold = SomeComplexParameter.objects.create(value=30) and filter SomeModel querysets using SomeModel.objects.filter(param__lt=p_threshold) it returns random set of SomeModel instances each time. What I tried so far: print(SomeModel.objects.filter(param__lt=p_threshold).query) yields SELECT "bricks_somemodel"."fid", "bricks_somemodel"."param_id" FROM "bricks_somemodel" WHERE "bricks_somemodel"."param_id" < 68e1c73401c5412bb91f4cb75ce57e8e which points to the fact that Django isn't using the overloaded operator. Instead it's comparing the uuids (pk for this model). This explains the randomness! I checked that SomeModel.objects.filter(param__value__lt=30) filters correctly, as it uses the native python < operator. But this won't be an option for me, as I must use the overloaded __lt__ method on SomeComplexParameter. Is there some way to configure my models so that filtering with param__lt=p_threshold uses the overridden __lt__ operator? Version info: Django 3.2.13, Python 3.9.0, sqlite -
Static file doesn't exist
output: 'static' in the STATICFILESDIRS setting does not exist. I've tried os.path.join(BASE_DIR, '/static'), but it is doesn't work. I didn't have this problem before adding new html-file and I didn't change static-folder. Setting.py STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'static' ] -
Error Iteration with Django in template two variables in same time
I want to iterate two lists in one loop, and I am getting this error. <ul> {% for protein, ligand in protein_list, ligand_list %} <li> {{protein, ligand}} </li> {% endfor %} </ul> Error during template rendering In template C:\Users\Narsil\dev\django-project\templates\RMSD\main.html, error at line 10 'for' statements should use the format 'for x in y': for protein, ligand in protein_list, ligand_list -
How can I make my Navigation Bar responsive?
I am working on a web-development project. I can not make my Navigation Bar responsive for mobile devices. For desktop, the navigation bar looks right, for mobile devices it is not working. I referred How can I make my navbar responsive? and https://getbootstrap.com/docs/5.1/components/navbar/. I was able to partially make it responsive but the search bar and dropdown menu disappeared from my navBar if I viewed it on a mobile. Here is my original code: {% load static %} <header class="section-header" style="text-align:center;padding:10px;font-weight: 600;position:sticky;top:0;z-index:999; background-color: #000; margin: -40px;"> <section class="header-main"> <div class="container"> <div class="row align-items-center"> <div class="col-lg-2 col-md-3 col-6"> <a href="{% url 'home' %}" class="logo" style="color: #fff; font-weight: 700; font-size: 2em; text-decoration: none;">Py<span style="color: #e7315a;">Tech</span></a> </div> <div class="col-lg col-sm col-md col-6 flex-grow-0"> <div class="category-wrap dropdown d-inline-block float-right"> <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-bars"></i> All category </button> <div class="dropdown-menu"> <a class="dropdown-item" href="{% url 'store' %}">All Products </a> {% for category in links %} <a class="dropdown-item" href="{{ category.get_url }}">{{ category.category_name }} </a> {% endfor %} </div> </div> <!-- category-wrap.// --> </div> <!-- col.// --> <a href="{% url 'store' %}" class="btn btn-outline-primary">Store</a> <div class="col-lg col-md-6 col-sm-12 col"> <form action="{% url 'search' %}" class="search" method='GET'> <div class="input-group w-100"> <input type="text" class="form-control" style="width:60%;" placeholder="Search" … -
How to use action attribute in form correctly
<form action="/contact-us/done"> <input type="submit" name="submit" class="btn btn-primary pull-right" value="Submit"> </form> I want to go to the link in action attribute after i submit, but it not work. Do i misunderstand something? Please help me, thanks!! -
List products in relation to the vendor clicked in django ecommerce
I have listed all the vendors (users which are staff) in my django tempelate using the following code. In tempelates: {% for stf in staff %} <li><a href="{% url 'vendor_products' %}">{{stf.username}}</a></li> {% endfor %} In views: def vendor_products(request): vend_prod = Product.objects.filter(user_id=request.user.id) context={ 'vend_prod': vend_prod } return render(request, "vendor_products.html", context) The usernames of the suppliers(vendors) is already listed. What I want is the products of the respective vendor will be dispalyed in a separate html page when the vendor username is clicked. Now the above code is displaying just the products of the user who is logged in. Here is the products model incase it is needed. class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=150) keywords = models.CharField(max_length=255) description = models.TextField(max_length=255) image = models.ImageField(null=False, upload_to='images/') price = models.DecimalField(max_digits=12, decimal_places=2,default=0) amount = models.IntegerField(default=0) detail = RichTextUploadingField() Thank you in advance! -
How to display Predictive model graph on Django framework?
I've made a predictive model using LSTM which predicts future prices for raw materials like cotton,fibre,yarn etc. At the end of code I used matplotlib library to plot graph which displays the original prices, predicted prices and future predicted prices. This is the graph which shows future prices according to dates How do I display this graph on Django framework? Because I need to deploy this model on a web application using Django but the tutorials I've seen so far show predictive models which take user input and don't really show anything related to plots or graphs. Following is the code: import numpy as np import pandas as pd import matplotlib.pyplot as plt import datetime as dt from datetime import datetime import warnings warnings.simplefilter(action='ignore', category=FutureWarning) from keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint, TensorBoard import os import glob import pandas import numpy from sklearn import preprocessing import numpy as np # Importing Training Set dataset_train = pd.read_csv('201222-yarn-market-price-china--034.csv1.csv') dataset_train.info() # Select features (columns) to be involved intro training and predictions cols = list(dataset_train)[1:5] # Extract dates (will be used in visualization) datelist_train = list(dataset_train.iloc[0]) datelist_train = [dt.datetime.strptime(date, '%m/%d/%Y').date() for date in datelist_train] print('Training set shape == {}'.format(dataset_train.shape)) print('All timestamps == {}'.format(len(datelist_train))) print('Featured selected: … -
'course_custom_tags' is not a registered tag library. Must be one of:
I am trying to add templatetags in using django, but i get this error after creating the template tags, i don't know if there is something i need to change in my settings.py to make this work. template.html {% extends 'base/base.html' %} {% load static %} {% load course_custom_tags %} {% block content %} course_custom_tags.py from course.models import UserCourse , Course register = template.Library() @register.simple_tag def is_enrolled(request , course): user = None if not request.user.is_authenticated: return False # i you are enrooled in this course you can watch every video user = request.user try: user_course = UserCourse.objects.get(user = user , course = course) return True except: return False ```[![enter image description here][1]][1] [1]: https://i.stack.imgur.com/39yyT.jpg