Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Structure such that each column recieves a component
Here is what my Month component looks like essentially a grid with days as columns and hours of the days as rows import React from "react"; export function Month() { const currentDate = new Date(); const days = []; for (let i = 0; i < 7; i++) { const day = new Date(currentDate); day.setDate(currentDate.getDate() + i); days.push(day); } return ( <div className="container justify-content-center "> <div className="row "> <div className="col-md-1">hour</div> <div className="col "> <strong> {new Date().toLocaleDateString("en-US", { weekday: "long" })} </strong>{" "} </div> <div className="col"> <strong> {days[1].toLocaleDateString("en-US", { weekday: "long" })} </strong> </div> <div className="col"> <strong> {days[2].toLocaleDateString("en-US", { weekday: "long" })} </strong> </div> <div className="col"> <strong> {days[3].toLocaleDateString("en-US", { weekday: "long" })} </strong> </div> <div className="col"> <strong> {days[4].toLocaleDateString("en-US", { weekday: "long" })} </strong> </div> <div className="col"> <strong> {days[5].toLocaleDateString("en-US", { weekday: "long" })} </strong> </div> <div className="col"> <strong> {days[6].toLocaleDateString("en-US", { weekday: "long" })} </strong> </div> </div> <div className="row"> <div className="col-md-1">7:00</div> {days.map((day, index) => ( <div className="col pb-5 bg-light border border-dark" key={index}> {day.toLocaleDateString()} </div> ))} </div> <div className="row"> <div className="col-md-1 d-flex">8:00</div> <div className="col pb-5 bg-light border border-dark" style={{ height: "73.33px" }} ></div> <div className="col pb-5 bg-light border border-dark" style={{ height: "73.33px" }} ></div> <div className="col pb-5 bg-light border border-dark" style={{ height: "73.33px" }} … -
Django storing environment variables
I'm making a Django chat project in which all messages are encrypted when sent and decrypted when read. I have this task: “Use a standard cryptographic algorithm (such as AES) to encrypt and decrypt messages. The encryption key must be unique for each user session and stored in a secure location (for example, in environment variables or using a key management system)." I can't figure out how to store the per-session encryption key inside environment variables. My understanding is that static data like the secret key is stored inside environment variables, but it doesn't change on every session. How should I implement the functionality described in the task? -
How to redirect request from Django to FastAPI
I have a Django API and a FastAPI wrapper. Requests will be sent from clients to Django, but I want to redirect them to FastAPI to do some role check (I can't do it in Django for some reasons) then sent it back to Django. For now, I am able to sent request from FastAPI to Django using FastAPI's middleware; but I cannot write a proper middleware for Django to do the same (I am just started with Django for 1 week). Can someone please suggest a solution? -
Django PyLint: Django.core.exceptions.ImproperlyConfigured
My Django app works fine when i am just launch my application through python src/manage.py runserver But i would like to integrate pylint here, and when i launch the command pylint src --load-plugins pylint_django i got the following traceback: Traceback (most recent call last): File "/venv/lib/python3.11/site-packages/pylint_django/checkers/foreign_key_strings.py", line 87, in open django.setup() File "/venv/lib/python3.11/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) ^^^^^^^^^^^^^^^^^^^^^^^ File "/venv/lib/python3.11/site-packages/django/conf/__init__.py", line 102, in __getattr__ self._setup(name) File "/venv/lib/python3.11/site-packages/django/conf/__init__.py", line 82, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MO DULE or call settings.configure() before accessing settings. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/venv/lib/python3.11/site-packages/pylint_django/checkers/foreign_key_strings.py", line 114, in open django.setup() File "/venv/lib/python3.11/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/venv/lib/python3.11/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "/venv/lib/python3.11/site-packages/django/apps/config.py", line 178, in create mod = import_module(mod_path) ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load File "<frozen importlib._bootstrap>", line 1126, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load … -
Django Csv: Having trouble with writerow
This is basicly my code: def export_to_excel(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=responds.csv' writer = csv.writer(response) writer.writerow(["First row", "Foo", "Bar", "Baz"]) writer.writerow(["Second row", "A", "B", "C", '"Testing"', "Here's a quote"]) return response Everything looks ok, but when I really exported it there is something wrong: Everything in just a shell! Why? How so? What should I do? -
MultiValueDictKeyError at generated form element
This is my form: <form action="" method="POST"> {% csrf_token %} <div class="col-4"> <input type="text" name="ad" placeholder="İsim"> {% for question in model.get_questions %} <div class="question col-6"> <div class="header"> {{ question }} <input type="checkbox" name="answ{{forloop.counter0}}"> </div> </div> {% endfor %} <input type="submit" value="Gönder"> </form> When I try to get request.POST['ad'] in the views its pretty working but when I try to get like answ0 it doesnt working. That doesn't appear when I print request.POST also. This is the error I receive: MultiValueDictKeyError at /form/1 'answ0' What is the issue? -
ImportError when setting wagtail development environment : "cannot import name 'Query' from 'wagtail.search.models'"
I'm currently working on a fork of Wagtail (version 6.0a0) and attempting to set up a development environment for contributing to the project. I've followed the standard steps for setting up the project but have encountered an ImportError when running migrations for a Wagtail-based website. Steps I've Taken: Cloned the forked repository locally. Activated a Python virtual environment for my work. Installed the cloned project using "pip install -e .[testing,docs] -U." Executed "npm ci" and "npm run build" for JavaScript dependencies. Created a new Wagtail website in a separate directory. Ran "python manage.py migrate," and encountered the ImportError. Error Message: Traceback (most recent call last): File "path/to/manage.py", line 10, in ... from wagtail.search.models import Query ImportError: cannot import name 'Query' from 'wagtail.search.models' Additional Information: The released version of Wagtail (version 5.2a0) installs successfully using "pip install wagtail" without any issues. My requirements file specifies Django version 4.2, but Django version 4.0.10 is installed in my Python virtual environment.(this version was installed with the cloned wagtail project) The requirements.txt file in the website generated by Wagtail specifies the following: Django>=4.2,<4.3 // wagtail==5.2a0 I at first thought this might be a dependency versions problem because the released version works fine with the … -
How to filter ManyToMany field in Django queryset?
I have models: class VideoParameter(models.Model): member = models.ForeignKey(Tag, on_delete=models.DO_NOTHING, related_name="parameter_tag") value = models.PositiveIntegerField() class Video(TimeStampedModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) parameters = models.ManyToManyField(VideoParameter, related_name="video_parameter") url = models.URLField(verbose_name=_('Url')) (I mean that a video have some parameters like Key-Value (ex. {"rabbit": 1, "panda": 1, "lion": 0})) Then I am trying to get the video, specified by query parameter. (like this /video/?rabbit=1&panda=1&lion=0) The SQL code that I want to do is belows: SELECT app_video.id, count(*) AS match_count FROM app_video INNER JOIN app_video_parameters on app_video.id = app_video_parameters.video_id INNER JOIN app_videoparameter ON app_video_parameters.videoparameter_id = app_videoparameter.id WHERE (app_videoparameter.member_id = 1 AND app_videoparameter.value = 0) OR (app_videoparameter.member_id = 9 AND app_videoparameter.value = 1) OR (app_videoparameter.member_id = 11 AND app_videoparameter.value = 1) ... GROUP BY (app_video.id) ORDER BY match_count DESC; How can I realize this process in Django queryset? -
Categorial Tabs Not Displaying in Nav-Bar Despite Using For Loop - Need Assistance
I'm trying to add multiple category tabs to the nav-bar using a for loop, but the result doesn't seem to show anything. I'm not sure where I went wrong. <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="{% url 'category:category_list' %}" role="button" data-bs-toggle="dropdown" aria-expanded="true"> Danh mục sản phẩm </a> <ul class="dropdown-menu"> {% for category in category_list %} <li><a class="dropdown-item" href="{% url 'category:category_detail' category.id %}">{{ category.category_name }}</a></li> {% endfor %} <li><a class="dropdown-item" href="#">Action</a></li> <li><a class="dropdown-item" href="#">Another action</a></li> </ul> </li> This is result -
How to implement caching for tokens in Django Rest Framework and Firebase Auth
I'm building an API using Django Rest Framework and I was thinking about using Firebase for authentication. I have some questions about how to implement the caching layer. **This is how the application works: ** A user logs in using the frontend (React.js), then when I make an API call to DRF and I pass the auth token sent back by Firebase. Using that token, DRF calls Firebase again to retrieve the user, and finally I retrieve the UserProfile for that user in DRF by querying a Postgres db. I want all this operations to result in the least amount of calls to Firebase, hence I was thinking about caching the (user token, user id) pair. However, I have never implemented caching in Django before and would appreciate any guidance. Also, what caching strategy and tool can you recommend me? Thank you -
Cannot delete "Forgot Password?" on Sign in page. Seems completely unresponsive to code
I'm expecting code to delete "Forgot your Password"?. Screenshot of deployed site (marked problem area in red) I cannot delete "Forgot your Password?" link, the issue seems to be to do with django resorting to default code that I cannot locate. Screenshot here of templates structure In templates/allauth/account/password_change.html I have commented out code {% extends "account/base_manage_password.html" %} {% load allauth i18n %} {% block head_title %} {% trans "Change Password" %} {% endblock head_title %} {% block content %} {% element h1 %} {% trans "Change Password" %} {% endelement %} {% url 'account_change_password' as action_url %} {% element form form=form method="post" action=action_url %} {% slot body %} {% csrf_token %} {% element fields form=form %} {% endelement %} {% endslot %} {% slot actions %} {% element button type="submit" %} {% trans "Change Password" %} {% endelement %} <!-- <a href="{% url 'account_reset_password' %}">{% trans "Forgot Password? TESTHERE" %}</a> --> {% endslot %} {% endelement %} {% endblock content %} Repo links See my full repo here: github.com/lmcrean/Project-4 See deployed site here: http://lmcrean-ittib-b97fbbd27fb0.herokuapp.com/accounts/login/ So far I've tried ... lead to no change in deployed site. I've tried updating file structure to contain account within allauth I've updated settings to … -
Representing NFT wallet addresses in Django model fields
I'm building a Django app that involves working with NFTs, and I want to know the best way to represent NFT wallet addresses using a Django model field. NFT wallet addresses are typically hexadecimal strings, but I'm not sure how to design the model field to accommodate them efficiently. I think the best option is a customization of the CharField with a length constraint to store the hexadecimal address. But is there a recommended maximum length for NFT wallet addresses? I'd exclude UUIDField and TextField. I'd appreciate any examples and recommendations. Thank you! -
Django-Tailwind not rebuilding after updating the template files
I did everything the instructions on the package website told me to; when I launch python manage.py tailwind start, it does indeed rebuild the stylesheets and add any new classes, but the issue is, after that, it just doesn't do anything when I add new classes in my templates. I'm not exactly sure what could be the issue with it, as I set everything up like the instruction said. All configs should be the same, and, I think, in the content config in tailwind.config.js, this is the line that's supposed to detect all of my templates: '../../**/templates/**/*.html' (this file is in [project_name]/theme/static_src/tailwind.config.js, my templates are in [project_name]/[app_name]/templates/[app_name]/[template_name].html, so I think it should check out) Actually, from what I've found out, it doesn't seem to detect changes pretty much anywhere, even in its own template files. While testing this out before actually asking in here, I also found out that changing the tailwind.config.js file itself and saving (even just saving without changes) actually does trigger the rebuild process. Although afterwards I found out that this was probably just because it was a config file, so it didn't really help me at all, the most I can get from this is to … -
Djoser override UserCreateSerializer not creating model instance
I've made modifications to the UserCreateSerializer provided by Djoser. Within the perform_create method, I'm attempting to create instances of the UserProfile and AddressDetails models. While the server appears to be functioning correctly, it seems that the data is not persisting as expected. I'm seeking guidance on identifying and rectifying any errors in this process. How would you suggest addressing this issue? accounts.serializers.py from djoser.serializers import UserCreateSerializer from django.contrib.auth import get_user_model from rest_framework import serializers from django.db import transaction from django.db.utils import IntegrityError from django.contrib.auth.password_validation import validate_password from .models import AddressDetails, UserProfile User = get_user_model() class UserCreateSerializer(UserCreateSerializer): address_line_one = serializers.CharField(write_only=True) address_line_two = serializers.CharField(write_only=True) address_line_three = serializers.CharField(write_only=True) province = serializers.CharField(write_only=True, required=True) barangay = serializers.CharField(write_only=True, required=True) city = serializers.CharField(write_only=True, required=True) zip_code = serializers.CharField(write_only=True, required=True) first_name = serializers.CharField(write_only=True, required=True) middle_name = serializers.CharField(write_only=True, required=True) last_name = serializers.CharField(write_only=True, required=True) date_of_birth = serializers.DateField() gender = serializers.CharField(write_only=True, required=True) relationship_status = serializers.CharField(write_only=True, required=True) phone_number = serializers.CharField(write_only=True, required=True) class Meta(UserCreateSerializer.Meta): model = User fields = ( "id", "email", "user_role", "password", "address_line_one", "address_line_two", "address_line_three", "province", "barangay", "city", "zip_code", "first_name", "middle_name", "last_name", "date_of_birth", "gender", "relationship_status", "phone_number" ) @transaction.atomic def perform_create(self, validated_data): address_line_one = validated_data.pop("address_line_one") address_line_two = validated_data.pop("address_line_two") address_line_three = validated_data.pop("address_line_three") province = validated_data.pop("province") barangay = validated_data.pop("barangay") city = validated_data.pop("city") zip_code = validated_data.pop("zip_code") … -
Add watchlist to product page
By clicking the Add button, the user should be able to add the product to the watch list. After this, the button should be changed to Remo, and by pressing it, the product will be removed from the list. There should be a link title at the top of the page and click on those products that are in the watch list to be displayed. However, these codes do nothing. Why?? forms & models.py: #forms.py class AddWatchlist(forms.Form): product_id = forms.IntegerField(widget=forms.HiddenInput()) #models.py(Related parts) class Product(models.Model): title = models.CharField(max_length=64) views.py: def product_detail(request, product_id): product = get_object_or_404(Product, pk=product_id) comments = Comment.objects.filter(product=product) offers = PriceOffer.objects.filter(product=product).order_by('-offer_price') off_list = [float(product.first_bid)] maximum = float(product.first_bid) if request.method == 'POST': # comment # offer off = maximum context = { 'product': product, 'comments': comments, 'offers': offers, 'off' : off } return render(request, 'auctions/product_detail.html', context) def watchlist(request): products = request.user.watchlist.all() return render(request, 'auctions/watchlist.html', {'products': products}) def add(request): if request.method == 'POST': form = AddWatchlist(request.POST) if form.is_valid(): product_id = form.cleaned_data['product_id'] product = Product.objects.get(id=product_id) request.user.watchlist.add(product) return redirect('product_detail') else: form = AddWatchlist() return render(request, 'auctions/add.html', {'form': form}) def remove(request, product_id): product = Product.objects.get(id=product_id) request.user.watchlist.remove(product) return redirect('watchlist') urls.py: path("product_detail/<int:product_id>/", views.product_detail, name="product_detail"), path('add', views.add, name='add'), path('remove/<int:product_id>/', views.remove, name='remove'), path('watchlist', views.watchlist, name='watchlist'), product_detail.html(Related parts): {% for … -
You cannot call this from an async context - use a thread or sync_to_async Django
I'm making a telegram bot. That's why I use asynchronous methods in django. @dp.message(Command('habits')) async def handle_habits(message: types.Message): chat_id = message.chat.id profile = await TelegramProfile.objects.aget(chat_id=chat_id) user = profile.user await bot.send_message(chat_id, text=user - {user}') I get an error when I call the last line: You cannot call this from an async context - use a thread or sync_to_async. How to fix it? -
Form not valid after setting QuerySet of field in __init__
A new Workorder is created by visiting the Building page and creating a Work Order. This in turn displays the WorkOrderForm on a new page. When viewing this form, I want to display only the equipment associated to a building, not all of the equipment. I have tried overriding the __init__ of the form to set the queryset of the MultipleChoiceField, which works as intended in displaying the equipment associated to the building, however when submitting the form the form.is_valid() fail yet there are no errors displayed. I have 3 models Building, WorkOrder and Equipment as follows: Building class BuildingDetail(models.Model): location_Code = models.CharField(primary_key=True, max_length=15, help_text='Enter a location code.', unique=True) civic_Address = models.CharField(max_length=100, help_text='Enter the civic address of the location.') current_Tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE, help_text='Select a Tenant.') landlord = models.ForeignKey(Landlord, on_delete=models.CASCADE, help_text='Select a Landlord.') WorkOrder class WorkOrder(models.Model): id = models.CharField(primary_key=True, max_length=7, default=increment_workorder, verbose_name="ID") building_Code = models.ForeignKey(BuildingDetail, on_delete=models.CASCADE) issue_Date = models.DateField(blank=True, null=True, default=datetime.date.today()) completion_Date = models.DateField(blank=True, null=True) tenant_Issue = models.TextField(help_text="Enter the issue description.") scope_Of_Work = models.TextField(help_text="Enter the Scope of Work required.") contact_name = models.CharField(max_length=50, help_text='Enter the contact Name.', blank=True, default="") contact_number = models.CharField(max_length=11, help_text='Enter the contact Phone Number.', blank=True, default="") rebill_Invoice = models.TextField(max_length=50, help_text='Enter the Devco Rebill Invoice number.', blank=True, default="") rebill_Date … -
Can i connect django with mongoDb
Does it good to connect django version 4.2.7 With monogdb? Is is a good practice? What is the trade off If there . If not what is best DB AND DBMS to work with it Or just use django models I have seen that a djongo is not a good one because it has a lof of drowbacks -
Django add random character in filename
I want to upload image and overwrite if the file exist without changing the filename. It's already can overwrite the file but django always add random char on the end filename. How can i overwrite with the same filename ? Here are my code. foto_content_url = models.ImageField(null=True, blank=True, upload_to=foto_path) def foto_path(instance, filename): return '/', filename + '.jpg']) -
PostgreSQL database migration problem from my Django project to AWS Elastic Beanstalk
I've just finalised my project based on **Django ** and **PostgreSQL ** *locally * on my Windows 10 machine. When migrating to AWS Elastic Beanstalk using pgAdmin 4, I'm having problems with the database. Despite my efforts to deploy the project with its data, the database on AWS does not contain any of the information previously stored locally. I followed the recommended steps to export my PostgreSQL database with pgAdmin 4 and successfully deployed my Django project on AWS Elastic Beanstalk. However, I can't find the data in the AWS database. I tried to export my PostgreSQL database from pgAdmin 4 as a backup file. Then I imported this file into my AWS database. I expected all my data, such as tables, records, etc., to be copied from my local database to the database on AWS. I checked the permissions and configurations to make sure the login details were correct, but the data doesn't seem to have transferred correctly to the database on AWS. What steps have I missed or what specific configurations are required to ensure the complete transfer of data from my local database to AWS Elastic Beanstalk? -
how to save user progress?
I'm building a learning spoken languages website where the users get to guess pictures, and I'm using Django and React. How to make each user have its own data or, in other words, how to make each user have its own progress? What do I need in Django to do this? I have a solution which is to add a user column in the model I want to save the progress of, and when someone register, an instance of that model will be created. But in this way if I have so many users, I will have a huge database, does anyone know if there is a better way to do that? -
ModuleNotFoundError: No module named 'pygments'
I try to practive with Django REST Framework. I have installed pygments module via: (venv) pip install pygments I see it in installed modules: (venv) pip list Package Version ------------------- ------------ asgiref 3.7.2 Django 4.2.7 djangorestframework 3.14.0 numpy 1.26.1 pandas 2.1.2 pip 23.3.1 Pygments 2.16.1 But when I import it to use and run make migration: (venv) python manage.py makemigrations snippets .... from pygments.lexers import get_all_lexers ModuleNotFoundError: No module named 'pygments' How to solve this problem? I follow the toturial of Django REST framework: https://www.django-rest-framework.org/tutorial/1-serialization/ and stuck at this step. -
Django html table iterating pandas df and create scrollbar
I am working on a django project where I render a pandas df in the context. I then iterate through this data frame to display it in a table td td (html below). I would like to get this as a fixed size with horizontal and vertical scrollbars instead when the data frame is too large. How can I do this? Thnx! :-) <table style="margin-left: auto; margin-right: auto;"> <tr> {% for col in df.columns %} <td> <b>{{col}}</b> </td> {% endfor %} </tr> {% for index, row in df.iterrows %} <tr> {% for cell in row %} <td> {{cell}} </td> {% endfor %} </tr> {% endfor %} </table> -
itrate ManyToMany Field and save the instance of the field
Hi im developing django app for sending bulk email to Users, i have two models name Reminder and Mail , Reminder model has a Assign_to field which is ManyToMany Field with User model, i write a signal for Reminder model for When an instance Created, for every User that assigned in reminder an instance created in Mail model, i user for loop in signal, but i dont have error but it just dosnt work My Mail Model: ``class Mail(models.Model): sender = models.ForeignKey( "accounts.User", on_delete=models.CASCADE, related_name="user_sender" ) recipient = models.ForeignKey( "accounts.User", on_delete=models.CASCADE, related_name="user_recipient" ) subject = models.CharField( max_length=255, ) body = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) is_read = models.BooleanField(default=False) is_archived = models.BooleanField(default=False) is_deleted = models.BooleanField(default=False) is_starred = models.BooleanField(default=False) cc = models.EmailField(blank=True, null=True) bcc = models.EmailField(blank=True, null=True) attachments = models.FileField(upload_to="attachments", blank=True, null=True) importance = models.CharField( max_length=20, choices=[("HIGH", "HIGH"), ("MEDIUM", "MEDIUM"), ("LOW", "LOW")] ) folder = models.CharField( max_length=20, choices=[("INBOX", "INBOX"), ("SENT", "SENT"), ("DRAFT", "DRAFT")], ) is_draft = models.BooleanField(default=False) reply_to = models.EmailField(blank=True, null=True) thread_it = models.CharField(max_length=255, blank=True, null=True) is_replied = models.BooleanField(default=False) tags = models.ManyToManyField("Tag", blank=True) is_forwarded = models.BooleanField(default=False) def __str__(self): return self.subject` ` MyReminder Model: class Reminder(models.Model): reminder = models.CharField( default=generate_pk, max_length=255, unique=True, editable=False, verbose_name="Reminder ID", ) title = models.CharField(max_length=255) description = models.TextField() date = … -
Hello, when ever i submit a contact page they show me the error
Here is the code Views.py enter image description here enter image description here models.py enter image description here Here is the image of my code. Please tell me the solution. How i submit my contact form in my django database.