Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problems with CustomUser model in Django
I am new using Django and I am trying to build a project that requires to use a Custom User Model. I have encountered many problems on my way, tried to resolve them on my own but after more than one week I am exhausted, so I ask for your help. I think the main problem is that I don't understand well how to create a CustomUser model. I need a user to have many fields (E.g full_name, mobile_phone, etc), but one of the critical fields which I've had problems is: division_id (wich is a foreign key for a model created in another app named 'divisions'). I've had a lot of problems because there is no any migration yet (its supposed that your first migration must be when you created your custom user model), so there isn't any values in 'division' model. Is it possible to refer a foreign key in that case considering that the model referred isn't created yet? I mean, the first migration can create a custom user model and a division model simultaneusly, or what I have to do? Another problem I have, is that when I'm trying to refer the Division model into my CustomUser … -
How to import file from a nested directory with django
I am building a django web application. For the code, I have a few helper functions I am trying to import, but django gives me a ModuleNotFoundError. This is my file structure ── stock_predictor ├── __init__.py ├── admin.py ├── apps.py ├── models.py ├── models_helper │ ├── __init__.py │ ├── arma.py │ ├── data_handler.py │ └── yahoo_stock_data.py ├── tasks.py ├── templates │ ├── base.html │ └── homepage.html ├── tests.py ├── urls.py └── views.py Here the models_helper directory contains a list of files I want to import in the tasks.py file. I tried adding the __init__.py file to the models_helper directory, but this does not solve the issue. I also tried adding the path to sys.path. That, too, does not seem to solve the problem. My imports in the tasks.py files are as follows. from models_helper.yahoo_stock_data import YahooStockData from models_helper.data_handler import DataHandler from models_helper.arma import AlgoARMA The error I get is as follows. ModuleNotFoundError: No module named 'models_helper' NOTE: This seems to be a django issue as I can import using sys and run the python script directly from the terminal. These are the links I followed to get the code to work, but it does not. Importing modules from nested folder … -
Permission denied error on django-s3direct
When uploading a file to S3 there comes error like this in console [WARNING][220126 010447] Forbidden: /s3direct/get_aws_v4_signature/ [26/Jan/2022 01:04:47] "POST /s3direct/get_aws_v4_signature/ HTTP/1.1" 403 31 and Permission denied(like javascript alert, but why??) popup is shown on browser. I have checked the credential and Bucket name again and again, but there is no typo. and I can upload the file with this credential from aws-cli However this django code show the permission error. Where should I check ?? in settins.py setup AWS environment. AWS_ACCESS_KEY_ID = '**********' AWS_SECRET_ACCESS_KEY = '*******************' AWS_STORAGE_BUCKET_NAME = 'vr-dev-bot-resource-bucket' AWS_S3_REGION_NAME = 'ap-northeast-1' AWS_S3_ENDPOINT_URL = 'https://s3.ap-northeast-1.amazonaws.com' S3DIRECT_DESTINATIONS = { 'example_destination': { # "key" [required] The location to upload file # 1. String: folder path to upload to # 2. Function: generate folder path + filename using a function 'key': 'uploads/images', # "auth" [optional] Limit to specfic Django users # Function: ACL function 'auth': lambda u: u.is_staff, # "allowed" [optional] Limit to specific mime types # List: list of mime types 'allowed': ['image/jpeg', 'image/png', 'video/mp4'], # "bucket" [optional] Bucket if different from AWS_STORAGE_BUCKET_NAME # String: bucket name 'bucket': 'custom-bucket', # "endpoint" [optional] Endpoint if different from AWS_S3_ENDPOINT_URL # String: endpoint URL 'endpoint': 'custom-endpoint', # "region" [optional] Region if different from AWS_S3_REGION_NAME … -
what is the use of room in the in the render section?
***python Django framework I can't understand what is the use of {'rooms':rooms}) in the render section please help i am just learning django import imp from django.shortcuts import render from django.http import HttpResponse rooms =[ {'id':1, 'name':'learn python'}, {'id':2, 'name':'learn html and javascript'}, {'id':3, 'name':'at last learn django'}, ] # Create your views here. def home(request): return render(request,'home.html', **{'rooms':rooms})** def room(request): return render(request, 'room.html') -
Django how to prevent to showing inbound forms data to others forms?
in my blog page I have comment section where I am rending forms after each comment. Right now if any comment forms didn't successfully submitted then it's showing inbound data to others forms. How to prevent to to showing inbound forms data or invalid data to others forms? here is code: views.py: ...my others code if request.method == "POST": comment_form = CommentFrom(request.POST or None) if comment_form.is_valid(): isinstance.save() ...my others code my html #this is parent forms <form method="POST"> <input type="text" name="name" {% if comment_form.is_bound %} value="{{ comment_form.name.value }} {% endif %}"> <textarea>{% if comment_form.is_bound %}{{ comment_form.comment.value }} {% endif %} </textarea> </form> #this is child forms after every comment inside my for loop <button type="button" data-toggle="collapse" data-target="#collapseExample{{i.sno}}" aria-expanded="false" aria-controls="collapseExample{{i.sno}}"> Replay </button> <form method="POST"> <input type="text" {% if comment_form.is_bound %} value="{{ comment_form.name.value }} {% endif %}" name="name"> <textarea>{% if comment_form.is_bound %}{{ comment_form.comment.value }} {% endif %} </textarea> </form> -
Permission denied error in django app develop. im using windows 10. how to solve this error?
enter image description here how to solve this error in windows. -
Django how deactive User Account
Let's say I want to deactivate the specific User Account when the user clicks Deactivate Account button. How would I do this? \\views.py def delete_view(request): profile = request.user if request.method == 'POST': form = DeleteUserForm(request.POST, request.FILES, instance=profile) if form.is_valid(): profile.is_active = False return redirect('/') else: form = DeleteUserForm(instance=profile) return render(request, 'delete.html', {'form': form, 'profile': profile}) \\forms.py class DeleteUserForm(forms.Form): delete = forms.CharField( label='', max_length=0).widget = forms.HiddenInput() The code was just an attempt, but does not work because of the instance, so you can think away the instance -
django.db.migrations.exceptions.NodeNotFoundError: Migration order.0001_initial dependencies reference nonexistent parent node
I mistakenly deleted all the migrations folders inside the app and also deleted the db. Also, I ran command python manage.py flush. After all when I am running this python manage.py makemigrations I have this same error occurred. I don't know how to resolve it. Please help me to solve this. I am working on a localhost only. ` dependencies = [ ('product', '0016_productvariants_item_num'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ]` -
Routing for FormView Class
I have django_test project and defapp application in it. I want to access form.html which MyView makes, I am still confused about routing. What I know about is like this, path('', views.index, name='index'), calls def index(request): in views.py However how can I access the MyView class? in django_test/urls.py from django.contrib import admin from django.urls import path from django.conf.urls import include,url urlpatterns = [ url(r'^s3direct/', include('s3direct.urls')), path('admin/', admin.site.urls), ] in defapp/views.py from django.shortcuts import render # Create your views here. from django.views.generic import FormView from .forms import S3DirectUploadForm class MyView(FormView): template_name = 'form.html' form_class = S3DirectUploadForm in defapp/template/form.html <html> <head> <meta charset="utf-8"> <title>s3direct</title> {{ form.media }} </head> <body> <form action="" method="post">{% csrf_token %} {{ form.as_p }} </form> </body> </html> -
Heroku Python Deployment Version Issue
Heroku will not push my Python version for my Django app and I can't figure out why... I upgraded my python from 3.8.7 to 3.10.2 and reflected this within the runtime.txt file, and the changes are clearly added, but this isn't seeming to work. From heroku's Python Support: Supported runtimes python-3.10.2 on all supported stacks``` C:\Users\New User\Downloads\django-modal-ajax-crud-main\django-modal-ajax-crud-main>git push heroku main Enumerating objects: 191, done. Counting objects: 100% (191/191), done. Delta compression using up to 4 threads Compressing objects: 100% (173/173), done. Writing objects: 100% (191/191), 72.21 MiB | 1.24 MiB/s, done. Total 191 (delta 35), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: -----> Python app detected remote: -----> Using Python version specified in runtime.txt remote: ! Requested runtime ("python-3.10.2") is not available for this stack (heroku-20). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to whispering-oasis-59527. remote: To https://git.heroku.com/whispering-oasis-59527.git ! [remote rejected] main -> main (pre-receive hook declined) error: failed to push some refs … -
Django modeling a supplier DB with different products. Unable to figure out supplier_product relation table
I am having a Django project where I have a supplier and multiple products which are vastly different from each other. The products are called resources. Because they are very different I cannot have a product table and therefore, don't know how to make the supplier_product model through which I can fetch all the products related to supplier. Here are example models: class Company(models.Model): ...... #some common fields class Supplier(Company): # delivery_time = "3 weeks" delivery_time = models.CharField(max_length=255, blank=True, null=True) # minimun order quantity MOQ = models.FloatField(blank=True, null=True) moq_unit = models.CharField(max_length=255, blank=True, null=True) billing_address = models.ForeignKey( .... ) shipping_address = models.ForeignKey( .... ) There are some more fields in the supplier. Here are the resources: class Resource(models.Model): ....... #some common fields class Part(Resource): code = models.CharField(max_length=255, unique=True, blank=True, null=True) supplier = models.ForeignKey( Company, related_name="supplier_part", on_delete=models.SET_NULL, null=True, blank=True, ) country = models.CharField(max_length=255, blank=True, null=True) class Fuel(Resource): code = models.CharField(max_length=255, unique=True, null=True, blank=True) color = models.CharField(max_length=255) supplier = models.ForeignKey( Company, related_name="supplier_fuel", on_delete=models.SET_NULL, null=True, blank=True, ) Now the problem is how can I make a SupplierProduct models with (supplier, product) field. Which I can use to retrieve all products from a supplier. In that case I will remove the supplier from the Fuel … -
What the meaning of ^ for url
It might be too simple question. I have this urlpatterns in urls.py urlpatterns = [ url(r'^s3direct/', include('s3direct.urls')), path('admin/', admin.site.urls), ] localhost/admin works, but localhost/s3direct shows the 404 error. Page not found (404) Request Method: GET Request URL: http://localhost:8099/s3direct Using the URLconf defined in djang_test.urls, Django tried these URL patterns, in this order: ^s3direct/ admin/ The current path, s3direct, didn’t match any of these. (I use runserver at port 8099) -
How to schedule posts for carousel in templates using django?
I'm having a hard time to come up with a solution on how to schedule posts for bootstrap carousel with dynamic data in django. Example: I created a post for Jan. 1 - Jan. 30 if today is Feb. 1 the post should still be visible on the carousel. -
Django relay filter not working for foreign key field
import graphene from graphene_django import DjangoObjectType from commodity.models import CommodityItem class Brand(models.Model): # more fields... name = models.CharField(max_length=500) class CommodityItem(models.Model): # more fields... is_online = models.BooleanField(default=True) brand = models.ForeignKey( Brand, on_delete=models.CASCADE, verbose_name='Brand', db_index=True) class CommodityItemNode(DjangoObjectType): class Meta: model = CommodityItem use_connection = True description = 'Represents commodity item' filter_fields = { 'is_online' : ['exact'], 'brand_id': ['exact'] } interfaces = (graphene.relay.Node, ) all_commodity_item = DjangoFilterConnectionField(CommodityItemNode) Working query { allCommodityItem(isOnline: true) { edges { node { name } } } } Not Working query { allCommodityItem(isOnline: true, brandId: 1) { edges { node { name } } } } Error: { "status": "error", "errors": [ { "message": "['{\"brand_id\": [{\"message\": \"Invalid ID specified.\", \"code\": \"\"}]}']", "locations": [ { "line": 2, "column": 3 } ], "path": [ "allCommodityItem" ] } ], "data": { "allCommodityItem": null } } Reference: https://docs.graphene-python.org/projects/django/en/latest/tutorial-relay/ -
Correct way to provide cache backend in Django
I am following this part of Django docs trying to add cache to generated sitemaps. Docs provide following sample code: from django.contrib.sitemaps import views as sitemaps_views from django.views.decorators.cache import cache_page urlpatterns = [ path('sitemap.xml', cache_page(86400)(sitemaps_views.index), {'sitemaps': sitemaps, 'sitemap_url_name': 'sitemaps'}), path('sitemap-<section>.xml', cache_page(86400)(sitemaps_views.sitemap), {'sitemaps': sitemaps}, name='sitemaps'), ] It works as expected and caches result in my default cache (redis). But since I have really large sitemap, I would the cache to be stored in file cache, not in memory. My django settings.py does include required settings: CACHES = { # Redis cache "default": { ... }, # File cache "file": { ... }, } However when I try to specify correct arguments to cache_page decorator: urlpatterns = [ path('sitemap.xml', cache_page(86400)(sitemaps_views.index)(cache="file"), # <--- !!! {'sitemaps': sitemaps, 'sitemap_url_name': 'sitemaps'}), ] I receive an error: TypeError: _wrapped_view() missing 1 required positional argument: 'request' Which is the correct way of providing cache backend in such case ? -
Django Pass Parameters in function
I have to update four A records in AWS for that I have. used boto3 python library and for each one I have written the functions as Follows @csrf_exempt @wrap_view def create_A_record_1(request): response = client.change_resource_record_sets( HostedZoneId='**********', ChangeBatch={ 'Comment': 'string', 'Changes': [ { 'Action': 'CREATE', 'ResourceRecordSet': { 'Name': 'one.example.com', 'Type': 'A', 'SetIdentifier': 'main', 'Weight': 100, 'TTL': 300, 'ResourceRecords': [ { 'Value': '1.2.2.3' }, ], } }, ] } ) How can I create the POST function and pass the variable in that ? -
django-countries how to add serializer field
I'm trying to add the CountryField to a serializer for the Register process (using dj-rest-auth) and can't find the correct way to implement it. All the answers I found just say to use what the documentation says, but that doesn't help for me, maybe Im just not doing it right. This is what the documentation of django-countries says: from django_countries.serializers import CountryFieldMixin class CountrySerializer(CountryFieldMixin, serializers.ModelSerializer): class Meta: model = models.Person fields = ('name', 'email', 'country') I need to add the field here: class CustomRegisterSerializer(RegisterSerializer, CountryFieldMixin): birth_date = serializers.DateField() country = CountryField() gender = serializers.ChoiceField(choices=GENDER) # class Meta: # model = User # fields = ('country') # Define transaction.atomic to rollback the save operation in case of error @transaction.atomic def save(self, request): user = super().save(request) user.birth_date = self.data.get('birth_date') user.country = self.data.get('country') user.gender = self.data.get('gender') user.save() return user I tried different things besides this and nothing worked. -
Permission Denied When Installing Packages Using Pip In Docker Container Django
I'm unable to install the package inside my docker container, please let me know how can I solve this. Warning: WARNING: The directory '/home/app/.cache/pip' or its parent directory is not owned or is not writable by the current user. The cache has been disabled. Check the permissions and owner of that directory. If executing pip with sudo, you should use sudo's -H flag. error: ERROR: Could not install packages due to an OSError: [Errno 13] Permission denied: '/home/app' Check the permissions. Dockerfile: FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /app EXPOSE 8000 COPY ./core/ /app/ COPY ./scripts /scripts RUN pip install --upgrade pip COPY requirements.txt /app/ RUN pip install -r requirements.txt && \ adduser --disabled-password --no-create-home app && \ mkdir -p /vol/web/static && \ mkdir -p /vol/web/media && \ chown -R app:app /vol && \ chmod -R 755 /vol && \ chmod -R +x /scripts USER app CMD ["/scripts/run.sh"] command inside container: pip install django-storages -
Django Azure SQL ProgrammingError Invalid Object name
I am trying to use Azure SQL with Django by using mssql-django. I get this error during "makemigrations": django.db.utils.ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name 'customer_group_customergroup'. (208) (SQLExecDirectW); [42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)") The connection to Azure SQL is already working. If I start a new app, I could make the migrations and migrate it into Azure SQL without problem. If I migrate only the "customer_group" App, there is no problem. The problem only occurs when I want to migrate apps, whose model contains a foreign key field named customer_group. I tried renaming the field (suspecting it was some naming conflict) but the error still persists. Does anyone know how to correct this error? Thank you! Edit: My customer_group app has this model: class CustomerGroup(models.Model): name = models.CharField(max_length=50, unique=True, blank=False, null=False, verbose_name="Customer group name") owner_first_name = models.CharField(max_length=20, blank=False, null=False) owner_last_name = models.CharField(max_length=20, blank=False, null=False) address = models.CharField(max_length=100, blank=False, null=False) phone = models.CharField(max_length=15, blank=False, null=False) billing_info = models.CharField(max_length=200, blank=False, null=False) uuid = models.UUIDField(unique=True, default=uuid.uuid4, editable=False, blank=False, null=False) def __str__(self): return self.name -
Django-respondive-images dosen't find files when not in local
i use responsive-images https://pypi.org/project/django-responsive-images/ on my PC django works well and also django-responsive-images when i move all up to my website responsive images dosen't find images in my template file if i use <img class="card-img-top" srcset="{% srcset item.img 200x400 400x800 nocrop %}" src="{% src item.img 400x800 nocrop %}" alt="Card image cap"> i get that error it seems dosen't find file FileNotFoundError at / [Errno 2] No such file or directory: '/code/uploads\\Item\\0\\817_img.jpg' Request Method: GET Request URL: http://www.mysite.it/ Django Version: 3.2.5 Exception Type: FileNotFoundError Exception Value: [Errno 2] No such file or directory: '/code/uploads\\Item\\0\\817_img.jpg' Exception Location: /usr/local/lib/python3.9/site-packages/django/core/files/storage.py, line 238, in _open Python Executable: /usr/local/bin/python Python Version: 3.9.4 Python Path: ['/code', '/usr/local/lib/python39.zip', '/usr/local/lib/python3.9', '/usr/local/lib/python3.9/lib-dynload', '/usr/local/lib/python3.9/site-packages'] Server time: Tue, 25 Jan 2022 14:16:46 +0000 but if i don't use responsive images it works <img class="card-img-top" src="{{item.img.url}}" alt="Card image cap"> do you know why it dosen't work? -
Django Admin route Redirects to /login
i'm a newbie to Django and i just started this project.... After Creating Superuser using this command python manage.py createsuperuser I tried to access the admin route but on typing the /admin on the browser it's displays this error on the browser Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/login Using the URLconf defined in myblog.urls, Django tried these URL patterns, in this order: 1. admin/ I tried adding: LOGIN_REDIRECT_URL = '/admin/' in the settings.py as someone suggested on stackoverflow but it shows the same thing. Kindly direct me on what i'm not doing right -
How to Debug S3direct with django
in settings.py AWS_ACCESS_KEY_ID = ************* AWS_SECRET_ACCESS_KEY = ************** AWS_STORAGE_BUCKET_NAME = "my-bucket-develop-whitebear" S3DIRECT_DESTINATIONS = { 'images': { # "key" [required] The location to upload file # 1. String: folder path to upload to # 2. Function: generate folder path + filename using a function 'key': resource.create_filename, 'key_args': 'my-assets/images', # "auth" [optional] Limit to specfic Django users # Function: ACL function 'auth': lambda u: u.is_authenticated, # "allowed" [optional] Limit to specific mime types # List: list of mime types 'allowed': ['image/jpeg', 'image/png'], 'acl': 'private', # "cache_control" [optional] Custom cache control header # String: header 'cache_control': 'max-age=2592000', # "content_disposition" [optional] Custom content disposition header # String: header 'content_disposition': lambda x: 'attachment; filename="{}"'.format(x), # "content_length_range" [optional] Limit file size # Tuple: (from, to) in bytes 'content_length_range': (10, 10000000), # 10MB # "server_side_encryption" [optional] Use serverside encryption # String: encrytion standard 'server_side_encryption': 'AES256', # "allow_existence_optimization" [optional] Checks to see if file already exists, # returns the URL to the object if so (no upload) # Boolean: True, False 'allow_existence_optimization': False, }, 'videos': { 'key': resource.create_filename, 'key_args': 'my-assets/videos', 'auth': lambda u: u.is_authenticated, 'allowed': ['video/mp4'], 'acl': 'private', 'content_length_range': (10, 200000000), # 200MB } } in forms.py class ResourceCreateForm(BaseModelForm): image = forms.URLField(widget=S3DirectWidget(dest='images'), required=False) class Meta: model = Resource … -
Django: Retrieve list of unique m2m combinations
I have the following model schema in Django (Note that I left out a detailed overview of class ModelB as it is irrelevant for the question) ``` class ModelA(Models.model): b = models.ManyToManyField(ModelB, blank=True) ``` Given a QuerySet of ModelA objects, I would like to receive all unique M2M combinations (of ModelB objects) that are present in the queryset. For example, for the following queryset of 4 ModelA objects: -
Launch script from Django
I have a file named "update_job.py"(it's an ETL). It should be executed each 1h to update data. Now I have an idea for it: using a infinit loop inside the update_job.py and make a sleep of 1h for each time we pass inside the loop and excute the script separately. I think it's a bad practice. Now I wanna know how can I make a job to exectute it from Django. Please help, I'm new to Django. Regards, Minonja -
django updating wrong post
Made a update post fucntion and it is working, however it is always updating just the first post. I am using tabs in html and i think it is because how i pass the form, but cannot figure it out. at first in the html, next to the post to update, is a button <a class="dropdown-item"> <button class="btn btn-info" data-toggle="modal" data-target="#note-update-modal">Update</button> </a> That brings up a form, which is located futher down on the html {% for note in checklist.notes.all %} <form method="POST" action="{% url 'update_notes' note.id title.slug %}" class="modal fade" id="note-update-modal" tabindex="-1" aria-hidden="true"> {% csrf_token %} <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">New Note</h5> <button type="button" class="close btn btn-round" data-dismiss="modal" aria-label="Close"> <i class="material-icons">close</i> </button> </div> <div class="modal-body"> <div class="form-group row align-items-center"> <label for="{{ form.title.id_for_label }}" class="col-3">{{ form.title.label }}: </label> <input class="form-control col" name="{{ form.title.html_name }}" type="text" id="{{ form.title.id_for_label }}" value="{{ note.title }}" placeholder="Note title" required /> </div> <div class="form-group row"> <label for="{{ form.content.id_for_label }}" class="col-3">{{ form.content.label }}</label> <textarea class="form-control col" rows="6" name="{{ form.content.html_name }}" id="{{ form.content.id_for_label }}" placeholder="{{ note.content }}"> </textarea> </div> </div> <div class="modal-footer"> <button role="button" class="btn btn-primary" type="submit"> Update Note </button> </div> </div> </div> </form> {% endfor %} It only brings up the first note, …