Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is my delete viewonly deleting the latest entry?
I'm trying to get my delete_entry view to delete the correct entry, however whichever delete button I click, it's referring to the same item_id. I have changed the view so that it prints the entry to be deleted rather than deleting it, and whichever button I choose from the list, it selects the same entry. Is there something in my view that isn't working? My edit functionality is working as expected, so is it worth just changing delete_entry to work in the same way as EditHealth? Health_hub_history.html: {% for item in stats %} <tr> <td>{{ item.user }}</td> <td>{{ item.weight }} </td> <td>{{ item.date }}</td> <td>{{ item.run_distance }}</td> <td>{{ item.run_time }}</td> <!-- Button trigger modal --> <td> <a href="edit/{{ item.id }}"><button type="button" class="btn btn-primary"> Edit </button> </a> </td> <td> <button type="button" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#staticBackdrop"> Delete </button> </td> <!-- Modal --> <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="staticBackdropLabel">Are you sure you want to delete this entry?</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> If you just need to amend something, try the edit button. </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button> <a href="delete/{{ item.id }}"><button class="btn btn-danger">I'm sure</button></a> … -
Class Based View Reverse URL not reversing to URL with id
I have different views trying to add a product for one member created on the app not a user with authentication more of a one admin management system. below is my code kindly help much appreciated. I get an error django.urls.exceptions.NoReverseMatch: Reverse for 'read_hairbty' with no arguments not found. 1 pattern(s) tried: ['read_hairbty/(?P[0-9]+)$'] Views.py Create Appointment class HBTYOrderView(BSModalCreateView): model = HbtyOrder template_name = 'accounts/modals/hairbty/create_hbtyordr.html' form_class = HairbtyOrderForm success_message = 'Success: Appointment was created.' success_url = reverse_lazy('read_hairbty') View Appointment class HBTYReadView(generic.ListView): model = HbtyOrder context_object_name = 'hairbty' template_name = 'accounts/modals/hairbty/read_hbty.html' allow_empty = True pk_url_kwargs = 'hbtycustomer_id' paginate_by = 100 def get_queryset(self): qs = self.model.objects.filter(hbtycustomer_id=self.kwargs['pk']).order_by('-date_created') p_f = HbtyOrdersFilter(self.request.GET, queryset=qs) return p_f.qs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = HbtyOrdersFilter(self.request.GET, queryset=self.get_queryset()) return context Urls.py path('read_hairbty/<int:pk>', views.HBTYReadView.as_view(), name='read_hairbty'), path('create_hairbtyorder/', views.HBTYOrderView.as_view(), name='create_hairbtyorder'), -
redis-server installation error on ubuntu 18.04
error I'm trying to install redis-server for celery use, but I'm getting an error. how can i resolve it? -
Based on the dropdown value ,store the form data to respective tables in django
Django, I have 3 models, In the html form there is a drop down menu with three value, based on the dropdown value selected ,the data from the form should be stored in the respective model table. Like if the first dropdown selected then on form submission the data should be stored in the first table, and so on. Please provide some inputs on this, thanks. -
How to add .htaccess file in Django
I try to add a .htaccess file in the Django project but could not find any solution. My project is deployed on AWS. Here is .htacess code RewriteEngine On RewriteBase /precure/ RewriteRule ^manage\.py - [F] RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ django.cgi/$1 [QSA,L] -
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.