Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django uploading file from disk to S3 using django-storages
In my Django project I use django-storages to save files to S3 uploaded via a Form. Model is defined as class Uploads(models.Model): file = models.FileField(upload_to=GetUploadPath) I'm making changes to the file that was uploaded via Form by saving to disk and then trying to pass a File object to the model.save() method. with open(os.path.join(settings.MEDIA_ROOT, s),"rb") as f: file_to_s3 = File(f) If I pass the file object using request.FILES.get('file') then the in-memory file gets uploaded properly, however when I try to upload the modified file from disk, I get this error, RuntimeError: Input C:\Users\XXX\File.csv of type: <class 'django.core.files.base.File'> is not supported. Followed this post but doesn't help, any thought's please. -
What could i do if I've an existing database with an user table and I want to use it for django login
I've an existing database with an user table in sql server, how can I use that table dbo.users for my django login and authenticate it -
form.errors is not returning bad request
Upon submitting a form, the desired outcome is to display validation error messages in the template if the form is not valid. When it comes to what I'm actually getting and the form doesn't catch the errors (I have Max_length = 240... doesn't catch an error when text is > 240). forms.py: from django import forms from .models import Postit MAX_POST_LENGTH = 240 class PostForm(forms.ModelForm): class Meta: model = Postit fields = ['content'] def valid_content(self): content = self.validated_data.get("content") if len(content) > MAX_POST_LENGTH: raise forms.ValidationError("This message is too long") return content views.py: from django.http import HttpResponse, Http404, JsonResponse from django.shortcuts import render, redirect import random from django.utils.http import url_has_allowed_host_and_scheme from .forms import PostForm from .models import Postit # Create your views here. def homepage_view(request, *args, **kwargs): return render(request, 'pages/home.html', context={}, status=200) # create a new post and add to database def post_create_view(request, *args, **kwargs): form = PostForm(request.POST or None) next_url = request.POST.get('next') or None # pass next_url to respones if form.is_valid(): obj = form.save(commit=False) obj.save() if request.headers.get('X-Requested-With' or "HTTP_X_REQUESTED_WITH") == 'XMLHttpRequest': return JsonResponse(obj.serialize(), status=201) # testing if ajax is true if next_url is not None and url_has_allowed_host_and_scheme(next_url, 'localhost'): # if next_url invalid, no redirect - and check if safe return redirect(next_url) … -
Django model form will not validate due to this error
im running a django app and trying to create an instance of an object using a django form that the user will submit on the frontend html side. the error i get at the end seems to correspond with the category attribute this is what the class model looks like in my models.py class Listing(models.Model): title = models.CharField(max_length=64) description = models.TextField() image = models.ImageField(blank=True) categories = ((1,"Clothing/Footwear"), (2,"Books"), (3,"Electronics"), (4,"Cosmetics"), (5,"Toys"), (6,"Home/Garden"), (7,"Sport/Leisure")) category = models.CharField(choices=categories, max_length=2) starting_price = models.DecimalField(decimal_places=2, max_digits=10) lister = models.ForeignKey(User, on_delete=models.CASCADE, related_name="selling") here is what the class form looks like class Listing_Form(forms.ModelForm): class Meta: model = Listing fields = "__all__" here is my views.py function def create(request): if request.method == "POST": form = Listing_Form(request.POST) print(form.errors) if form.is_valid(): print('valid') form.save() return HttpResponseRedirect(reverse("index")) else: print('invalid') else: form = Listing_Form() when that line in the views function occurs print(form.errors) it gives me the following error ul class="errorlist" li category ul class="errorlist" li Select a valid choice. 7 is not one of the available choices." -
Django Ajax: set url with two dynamic url paths (<str:'variable'>/<str:'other_variable'>/get/)
I have a Django ajax template that will get all the Players from a players model: <body> <h1>List of Players:</h1> <ul id="display-data"> </ul> </body> <script> $(document).ready(function(){ setInterval(function(){ $.ajax({ type:"GET", url: "{% url 'getPlayers' %}", # Here is where I think the problem is success: function(response){ console.log(response); }, error: function(response){ alert("An error occured") } }); },1000); }) </script> However my urls.py file for the template that I need to run this for is a dynamic url: urlpatterns = [ path('<str:league_id>/<str:league_title>/draft/', draft, name='draft'), path('<str:league_id>/<str:league_title>/getPlayers/', getPlayers, name="getPlayers"), ] # Include url path is /league/ The problem is that the url set in the Ajax function is not including the league_id and league_title. Does anyone know how to add those parameters when setting the url path for the Ajax function? Or if that is even the problem with my setup? Here is my views.py for the draft and the get: def draft(request, league_id, league_title): league = League.objects.get(id=league_id) context = {'league': league} return render(request, 'league/draft.html', context) def getPlayers(request, league_id): league = League.objects.get(id=league_id) players = league.available_player.all() return JsonResponse({'players': list(players.values())}) -
How to generate huge random number of test data based on django models on both mongodb and mysql
I want to write a script that automatically generates huge random for testing on both MongoDB and MySQL. And every time I run that script, it will delete old data and re-generate a new one. These data will depend on fields I defined in the Django model. Should the script take care of makemigrations/migrate also or I handle that part and the script just generate test data? Any suggestion? -
Why are we reassigning self.prog_name in the ManagementUtility class?
This is the code snippet in the django that I'm tryin to parse. -
How to properly display the format of date time in Django?
I want to add the date and time when I uploaded a specific file in my database in Django. In my models.py, I added this line of code: models.py date_added = models.DateTimeField(auto_now_add=True) In the template, I added this code: {% block content %} <div class="container"> <tr> <td> CAR LIST </td> <td> Date Added </td> </tr> {% for car in cars %} <tr> <td><a href="{% url 'show-car' car.car_id %}">{{ car }}</a></td> <td>{{ car.date_added }}</td> </tr> {% endfor %} </div> {% endblock %} It correctly displays the date however the time only shows "midnight". How do I format the datetime into Month, Day, Year, Hours, Minutes, Seconds? -
Filter by other fields in Django Rest Framework's SlugRelatedField
I have a model with multiple ForeignKey relationships and am looking to build a POST API that allows me to post their verbose names rather than ids. This seems like a job for SlugRelatedField, however this does not allow me to provide a queryset that is filtered based on other fields within the JSON post. The problem is that the fields need to be filtered based on other fields within the JSON request. class GenericReportSerializer(serializers.ModelSerializer): """ GenericReportSerializer for POST. """ organization = serializers.SlugRelatedField(slug_field='name', queryset=models.Organization.objects.all()) subdivision = serializers.SlugRelatedField(slug_field='name', queryset=models.Subdivision.objects.all()) # queryset needs to be filtered by organization prediction_model = serializers.SlugRelatedField(slug_field='name', queryset=models.PredictionModel.objects.all()) # queryset needs to be filtered by both organization and subdivision class Meta: model = models.GenericReport fields = '__all__' # use all fields Organizations are unique by name, so SlugField is fine. However, subdivisions do not have unique names and need to be filtered by the organization, and the prediction_model needs to be filtered by both the organization AND the subdivision. I haven't found a convenient way to chain filters together in Django Rest Framework and extending the SlugRelatedField class doesn't give me access to the entire data structure. Is there a good way to accomplish this? -
Django allowed_hosts issue deploying to AWS Elastic Beanstalk (DisallowedHost exception)
I am trying to deploy my dockerized django app to Elastic, but I keep getting a DisallowedHost exception: django | Traceback (most recent call last): django | File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner django | response = get_response(request) django | File "/usr/local/lib/python3.9/site-packages/django/utils/deprecation.py", line 135, in __call__ django | response = self.process_request(request) django | File "/usr/local/lib/python3.9/site-packages/django/middleware/common.py", line 48, in process_request django | host = request.get_host() django | File "/usr/local/lib/python3.9/site-packages/django/http/request.py", line 148, in get_host django | raise DisallowedHost(msg) django | django.core.exceptions.DisallowedHost: Invalid HTTP_HOST header: '10.1.XX.XXX'. You may need to add '10.1.XX.XXX' to ALLOWED_HOSTS. I am not sure what the ip relates to but it is different everytime I try to deploy. my settings: ALLOWED_HOSTS = ['my.domain', 'xxx.ap-southeast-2.elasticbeanstalk.com'] I have tried adding the EC2 private ip dynamically following this answer (2nd answer not the accepted one): ALLOWED_HOSTS not working in my Django App deployed to Elastic Beanstalk Similarly this way: Django ALLOWED_HOST setting for Elastic beanstalk instance behind Elastic Load Balancer I've also tried this answer to create custom middleware: Django ALLOWED_HOSTS with ELB HealthCheck When I set allowed hosts to '*' it successfully deploys. -
Can you return a JsonResponse from a django context processor?
I am trying to create an app that will send an ajax request to the server every 30 seconds to get the updated time to then display. My request is being make to the url '/' and I want to use a context processor to intercept that request and response with a JsonResponse object that holds the time. This is my javascript file that is making the request: async function makeRequest(url, method, body) { let headers = { 'X-Requested-With': 'XMLHttpRequest', 'Content-type': 'application/json' } let response = await fetch('/', { method: method, headers: headers, body: body }) return await response.json() } async function getTime() { const data = await makeRequest('/', 'get') let time_h1 = document.getElementById('time') time_h1.innerHTML = await data['time'] setTimeout(getTime, 30000) } getTime() Here is my context processor: def update_time(request): if request.headers.get('X-Requested-With') == 'XMLHttpRequest': cur_time = pytz.timezone(get_timezone(request)) standard_time = datetime.now(cur_time).strftime("%-I:%M%p") return JsonResponse({'time': standard_time}) return {} When I add this to my settings and run the server I get this error everytime I refresh ValueError: dictionary update sequence element #0 has length 24; 2 is required Is there any way to response with the time like this using a context processor? -
Sort based on where the search string found
Is it possible to sort the search result based on where the search string is found? Basically I am using Django Rest and trying to show the results on top if the search string is found at the beginning. For example, values = [ "another test", "test", "something", "teeest"] search_string="te" result=["another test", "test", "teeest"] I want to bring the last two in the front as it has "te" at the begining like result=[ "test", "teeest", "another test"] -
Run a Batch Insert into another tables after inserting multiple items into table
There is a activity "Goods Receive Note" where we are receiving one item or more than one item from supplier. At the event of posting the stock of each item require to insert into store table where is stock maintained with flagged "GRN". I can't figure it out, how to insert all record at once in Store and StoreDet at the time GRN is posted. for example: in given picture i bought two items from Texco having rate of each unit and the quantity i received. Once i added all invoice items and attempting save button, on same occasion i am trying to save all records into Store and StoreDet tables. and the quantity goes to increase field. admin.py from django.contrib import admin from .models import GrnItemsDet, PaymentMethods, Warehouse, MaterialMaster, MaterialType,GrnNote class GrnNoteInline(admin.TabularInline): model = GrnItemsDet class GrnDetAdmin(admin.ModelAdmin): inlines = [ GrnNoteInline ] def invoiceNumber(self,obj): return obj.get_value() admin.site.register(PaymentMethods) admin.site.register(Warehouse) admin.site.register(MaterialMaster) admin.site.register(MaterialType) admin.site.register(GrnNote,GrnDetAdmin) admin.site.register(GrnItemsDet) model.py from email.policy import default from sqlite3 import Timestamp from tabnanny import verbose from unittest.util import _MAX_LENGTH from django.db import models ############### # Warehouse < # ############### WAREHOUSE_TYPES = ( ('Frozen','Frozen'), ('Cold','Cold'), ('Dry','Dry'), ('Misc.','Misc.') ) class Warehouse(models.Model): name = models.CharField(max_length=20,blank=False, null=False, unique=True, verbose_name='Warehouse Name') whtype = models.CharField(max_length=25, … -
Django Rest Internationalization not working on some language
I am using Django Rest Framework and its Internationalization function. I can now get a auto translated response on default errors response by adding "Accept-Language" on header. I tried "zh-hans" is working but "zh-hant" not working. I also tried "ja-JP" , "de" its working. Is there a list for me to check the language code? I found a name list from here https://explore.transifex.com/django-rest-framework-1/django-rest-framework/ it said its support Chinese Traditional and Chinese (Taiwan). I tried zh-tw not working too. -
Counting the children matching grandchildren conditions in Django
Given the following models: class Flight: class Checklist: flight = ForeignKey(Flight) class Item: checklist = ForeignKey(Checklist) completed = BooleanField() I need to get the number of completed checklists for each flight. A checklist is considered completed when all of its items are completed. I know for checklists I can do Checklist.objects.annotate( is_complete=~Exists(Item.objects.filter(completed=False, checklist_id=OuterRef('pk'))) ) but I need something for flights, something like Flight.objects.annotate( completed_checklists=Count(Checklist.objects.annotate(<is complete annotation).filter(is_complete=True) ) -
Ordering a column in Django admin is not working on remote server but is ok locally
In Django admin, I can order each table according to whatever column I want, without having to specify anything in the model: A little arrow describing the ordering is normally appearing after clicking on a column header. admin.py: from django.contrib import admin from .models import User from .resources import UserAdminResource from import_export.admin import ExportActionModelAdmin class UserAdmin(ExportActionModelAdmin, admin.ModelAdmin): resource_class = UserAdminResource list_display = [f.name for f in User._meta.fields] list_display.remove("id") admin.site.register(User, UserAdmin) resources.py: from import_export import resources from .models import User class UserAdminResource(resources.ModelResource): class Meta: model = User models.py: from django.db import models from django.conf import settings class User(models.Model): name = models.CharField( max_length=256, verbose_name=_("Name"), null=False ) address = models.CharField( max_length=256, verbose_name=_("Address"), null=True, blank=True ) city = models.CharField( max_length=256, verbose_name=_("City"), null=True, blank=True ) class Meta: verbose_name = _("User") verbose_name_plural = _("Users") def __str__(self): return self.name But when deployed on a remote server, clicking on the column header makes it quickly blink, but it's not working (i.e. it's not ordering the rows), even so the URL changes to: server.org/admin/lorem/user/?o=2 for example. Is there anything special to do when one want to sort columns in the Django admin on a remote server compared to a local machine? Both the local and remote deployment are on … -
Django REST Framework - multiple views for single endpoint
I recently learned a bit about RESTful design with Django/DRF, I want to know how to have 1+ views for single endpoint depending on request method (GET, POST etc.) !NOT ONE VIEW WITH DIFFERENT METHODS, BUT ONE VIEW FOR EACH METHOD FOR SAME ENDPOINT!. I can't find the way to do that simple thing. I know about viewsets and generic stuff BUT I want to do this that way and via restframework.views.APIView only Suppose I have views.py (views are 100% fine): class ClubListView(APIView): def get(self, request): clubs_qs = Club.objects.all() serializer = ClubSerializer(clubs_qs, many=True) return Response(serializer.data, status=status.HTTP_200_OK) class ClubCreateView(APIView): def post(self, request): serializer = ClubSerializer(data=request.data) serializer.is_valid(raise_exception=True) new_club = create_club(**serializer.validated_data) serializer = ClubSerializer(new_club) return Response(serializer.data, status=status.HTTP_201_CREATED) So the question is how can I set those 2 views to http://localhost/api/players/ endpoint with Django, so if it's POST the creating view is triggered, if GET - the list view. Idk maybe I just need to create single view that inherits those 2, but maybe there is more proper way implementing that. Thanks in advance -
is django queryset.distinct() necessary when you are not using queryset.values()?
I'm trying to wrap my head around the distinct method of the django queryset class, the thing I'm having trouble understanding is when to actually use it. note that I'm not talking about the "distinct on" feature of postgres. I understand that each model instance has to have an id property and ids are unique so when you are querying model instances it's not really possible to get duplicate models/rows. so is the following use of distinct redundant? User.objects.distict() I know that one correct use of the distinct method is when you use the values method and you don't select the id, you might have values that are duplicate and you could use distinct in these scenarios. is there any other scenario where one might need to use distinct (e.g. when using select_related or prefetch_related)? -
try to save values in the filter after reloading the page in the django template
I try to save values in the filter after reloading the page in the django template. My code: <label for="structDivisions">Structural divisions</label> <select id="structDivisions" class="form-select form-select-sm" name="struct_division"> {% for SD in struct_divisions %} <option value="{{ SD.id }}" {% if SD.id == struct_division.id %} selected {% endif %}>{{ SD }}</option> {% endfor %} </select> it doesn't work also a tried like this: <label for="structDivisions">Structural divisions</label> <select id="structDivisions" class="form-select form-select-sm" name="struct_division"> {% for SD in struct_divisions %} <option value="{{ SD }}" {% if SD == struct_division.select %} selected {% endif %}>{{ SD }}</option> {% endfor %} </select> it doesn't work too -
Django URLs: Best practice when passing data to the view
I've googled this, and I'm not finding any answers: When is it appropriate to pass values through (appended to) a URL and into a view versus passing data, let's say JSON, in a request? For instance, when sending filter variables to run through a query to build a response, it seems like either approach is feasible. -
request media files in django when the debug is false
i tried to set media root and media url in but when the debug is false don't return anything settings.py ... DEBUG = False ALLOWED_HOSTS = [ '127.0.0.1', '0.0.0.0', ... ] ... STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR / "static", ] STATIC_ROOT = BASE_DIR / 'staticfiles' MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = 'media/' urls.py ... urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) ... What should i do to return media files in my projects -
Django constraint - allow only one object with same bank/mortgage and status that is not equal to DRAFT
I have a model Application with fields bank, mortgage and status. For same bank and mortgage I want to allow only one application with status different from DRAFT. class Application(..): bank = .. mortgage = .. status = .. # draft, active, in_progress etc. So there can be multiple applications like these: # ok Application(bank=1, mortgage=2, status='draft') # ok, tuple mortgage and bank already exists but but status is draft Application(bank=1, mortgage=2, status='draft') # ok, tuple mortgage and bank already exists but status is active Application(bank=1, mortgage=2, status='active') # ERROR - tuple mortgage and bank already exists and there is already one object with same tuple bank, and non-draft status Application(bank=1, mortgage=2, status='in_progress') # ok - bank is different Application(bank=3, mortgage=2, status='active') In words, I can't create an application with same bank and same mortgage and status that is not draft if there is already an application with same bank and mortgage and status that is not draft. Is it possible to do such constraint? Would CheckConstraint work? -
possible alternative to psycopg2.connect
I have made a chatting app in django (with log in and sign up) , and I have configured the database (created tables through the pgadmin4 gui) my sign-up function is something like this : @csrf_exempt def signUp(request): IP = request.META.get('REMOTE_ADDR') jned = json.loads(request.body) email = jned['email'] password = jned['password'] user_id = tokenGen() user_token = tokenGen() now = int(time.time()) create_user = f'''insert into auth_user(idx,email,passwordx,ip,utime,tokenx) values ('{user_id}','{email}','{password}','{IP}','{now}','{user_token}')''' try: connection = psycopg2.connect(user="postgres", password="0000", host="127.0.0.1", port="5432", database="project1") except: print('error in connection ') cursor = connection.cursor() cursor2 = connection.cursor() cursor2.execute(f"SELECT * FROM auth_user WHERE email = '{email}'") if cursor2.rowcount >0 : print('email already exists') return HttpResponse(json.dumps({'status':'email already exists' , 'done':False})) else: values('{jned['email']}','{ip}','{hashit(jned['password'])}','{token}',{int(time.time())})") cursor.execute(create_user) connection.commit() return HttpResponse(json.dumps({'status':'never used this website huh?' , 'done':True, 'token':user_token})) everything works perfectly fine. but I think that I am connecting to the database in a wrong way, all the tutorials on youtube setup the database in settings.py , taking a completely different path (they use models and django.db). so , the question is : can I push this to production or should I write all the database models even though I don't need them? -
How send value from view to template form url
i am passing parameter in url i want to pass parameter from veiw by render() function and put in form url template. url.py path('log/<x>', csrf_exempt(views.login) , name='login-bot') veiw.py def login(request, x=123): return render(request, 'chat/user_info_add.html', {'x':x} ) template (user_info_add.html) here look i have put value in x={{x}} but not working mean not geting value------- in action attribute of form i tried '{{x}}' and work just as string not that value which i was sending from veiw but without quote it giving template syntax error <div class="first_loginbox"> <form action="{% url 'chat:login-bot' x={{x}} %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class ="second_loginbox"> <label for="login_screen" class="label_login">Add Info</label><br> <input type="email" class="form-control marg" " name="email" placeholder="Enter Email Address"> <input id="css2" type="text" class="form-control marg " name="name" placeholder="Enter your Name"> <button id = "css3" class="btn btn-outline-success">Login</button> </div> </form> </div> please if any one could help how we put value inside {% url 'chat:login-bot' {{x}} %} error Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '{{x}}' from '{{x}}' -
Subscribe to all changes of instances of the model
I'm using this example: https://djangochannelsrestframework.readthedocs.io/en/latest/examples/model_observer.html I'm displaying all the data from model Post on the page in the table. I decided to use websockets for this and stuck on this issue: If I'm changing/adding/deleting instances of model using django admin panel - all works fine, but if I'm doing changes by hand in the shell or my celery worker updating the database - then nothing happens, what can be an issue? My code so far: consumers.py from djangochannelsrestframework import permissions from djangochannelsrestframework.generics import GenericAsyncAPIConsumer from djangochannelsrestframework.mixins import ListModelMixin from djangochannelsrestframework.observer import model_observer from .models import Post from .serializers import PostSerializer class PostConsumer(ListModelMixin, GenericAsyncAPIConsumer): queryset = Post.objects.all() serializer_class = PostSerializer permissions = (permissions.AllowAny,) async def connect(self, **kwargs): await self.model_change.subscribe() await super().connect() @model_observer(Post) async def model_change(self, message, observer=None, **kwargs): await self.send_json(message) @model_change.serializer def model_serialize(self, instance, action, **kwargs): return dict(data=PostSerializer(instance=instance).data, action=action.value) my template: index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous" /> <title>Code with SJ</title> </head> <body> <div id="app" class="row mt-5"> <div class="col-1"></div> <div class="col-10"> <div class="card"> <p class="card-header">Display list of all the posts in Real-Time</p> <div class="card-body"> <table class="table align-middle mb-0 bg-white"> <thead …