Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dashboard entry restriction using credit card payment
I have an eccomerce system build with Django with some services in the dashbord , I want to restrict some services from those who have not payed through credit card ,though they can login and perform other services which I offer for free,just like AWS or Canva does for premium services. -
How to typehint custom and overridden Managers in an Abstract Class using django-stubs?
we are trying to add typehints to our django (3.2) project. We are using django-stubs (1.12.0). We have a BaseModel with a custom manager that we use for almost every other model. class BaseManager(models.Manager): # ... class AbstractBaseModel(models.Model): # ... objects = BaseManager() # ... class MyManager(BaseManager): # ... class MyModel(AbstractBaseModel): # ... objects = MyManager() # ... When I run this through mypy (0.982), I get this error on the objects assignment of MyModel: Incompatible types in assignment (expression has type "MyManager[MyModel]", base class "AbstractBaseModel" defined the type as "AbstractBaseModel_BaseManager2[AbstractBaseModel]") How would I add typehints to this? Thank you! -
permission to class some fields of ViewSet method Django rest framework
I wanted AllowAny permission only for the retrieve function. In my ViewSets. class PostLanguageViewSet(viewsets.ViewSet): permission_classes = (permissions.AllowAny,) permission_classes_per_method = { "retrieve": permission_classes } def retrieve(self, request, post_id=None, post_language_id=None, *args, **kwargs): ... def destroy(self, request, post_id=None, post_language_id=None, *args, **kwargs): ... def update(self, request, post_id=None, post_language_id=None, *args, **kwargs): ... -
Почему ошибка?Делаю страницу на django
enter image description here bboardenter image description here Могу в ответе скинуть скрины других файлов -
how to call get_foo_display in html page
I want to show in ListView human redable format instead of actual values. Like From this | fc_mo | c_serv | | --- | --- | | 1 | 5 | To this | fc_mo | c_serv | | --- | --- | | 1 | cardiology | Or to check it values I tried to call it in several ways, but it always get no data from it model.py class LicAppNew(models.Model): id_prof = models.AutoField(primary_key=True, serialize=True) fc_mo = models.CharField(max_length=8, choices=FC_MO_CHOICES) name = models.CharField(max_length=280, blank=True, null=True, choices=FC_NAME_CHOICES_2) date_b = models.DateField(blank=True, null=True, default='01.04.2022') idpr = models.IntegerField(blank=True, null=True, choices=IDPR_CHOICES) disp = models.CharField(max_length=10, blank=True, null=True) date_e = models.DateField(blank=True, null=True, default='01.01.2070') lic_num = models.CharField(max_length=255, blank=True, null=True) c_serv = models.IntegerField(blank=True, null=True, choices=C_SERV_CHOICES) deleted = models.BooleanField(default=False, blank=True, null=True) class Meta: managed = True db_table = 'lic_app_new' #ordering = ['fc_mo'] ordering = ['fc_mo','c_serv'] #def __str__(self): # return self.name() def get_absolute_url(self): return f'/app/{self.id_prof}' views.py class LicAppNew_view(ListView): model = LicAppNew template_name = 'app/LicView_view.html' queryset = LicAppNew.objects.all() class AppLicUpdateView(UpdateView): model = LicAppNew template_name = 'app/detail_app_view.html' form_class = LicAppNewForm success_url = '/app/' LicView_view.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"> <link rel="stylesheet" href="{% static 'ksg/css/ksg.css' %}"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/css/fontawesome.min.css"> </head> <body> <aside> <img src="{% static … -
What could i do if I've an existing database with an user table and I want to use this table for my django app login
I've an existing database created previous my djangoApp, it already contains an user table in my sql server database (cause it's working from the desktop app), the thing is that i want to use same attributes of de sqlserver table in my django app, with inspecdb I took all my sqlserver tables to django model, the thing is how can I use that table (from sqlserver) for my django app to login and authenticate users with this table information? all of this in my local machine using sqlserver and django -
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