Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error in the configuration of django parameter files in VSC
Good evening, I am following a python course on the web, dictated by the Universidad Pontificia de Chile, according to the video and documentation provided by them, using django. At the moment I am configuring the parameters for the Views of django. The first web page works perfectly, but when reconfiguring the views.py and urls.py files, to take information provided by the user through the API gives the following message: Request Method: GET Request URL: http://127.0.0.1:8000/music/ Beatles Using the URLconf defined in AyudantiaMP1.urls, Django tried these URL patterns, in this order: music/ artists/<artist_id>/ [name='artist_detail'] music/ [name='index'] admin/ The current path, music/Beatles, didn’t match any of these. I do not find it wrong. Greetings and thank you in advance Below are the related .py files: view.py from django.http import HttpResponse def index(request): return HttpResponse('Bienvenidos a la app de música!') def artist_detail(request, artist_id): return HttpResponse('Estás viendo al artista %s.' % artist_id) urls.py (app) from django.urls import path from . import views urlpatterns = [ path('artists/<artist_id>/',views.artist_detail,name='artist_detail'), path(' ' , views.index,name='index'),] urls.py (environment) from django.contrib import admin from django.urls import path from django.urls import include urlpatterns = [ path('music/',include('music.urls')), path('admin/', admin.site.urls),] According to the course, by configuring the parameters shown, the web page will … -
Django 404 image for profile picture
I have added a new attribute to my django model that includes a imagefield attribute for profile pictures: Models.py: class AvailableDrinks(models.Model): drink_name = models.CharField(max_length=200) store_name = models.ForeignKey('Stores', on_delete=models.CASCADE,) description = models.CharField(max_length=1200) drinksSlug = models.SlugField(unique=True, null=True) photo = models.ImageField(upload_to="static/media/images/drinkPhotos", blank=True) def __str__(self): return self.drink_name Views.py: class DrinksView(generic.DetailView): template_name = "drinks.html" context_object_name = "drinks" model = AvailableDrinks slug_url_kwarg = 'drinksSlug' def get_object(self): return get_object_or_404(AvailableDrinks, drinksSlug=self.kwargs['drinksSlug']) def get_queryset(self): return AvailableDrinks.objects.all() class StoreView(generic.DetailView): template_name = "caffeine-stores.html" model = Stores context_object_name = 'stores' slug_url_kwarg = 'slug' Url.py: urlpatterns = [ path("", HomeView.as_view(), name="home"), path('<slug:slug>/', StoreView.as_view(), name="stores"), path("<slug:slug>/<slug:drinksSlug>/", DrinksView.as_view(), name="drinks"), path("<int:account_id>/select_drinks/", views.select_drink, name="select") ] print(settings.DEBUG) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Settings.py: STATIC_URL = 'static/' MEDIA_URL = '' MEDIA_ROOT = BASE_DIR I have printed out my directories to make sure that they are properly pointing to the image files. I have also insured that they are uploading correctly from the admin page yet I still get an error: ""GET /static/media/images/drinkPhotos/icepop_drink.jpeg HTTP/1.1" 404 1888". Am I just missing something simple? I originally was getting a file attribute error saying that there was no file associated with the imagefield but I got around that with some fiddling. Now the website displays but the images revert to their alt … -
cant create django superuser when User model extends Abstract User
I am trying to create a custom user model by inheriting from AbstractUser.Only issue is that I am not able to create a SuperUser in my terminal. It prompts me to enter my username and then throws this error after that django.db.utils.OperationalError: no such column: api_user.name this is what my user model looks like: class User(AbstractUser): name = models.CharField(max_length=200) email = models.EmailField(unique=True) password = models.CharField(max_length=200, default="") dob = models.DateField("Date Of Birth",blank=True, default=None) profileImg = models.ImageField(upload_to='frontend/src/assets/profileImgs/',blank=True) createdAt = models.DateTimeField(auto_now_add=True) REQUIRED_FIELDS = [] USERNAME_FIELD = "username" def __str__(self): return self.username def was_published_recently(self): return self.createdAt >= timezone.now() - datetime.timedelta(days=1) def to_dict(self): return{ "id": self.id, "name": self.name, "email": self.email, "password": self.password, "dob": self.dob, "profileImg": os.path.basename(self.profileImg.name), "createdAt": self.createdAt, } I am really new to django so I am not sure what am I doing wrong here -
Several Django Projects
I want to create several django projects that use the same package; can I create them in the same virtual environment won't this create conflict? the idea is that each of them can use a separate database. or would it be better to list each in its own directory? I put them all in the same directory and therefore the same virtual environment -
Django & HTMX - make forms render_field a target of HTMX
I've created a django form where user can input partial name of a client. HTMX displays all matching clients and when button is pressed next to clients name, I'd like it to fill multiple form fields. Let's consider simplified Django manual form example: invoices/templates/invoice_add.html {% extends 'base.html' %} {% load widget_tweaks %} {% block content %} <form method='POST' autocomplete='off'> {% csrf_token %} <label>{{ form.number.label_tag }}</label> {{ form.number.errors }} {% render_field form.number class="form-control" %} <br> <label>{{ form.buyer_name.label_tag }}</label> {{ form.buyer_name.errors }} {% render_field form.buyer_name class="form-control" hx-post="/invoices/check_client/" hx-trigger="keyup" hx-target="#buyer_names_list" %} <div id="buyer_names_list"></div> <br> <label>{{ form.buyer_tax_no.label_tag }}</label> {{ form.buyer_tax_no.errors }} {% render_field form.buyer_tax_no class="form-control" %} <br><div id="tax_no_test"></div> <input type='submit' value='save'/> </form> {% endblock %} As mentioned above, when populating buyer_name I'm getting a list of client names with a button next to their name inside buyer_names_list. This button calls below function to pull the tax number: invoices/views.py def particular_client_invoice(request): client_obj = Client.objects.all().filter(name=request.POST.get('clientname')) context = {'client_tax_no': client_obj.values_list('tax_no', flat=True)[0]} return render(request, 'partials/specific-invoice.html', context) My issue: While it properly returns desired tax number, I can only return the values from HTMX inside a div (id="tax_no_test" in this case). I'd like field form.buyer_tax_no to be the target field of the tax number. Is that possible? Alternatively (worse … -
How do I change the URL a user copies in Django?
Building a DJANGO app. All the links on one of my pages when you click 'copy link' don't return the links URL but the GET command that I'm firing off in a custom function, for context clicking a link increments a vote counter in the app and then it redirects to the actual link, however this is preventing users from getting the URL of that link if they use right-click -> copy link in a browser. How do I intercept a 'Copy Link' request and pass the actual URL to the user? I've not been able to find any resources on the web to help me, granted I'm not sure what I'm searching has been the right keywords. -
Render a django template without a django app
I am very new to Django. I have the following Django template, and I would like to render it to display the username variable. How can I do this without setting up an entire Django app structure? <html> <body> hello <strong>{{username}}</strong> your account is activated. </body> </html> I've seen this question, but when I run the code there, I get an error message: ImproperlyConfigured: No DjangoTemplates backend is configured. -
Nginx configuration for both front-end and back-end in same file
I have an app hosted on a server with Nginx and Gunicorn. This app’s frontend is built using React while the backend Django. I do understand how to configure Nginx and Unicorn for a Django app. But what I want is every request to the ‘/admin/’ and ‘/api/‘ should be sent gunicorn, but every other request to the root url and others should be sent to the react app to handle. I have the below configuration for Nginx to serve Django but I don’t know how to go about it for the frontend and back-end in one configuration file. # /etc/nginx/sites-available/myapp server { listen 80; server_name myapp.com www.myapp.com location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/myapp; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Thank you for your assistance -
how to filter in the django admin-site through created fields
class Ron(models.Model): ron_id=models.AutoField(primary_key=True,verbose_name='identificador') ron_nombre=models.CharField(max_length=50,verbose_name='Nombre') ron_descripcion=models.CharField(max_length=1000,verbose_name='Descripcion') fk_ron_clasi_tipo=models.ForeignKey('ClasificacionTipo',on_delete=models.CASCADE,verbose_name='Clasificacion y Tipo') fk_ron_anej=models.ForeignKey('Anejamiento',on_delete=models.CASCADE,related_name='ron_anejamiento',verbose_name='Añejamiento') fk_ron_grado_alco=models.ForeignKey('GradoAlcohol',on_delete=models.CASCADE,related_name='ron_grado_alcohol',verbose_name='Grado Alcohol') fk_ron_color=models.ForeignKey('Color',on_delete=models.CASCADE,related_name='ron_color',verbose_name='Color') fk_ron_prove=models.ForeignKey('Proveedor',on_delete=models.CASCADE,related_name='ron_proveedor',verbose_name='Proveedor') fk_ron_lugar=models.ForeignKey('Lugar',on_delete=models.CASCADE,related_name='ron_lugar',verbose_name='Origen',limit_choices_to={'lugar_tipo':'parroquia'}) I have this model, in the fk_ron_lugar I have limited options so that only the parishes can be selected in the adminsite, but I would like to generate a kind of filter where you have three fields, first choose the state, then the municipalities of the state you referred to, and finally the parishes of said municipality, and when you save, the parish ID is used+ -
The group_send in channel_layers from django does not work when running multiple times
I was learning about django-channels and wanted to create a basic timer that tells me every second, or rather sends a response to the react frontend/ client every sec as to many seconds has it been since a certain button has been clicked. But it seems that the group_send method of the channel_layer runs only the first time, but in my code the time update of the timer is in the consumer class, which i cannot access if the group_send method does not work. Here is the consumer.py file import json import asyncio from channels.generic.websocket import AsyncWebsocketConsumer from django.utils import timezone class HelloConsumer(AsyncWebsocketConsumer): async def connect(self): # Join the hello_group when a WebSocket connection is established await self.channel_layer.group_add('hello_group', self.channel_name) await self.accept() async def disconnect(self, close_code): # Leave the hello_group when a WebSocket connection is closed await self.channel_layer.group_discard('hello_group', self.channel_name) async def receive(self, text_data): # Handle the received message if text_data == 'hello': # Update the last_hit timestamp self.scope['last_hit'] = timezone.now() else: await self.send(text_data=json.dumps({'error': 'Invalid message'})) async def send_hello_message(self, event): # Send hello message to the client while True: print('hehe2') last_hit = event.get('last_hit', None) if last_hit: seconds_ago = (timezone.now() - last_hit).seconds await self.send(text_data=f'Hello World hit {seconds_ago} seconds ago') else: await self.send(text_data='Hello World … -
Specifying css file for admin
I am trying to change styles for displaying my model in Django Admin: class ContentAdmin(MyAdmin): ... class Media: css = { 'all': ('css/myadmin.css',) } The file myadmin.css is located in static/css/. When running locally, the following appears in the console when loading the admin page: "GET /static/css/myadmin.css HTTP/1.1" 404 1804 It looks like the request is going to the correct location where the file is resides. So, why isn't it found? -
DUPLICATION FINDING FOR ROW BASE ON COLUMN
Looking at the table in the image we could see that the row for SNO 1 with Reference number PAP123 is a duplicate of the row for SNO 3 with Reference number PAP123. We could see that the duplication happens in the CUTTING column and that is why under the DUPLICATION column for both SNO 1 and SNO 3 there is a "True" condition and in parentheses the CERTIFICATE No. and BATCH for its duplicate is indicated together with the column in which the duplicate is happening. We could also see that under the WEEDING column duplication happens for SNO 2 and SNO 4 but it is not marked as duplicate because the REFERENCE NO. are not the same. Now I want to use this same logic to modify the code below so that the output will look for duplicates like in the table of the image. For duplicate to happen a row needs to have at least a column value repeated and the value should fall under the same column. Also, the Reference no. for both rows should be the same. duplicate_mask = combined_data.duplicated(subset=[ 'SLASHING BEFORE LINING & PEGGING', 'CUTTING OF PEGS', 'LINING & PEGGING', 'PLANTAIN /ECO TREE-HOLING', 'COCOA-HOLING', … -
How to fix "nginx: [emerg] "upstream" directive is not allowed" in Nginx with Django?
I want to use Django, Python, Nginx. I made the /etc/nginx/sites-availabe/microdomains.conf file like this: upstream django { server unix:///home/christian/microdomains/microdomains.sock; } server { listen 80; server_name ubuntuchristian; charset utf-8; # max upload size client_max_body_size 75M; # Django media and static files location /media { alias /home/christian/microdomains/media; } location /static { alias /home/christian/microdomains/static; } # Send all non-media requests to the Django server. location / { uwsgi_pass django; include /home/christian/microdomains/uwsgi_params; } } However, when testing, it generates the error: (md) christian@ubuntuchristian:~/microdomains$ sudo nginx -t -c /etc/nginx/sites-available/microdomains.conf nginx: [emerg] "upstream" directive is not allowed here in /etc/nginx/sites-available/microdomains.conf:1 nginx: configuration file /etc/nginx/sites-available/microdomains.conf test failed Any suggestions to handle this error? I need that the nginx works fine. -
Django Channels WebSocket Connection Returns 404 Not Found
I'm working on a Django project with Django Channels to handle WebSocket connections. I've set up my routing and consumers, but when I try to open a WebSocket connection from my JavaScript code, I get a 404 Not Found error. Here's my JavaScript code: var chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/'); And here's my Django Channels routing: # routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/$', consumers.ChatConsumer.as_asgi()), ] When I try to open the WebSocket connection, I get this error in the console: GET http://localhost:8000/ws/chat/ 404 (Not Found) I've also configured Django Channels to use Redis as the channel layer in my settings: # settings.py CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } I've checked and double-checked my routing and everything seems to be in order. What could be causing this error? How can I debug this issue? Any help would be appreciated. -
Django save() is not properly saving my object
I have two models one named Post and the other Journey. Each Journey contains a query set of Post objects. When I add a post to the posts of Journey and save both the new Post and the Jounrey, the post does save properly but the Journey doesn't. The Post is beign properly created because in my JourneyView it is displayed after it is created but when I refresh the Post no longer appears as part of the Journey. I checked the database manually and the new post is saved and the object does exist it is just not being saved as part of the Journey. This is the function I am using to create the post: #Create post @api_view(['POST']) def post_create(request): form = PostForm(request.POST) attachment = None attachment_form = AttachmentForm(request.POST, request.FILES) #journeys = Journey.objects.filter(created_by_id=request.user.id) #journey = Journey.objects.get(id = post.journeyID) if attachment_form.is_valid(): attachment = attachment_form.save(commit=False) attachment.created_by = request.user attachment.save() if form.is_valid(): post = form.save(commit=False) post.created_by = request.user post.save() journey = Journey.objects.get(id = post.journeyID) #journey.posts.set(journey.posts.all()) journey.save() #save_Journey(post.journeyID) if attachment: post.attachments.add(attachment) user = request.user user.posts_count = user.posts_count + 1 user.save() serializer = PostSerializer(post) return JsonResponse(serializer.data, safe=False) else: return JsonResponse({'error': 'add somehting here later!...'}) I already tried using a for loop to save … -
How to obtain a queryset from unrelated models in Django
I am developing a website on car spare parts. The main model is Part, which has different parent models, such as Category and Brand. I want to automatically generate the menu from my database. If I had one level menu, "Category", this is pretty straightforward. I just select all categories, which have at least one part in them, and pass them to the template in the context: category_list = Category.objects.annotate(num_parts=Count('parts')).filter(num_parts__gt=0) context['category_list'] = category_list return context But now I want my menu to be two-level, consisting of categories and brands: Wheels Toyota Ford Renault Radiators Ford Mersedes Or course, I don't want to obtain empty menu options, where are no parts. Please give me a hint, how can I do this! -
get multiple query params with the same key in drf django-filter
I am going to use django-filter to perform filtering in Django models everything is fine but i have two problems 1.In the url, I must send the brand name or do not send the brand name at all, if I send the brand name empty, an error will occur -> how can i fix it? http://127.0.0.1:8000/api/products/filtered_data/?brand_name=nike -> correct http://127.0.0.1:8000/api/products/filtered_data/ -> correct http://127.0.0.1:8000/api/products/filtered_data/?brand_name= -> { "brand_name": [ "Select a valid choice. is not one of the available choices." ] } 2.To get multiple brands, I have to send the brand name several times, but I want to make it possible to send the brand names with ',' http://127.0.0.1:8000/api/products/filtered_data/?brand_name=nike&brand_name=guchi -> i have to send brand names like this http://127.0.0.1:8000/api/products/filtered_data/?brand_name=nike,guchi -> i want to send brand names like this views.py: class ProductFilter(filters.FilterSet) brand_name = filters.ModelMultipleChoiceFilter(queryset=Brand.objects.all(),) class Meta: model = Product fields = ["has_discount","brand_name","available"] class filtered_data(ListAPIView): authentication_classes = [] permission_classes = [] queryset = Product.objects.all() serializer_class = ProductSerializer filterset_class = ProductFilter models.py: class Brand(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Product(models.Model): category = models.ManyToManyField(Category, related_name='cat_product') name = models.CharField(max_length=200) has_discount = models.BooleanField(default=False) brand_name = models.Foreignkey(Brand, on_delete = models.CASCADE) brand_image = models.ImageField(null=True,blank=True,upload_to='product') create = models.DateTimeField(auto_now_add=True) available = models.BooleanField(default=True) discount = models.IntegerField(blank=True, null=True) -
If we provide a physical path of the backend and frontend, is it possible to deploy using WordPress apis
i have backend code in django and frontend code i want to deploy on wordpress i gave path of my frontend and backend If we provide a physical path of the backend and frontend, is it possible to deploy using WordPress apis. -
django OneToOneField to abstract object
i want a field be OneToOneField to an abstract object, the abstract will be never used, instead will be used subclasses: from django.db import models class Abs(models.Model): useType = True absName = models.CharField(max_length=10, default='mickey', blank=True) class Meta: abstract = True from django.db import models from .abs import Abs class Sub(Abs): useType = False name=models.CharField(max_length=10, default='', blank=True) from django.db import models from .abs import Abs class ParentClass(models.Model): abs = models.OneToOneField(Abs, on_delete=models.CASCADE) but when make makemigrations i receive following error: books.ParentClass.abs: (fields.E300) Field defines a relation with model 'Abs', which is either not installed, or is abstract. books.ParentClass.abs: (fields.E307) The field books.ParentClass.abs was declared with a lazy reference to 'books.abs', but app 'books' doesn't provide model 'abs'. If Abs was a real object all works fine, but Abs should never be a real object, so i thought should be abstract, it's only a basket to common info/methods, an interface. Is there a way to do that? Many thanks -
Django - dynamic filtering multiple querysets
I want to make a monthly breakdown of expenses by type of expenses. I would like to enter the start date and end date dynamically through the filter form, so that I don't have to duplicate the code for each month. For each type of expense I created a separate queryset (more than 20). Here is the view.py def monthly_analysis_november(request): accountant = Expenses.objects\ .filter(date__gte = "2023-11-01", date__lte = "2023-11-30", type_of_expense = "accountant expenses")\ .annotate(price=Sum(F('quantity')*F('price_per_unit')))\ .aggregate(total_accountant=Sum('price')) interest_rates = Expenses.objects\ .filter(date__gte = "2023-11-01", date__lte = "2023-11-30", type_of_expense = "interest rates")\ .annotate(price=Sum(F('quantity')*F('price_per_unit')))\ .aggregate(total_interest_rates=Sum('price')) phones = Expenses.objects\ .filter(date__gte = "2023-11-01", date__lte = "2023-11-30", type_of_expense = "phones")\ .annotate(price=Sum(F('quantity')*F('price_per_unit')))\ .aggregate(total_phones=Sum('price')) oil = Expenses.objects\ .filter(date__gte = "2023-11-01", date__lte = "2023-11-30", type_of_expense = "oil")\ .annotate(price=Sum(F('quantity')*F('price_per_unit')))\ .aggregate(total_oil=Sum('price')) leasing = Expenses.objects\ .filter(date__gte = "2023-11-01", date__lte = "2023-11-30", type_of_expense = "leasing")\ .annotate(price=Sum(F('quantity')*F('price_per_unit')))\ .aggregate(total_leasing=Sum('price')) other_expenses = Expenses.objects\ .filter(date__gte = "2023-11-01", date__lte = "2023-11-30", type_of_expense = "other")\ .annotate(price=Sum(F('quantity')*F('price_per_unit')))\ .aggregate(total_other_expenses=Sum('price')) ... Here is the model.py I've created class Expenses(models.Model): date = models.DateField() place_of_expense = models.ForeignKey(ConstructionSite, on_delete=models.CASCADE, blank=True, null=True) TYPE_OF_EXPENSE_CHOICES = ( ("oil", "oil"), ("leasing", "leasing"), ("material", "material"), ("land leasing", "land leasing"), ("spare parts", "spare parts"), ("tools and equipment", "tools and equipment"), ("services", "services"), ("accountant expenses", "accountant expenses"), ("interest rates", "interest rates"), ("phones", "phones"), ("other", … -
Django REST Framework: Custom Validator for Image URL Not Working as Expected
I'm currently working on a Django REST Framework project where I have a ProjectModel with both an image_file field (for uploaded images) and an image_url field (for externally hosted images). Additionally, I have a custom validator (ImageURLValidator) to validate the image_url field. The models and serializer classes look like this: models.py: from django.db import models class ProjectModel(models.Model): image_file = models.ImageField( null=True, blank=True, upload_to='project/%Y/%m/%d' ) image_url = models.URLField( null=True, blank=True ) serializers.py: from rest_framework import serializers from .validators import ImageURLValidator from .models import ProjectModel class ProjectSerializer(serializers.ModelSerializer): image_url = serializers.URLField( required=False, allow_null=True, allow_blank=True, validators=[ImageURLValidator()] ) class Meta: model = ProjectModel fields = ['id', 'image_file', 'image_url'] validators.py import requests from rest_framework import serializers from django.core import validators from django.utils.translation import gettext_lazy as _ class ImageURLValidator: def __call__(self, value): if not value.startswith(('http://', 'https://')): raise serializers.ValidationError( _("URL must start with 'http://' or 'https://'") ) try: validators.URLValidator()(value) except serializers.ValidationError: raise serializers.ValidationError( _("Invalid URL format") ) # Fetch content from URL and check image format response = None try: response = requests.get(value) response.raise_for_status() # Check for error status except requests.exceptions.RequestException as e: raise serializers.ValidationError( _("Error fetching content from URL: %(error)s") % {'error': str(e)} ) content_type = response.headers['content-type'] if not content_type.startswith(('image/')): raise serializers.ValidationError( _("URL must point to an … -
Dynamically change used database table while django app is running?
I want to create a service that has a page to configure a data base table (columns and types) and that allows to CRUD lines in it via the page. The content of that table should then be used for comparison with payload of rest api call. I am quite new to django and don't know if that approach is possible with the django ORM. What I saw so far is that one defines the database scheme hardcoded and I didn't see how I can make my concept running with this. If not I am thinking about representing and managing this dynamically created table via a json or likewise object that is stored in an object database. -
Basic Django Chat Using Sockets Not Sending To The Browser
If anybody can help with this conundrum. This is the django socket server for an absolutly un authenticated chat, everything is working upto saving the entry to the database. But the send event is not reaching the browser. import asyncio import websockets from asgiref.sync import sync_to_async from django.core.management.base import BaseCommand, CommandError from pages.models import Message clients = [] class Command(BaseCommand): help = "Start Web Sockets" def handle(self, *args, **options): global clients @sync_to_async def update(data): print('** Saving **') message = Message(message=data) message.save() async def handler(websocket): while True: data = await websocket.recv() print('** Received **') clients.append({'websocket': websocket}) await update(data) print('** Broadcasting **') for client in clients: this_websocket = client['websocket'] await this_websocket.send(data) print('** Sent **') async def main(): async with websockets.serve(handler, "localhost", 8765): await asyncio.Future() # run forever asyncio.run(main()) In the browser I have the following code submit works as it triggers the socket server to respond and save the data to the database, yet it dosn't send anything to the browser. $(document).ready(function(){ // Open Web Socket websocket = new WebSocket("ws://localhost:8765/"); // Display Submitted Messages websocket.addEventListener('message', function (event) { console.log('** Recieved Message **'); var html = '<div class="s-chat__message">' html += event.data; html += '</div>'; }); // Submit A Message $('#message').submit(function(evt){ evt.preventDefault(); websocket.send($('#id_message').val()); $('#message-input').val(''); … -
limiting choices shown in a the template
I have a list of time choices for booking a table in my model, when user want to book a table he will selec the time from the choices, but i want that as user select the time this time won't be shown again as available until the booking has been canceled or marked as "used". My model... class BookingTable(models.Model): TIME_CHOICES =[ (time(8,0), '08:00'), (time(9,0), '09:00'), (time(10,0), '10:00'), (time(11,0), '11:00'), (time(12,0), '12:00'), (time(13,0), '13:00'), (time(14,0), '14:00'), (time(15,0), '15:00'), (time(16,0), '16:00'), (time(17,0), '17:00'), (time(18,0), '18:00'), (time(19,0), '19:00'), (time(20,0), '20:00'), (time(21,0), '21:00'), ] table = models.ForeignKey(Table, on_delete=models.CASCADE) user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) time = models.TimeField(default='00:00', choices=TIME_CHOICES) def get_absolute_url(self): return reverse("list_tables") def __str__(self) -> str: return self.user.username + "-" + self.table.name class Meta: constraints = [ models.UniqueConstraint(fields=['table', 'time'], name='table_time') ] The view for booking table class BookTableView(LoginRequiredMixin, CreateView): model = BookingTable template_name = 'book_table.html' fields = ['time'] context_object_name = 'booking' def form_valid(self, form): user_bookings = BookingTable.objects.filter(user_id=self.request.user.id) if len(user_bookings) == 0: form.instance.user = self.request.user table = self.get_object(Table.objects) table.save() form.instance.table = table return super().form_valid(form) else: return render(self.request, 'booking_fail.html') -
I can't use get_foo_display in django template
I use 'choice set' in my model but I can't show their labels in template In model: class Malpractice_Detail(models.Model): DayTime_Choice={ ('morning','صبح'), ('noon','ظهر'), ('night','شب'), } Damage_Choice={ ('1','عدم آسیب'), ('2','آسیب به بیمار'), ('3','آسیب به پرسنل'), ('4','آسیب به تجهیزات پزشکی'), } malperactice_choice={ ('1','خطاهای دارویی'), ('2','خطاهای احیاء قلبی-ریوی'), ('3','خطادرتزریقات وخونگیری'), ('4','خطادر ثبت اطلاعات وثبت پرونده'), ('5','خطاهای مراقبتی وبالینی'), ('6','اشتباهات پاراکلینیکی'), ('7','اشتباهات جراحی'), ('8','خطاهای تشخیصی پزشک'), ('9','اشتباهات تجهیزاتی'), ('10','اشتباهات مدیریتی') } hospital=models.ForeignKey('Accounting.hospital', verbose_name='بیمارستان',null=True, on_delete=models.DO_NOTHING) name=models.CharField(max_length=50,verbose_name="نام شخصی که خطا از او سرزده",null=True, blank=True) unit=models.ForeignKey('Accounting.unit', verbose_name='بخش',null=False, on_delete=models.DO_NOTHING) time=models.CharField(max_length=10,choices=DayTime_Choice,null=False,blank=False,verbose_name='زمان وقوع') type=models.CharField(max_length=50,choices=malperactice_choice,null=True,blank=True,verbose_name="نوع خطا") date=models.DateField("تاریخ رخداد خطا", auto_now=False, auto_now_add=False) role=models.ForeignKey('role', verbose_name='سمت خطاکار',null=False,blank=False, on_delete=models.DO_NOTHING) damage=models.CharField(max_length=1,verbose_name='آسیب وارد شده',choices=Damage_Choice,default=1,null=False,blank=False) st_happened=models.TextField(max_length=1000,verbose_name='شرح خطای رخ داده',null=False,blank=False) decisions=models.TextField(max_length=1000,verbose_name='تصمیمات اتخاذ شده',null=True,blank=True) cause_of_accident=models.TextField(max_length=1000,verbose_name='دلیل رخداد خطا',null=True,blank=True) solution=models.TextField(max_length=1000,verbose_name='پیشنهاد و راهکار',null=True,blank=True) user=models.ForeignKey(User, on_delete=models.DO_NOTHING) reporting_datetime=models.DateTimeField(auto_now_add=True) is_seen=models.BooleanField(verbose_name='دیده شده',default=False,null=True,blank=True) has_followup=models.BooleanField(verbose_name='شرح پیگیری دارد',default=False,null=True,blank=True) has_feedback=models.BooleanField(verbose_name='شرح بازخورد دارد',default=False,null=True,blank=True) def __str__ (self): return str(self.st_happened) class Meta: ordering=['-reporting_datetime'] In View: def Index(request): form=Malpractice_Detail.objects.select_related('Hospital','Unit','Role').filter(user=request.user).values('unit__name','date','role__Name','damage','st_happened','is_seen','has_followup','has_feedback') return render(request,"malpractice/index.html",{'form':form}) In template: show damage code but not show damage label {% for item in form %} <td>{{item.date|to_jalali:'%Y/%m/%d'}}</td> <td>{{item.damage}}</td>## This show number of choice <td>{{item.get_damage_display}}</td> ##Not show label <td>{{item.st_happened}}</td> I reed many post about this and try solutions but don't work for me please help me for solve this problem