Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get a serie of request.POST values
In the following views.py: def valores(request): global peso_unitario, preco_unitario peso_unitario=[] preco_unitario=[] N=a print('N='+str(N)) for i in range(N): peso_u=request.POST['peso_u'] preco_u=request.POST['preco_u'] if peso_u.isdigit() and preco_u.isdigit(): c = int(peso_u) d = int(preco_u) peso_unitario.append(c) preco_unitario.append(d) print(a) print(preco_unitario) if i<N-1: return render(request, 'valores.html') else: return render(request, 'pacote.html', {'peso_unitario': peso_unitario, 'preco_unitario': preco_unitario}) else: res = 'Apenas numero.' return render(request, 'pacote.html', {'res': res}) I have a function that receives a global value N=a, this value was received from the user, now I need to receive N times the both values in request.POST loop, but each time the user needs to enter the values. I don't know how to do this. -
How can I get the number of currently running coroutines of gevent>\?
We are currently developing in the mode of gunicorn+django+gevent. I would like to ask if there is any command line method to obtain the number of currently running coroutines when the service is running -
CORS error when adding <script> tag as a URL query parameter
What I'm working on are making Vue frontend to send GET request with filters to backend Django server. The issue that I'm currently encounter is if is I pass in <script> into the as a value for the filter, it will returns CORS error. For example: url?name=<script> CORS error However, other tag such as <body> works fine as I encoded the value before send to the server. Is there anyone have such experience and what are the possible issues to this? Thanks. -
Django, passing get query has a value to filter query, calls get query twice
I have get query which is passed as a value in filter query ,when running the code get query is called twice. #get query employee = Employee.objects.get( user=self.request.user.email, project=self.request.org_id) #filter query LeaveApproval.objects.filter(approver=employee) #dbCallLog SELECT ••• FROM "leavetracker_employee" WHERE ("leavetracker_employee"."project_id" = 'f5b10d49-9056-4faa-b95a-251f998a724f'::uuid AND "leavetracker_employee"."user_id" ='rajini@gmail.com') LIMIT 21 2 similar queries. Duplicated 2 times. Why employee call is duplicated twice? Thanks in advance. -
Tailwind Dynamic Colour Based on Page/URL
I was hoping someone new how I could dynamically set text/bg colours based on the current page I'm on? I've brought in a navbar from flowbite and it looks like it designed to highlight a specific option based on the page you're on but I don't quite understand how to make that happen. I'm using the Tailwind CDN and Flowbite CDNs. Thanks, Mitchell -
Django views.py code running automatically whenever I reload the server
I have logs which are uploaded and inserted into MySQL table from CSV files using upload_log endpoint in views.py of a Django app. I also have another views.py in a different sub-app (Django as well) that parses the existing data from the logs table and splits it in different rows according to conditions. The problem is the parsing happens whenever I reload the server which creates duplicates besides the fact that it is not my intention to have it like this. I need to have it so that whenever data is uploaded (post is triggered), it runs the function on that uploaded data to parse the logs. Edit (clarification): It doesn't execute when I do py manage.py runserver - But it executes after I run the runserver command and CTRL + S inside the file to reload the server. I would appreciate it if someone guides me through this. Here's the views.py of that task (Logs app): from rest_framework import viewsets from rest_framework.decorators import action from api.packets.models import Fields from .models import LogsParsed from api.logs.models import Logs from .serializers import LogsParsedSerializer class getLogs(viewsets.ModelViewSet): serializer_class = LogsParsedSerializer queryset = LogsParsed.objects.all() parsedLogs=[] for log in Logs.objects.all(): fields = Fields.objects.filter(pac_id=log.message_id_decimal) binaryTest=log.data_binary for field … -
How do I send django object list to javascript?
I want to django query to javascript.so I changed queries to list. I sended list to javascript.But list were not displayed by console log. class Comment_List_TV(ListView): template_name = 'account/user_comment_list_tv.html' def get_queryset(self): Comment_list_query = list(Comment_tv.objects.none()) if self.request.user.is_authenticated: Comment_list_query = list(Comment_tv.objects.filter(user=self.request.user)) print(Comment_list_query) return Comment_list_query Print display object list. But const mydata = "{{Comment_list_query}}"; console.log(mydata); Console log does not display django's object list. why? How do I send django object list to javascript? -
How to call a function in django channels consumers
I defined a sync_to_async def in consumers and i am trying to call it after the receice async function. but no clue how to do this this is my code : async def receive(self, text_data): text_data_json = json.loads(text_data) wsRecDeck = text_data_json['wsDeck'] await self.channel_layer.group_send( self.game_room_name, { 'type': 'send_deck_to_all', 'wsRecDeck': wsRecDeck, } ) @database_sync_to_async def updateDeck(self, wsRecDeck): if(LiveDeckDB.objects.filter(current_deck = wsRecDeck).exists()): LiveDeckDB.objects.filter(current_deck = wsRecDeck).delete() dbDeck = LiveDeckDB.objects.create(current_deck = wsRecDeck) dbDeck.current_deck = wsRecDeck dbDeck.save() print('|||||||Print Test For DB: ',dbDeck.current_deck) async def send_deck_to_all(self, event): wsRecDeck = event['wsRecDeck'] await self.send(text_data=json.dumps({ 'wsAllDeck': wsRecDeck, })) I am trying to call the updatedeck function immediatly after the receive function but i have no clue. Any tips? -
Django Channels sending multiple messages to same channel
Referring to documentation here I'm sending messages to the single fetched channel_name I'm able to successfully send messages to the specific channel Issues I'm facing On the channels it's sending messages multiple times For Example - When I send first message, I receive 1 time. On second message, I'm getting same messages twice. On third message, I'm geting same message 3 times. and so on... class ChatConsumer(AsyncJsonWebsocketConsumer): async def connect(self): self.user_id = self.scope['url_route']['kwargs']['user_id'] await self.save_user_channel() await self.accept() async def disconnect(self, close_code): await self.disconnect() async def receive_json(self, text_data=None, byte_data=None): message = text_data['message'] to_user = text_data['to_user'] to_user_channel, to_user_id = await self.get_user_channel(to_user) channel_layer = get_channel_layer() await channel_layer.send( str(to_user_channel), { 'type': 'send.message', 'from_user': self.user_id, 'to_user': str(to_user_id), 'message': message, } ) await channel_layer.send( str(self.channel_name), { 'type': 'send.message', 'from_user': self.user_id, 'to_user': str(to_user_id), 'message': message, } ) async def send_message(self, event): from_user = event['from_user'] to_user = event['to_user'] message = event['message'] await self.send(text_data=json.dumps({ 'from_user': from_user, 'to_user': to_user, 'message': message, })) @database_sync_to_async def get_user_channel(self, to_user): try: self.send_user_channel = ChatParticipantsChannel.objects.filter( user=to_user).latest('id') channel_name = self.send_user_channel user_id = self.send_user_channel.user.user_uid except Exception as e: self.send_user_channel = None channel_name = None return channel_name, user_id @database_sync_to_async def save_user_channel(self): self.user = User.objects.get(user_uid=self.user_id) ChatParticipantsChannel.objects.create( user=self.user, channel=self.channel_name ) @database_sync_to_async def delete_user_channel(self): ChatParticipantsChannel.objects.filter(user=self.user).delete() -
Django - Reverse for 'topic' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<topic>[^/]+)/\\Z']
I'm learning Django and there was a problem. I will be grateful if you help Reverse for 'topic' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P[^/]+)/\Z'] views: def topic(request, topic): topic = New_topic.objects.get(id=topic) comments = topic.comment_set.order_by('+date') context = {'topic':topic, 'comments':comments} return render(request, 'topic.html', context) urls: from django.urls import path from . import views app_name = "forum" urlpatterns = [ path('', views.main, name='main'), path('<int:topic>/', views.topic, name='topic') ] models: from django.db import models from django.contrib.auth.models import User class New_topic(models.Model): text = models.CharField(max_length=64) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.text class Comments(models.Model): topic = models.ForeignKey(New_topic, on_delete=models.CASCADE) text = models.TextField() date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.text template: main.html {% block content %} {% for list_forum in list %} <a href="{% url 'forum:topic' topic.id %}">{{ list_forum }}</a> {% endfor %} {% endblock content %} topic.html {% block content %} {{ topic }} {% for comment in comments %} {{ comment.text|linebreaks }} {% endfor %} {% endblock content %} -
Python: Display either Video or Image File, but it shows both
I have been working on a social media website where you can upload images and videos and follow other users. I managed to upload and display uploaded files to the website. I used FileField to load the image and video files, but when I implement it in my Template it shows both spaces, because there both using the same source url {{ source.file.url }} models.py class Post(models.Model): title = models.CharField(max_length=150) file = models.FileField(upload_to='uploads/%Y-%m-%d') models code works perfectly feeds.html {% if post.file.url %} <video class="video-context" width="500px" height="500px" controls> <source src="{{ post.file.url }}" type="video/mp4"> </video> {% endif %} {% if post.file.url %} <img class="image-context" src="{{ post.file.url }}" type="image/jpg" type="image/jpeg"> {% endif %} heres a sreenshot empty video player over img Now the problem is that both File Types are going trough one Model: FileField. The source is {{ source.file.url }} , the HTML is searching both files, but there only either image or video, so what can i do with the other empty file? How can I hide it? -
I created a comment section in my Django project and i want to redirect users to that same post they just commented on after they posted the comment
right now it redirects them to the home page. here is the views.py file: class AddReviewView(CreateView): model = Review form_class = ReviewForm template_name = 'blog/add_review.html' def form_valid(self, form): form.instance.post_id = self.kwargs['pk'] return super().form_valid(form) success_url = reverse_lazy('blog-home') and here is the models.py file: class Post(models.Model): title = models.CharField(max_length=100) price = models.DecimalField(default=0, max_digits=9, decimal_places=2) post_image = models.ImageField(null=True, blank=True, upload_to='post_images/') content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Review(models.Model): post = models.ForeignKey(Post, related_name="reviews", on_delete=models.CASCADE) name = models.CharField(max_length=255) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.post.title, self.name) here are my url patterns: urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('marketplace/', MarketplaceView.as_view(), name='blog-marketplace'), path('freelancers/', FreelancersView.as_view(), name='blog-freelancers'), path('user/<str:username>', UserPostListView.as_view(), name='user-posts'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/new/', PostCreateView.as_view(), name='post-create'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), path('about/', views.about, name='blog-about'), path('search-posts/', views.search_posts, name='search_posts'), path('post/<int:pk>/Review/', AddReviewView.as_view(), name='add_review'), ] pleae help me!! note: i want to change the success_url = reverse_lazy('blog-home') to redirect the the page they just commented on -
Django boto3 with s3 not working in production
So I am currently trying to enable large file uploads for my site www.theraplounge.co/ the only problem is I’m using boto3 to upload directly to s3 with https://justdjango.com/blog/how-to-upload-large-files as a guide. The good thing is large files get uploaded when I’m on development server. When I launch code to production server on heroku large files don’t upload anymore. I don’t think code would work locally but not in production which leads me to think the problem may be heroku 30s timeouts although I’m not sure. Anyone got a glue or a hint at what’s going on? -
Reverse for 'category-detail' with arguments '('',)' not found
I get this error when I try accessing my home page. I've tried reading similar solutions but I can't directly relate them to my case. I'm clearly missing something here but I can't see it. this is the traceback error message: Traceback (most recent call last): File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Muhumuza-Ivan\Desktop\JobPortal\jobapp\views.py", line 68, in index return render(request, 'index.html', context) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\shortcuts.py", line 24, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\backends\django.py", line 62, in render return self.template.render(context) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 175, in render return self._render(context) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 167, in _render return self.nodelist.render(context) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 1000, in render return SafeString("".join([node.render_annotated(context) for node in self])) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 1000, in <listcomp> return SafeString("".join([node.render_annotated(context) for node in self])) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 958, in render_annotated return self.render(context) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\defaulttags.py", line 472, in render url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\base.py", line 88, in reverse return resolver._reverse_with_prefix(view, prefix, *args, **kwargs) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\resolvers.py", line 802, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'category-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['jobapp/category/(?P<slug>[-a-zA-Z0-9_]+)/\\Z'] Index.html The error … -
Wagtail-2fa token doesn't work when setting up 2fa after new admin user registration
New users can't seem to set up 2fa--token always fails at set up with wagtail-2fa. Background: I set up a wagtail site a few months ago with Wagtail-2fa (which is based on django-otp). When I first set up an admin user with 2fa, the token works fine. That admin login has no problems using 2fa. When I try to set up new users, I can register the user, but when the user logs in for the first time, it requires 2fa set up (which is the desired behavior) but the token always fails. I've tried Google Authenticator, Symantec VIP, and Duo Mobile. None of them work for new users. Wagtail-2fa uses TOTP so I checked the time on the device and on the server and they appear to match at least to the minute. I've tried the same process on my localhost, staging, and production (the latter two on heroku), and none of them work (but the original admin with 2fa works). My main hypothesis now is that something broke with wagtail-2fa when I upgraded several packages: django 3.1.11 --> 4.0.5 wagtail 2.15.1 --> 3.0.1 It could be that wagtail-2fa doesn't support wagtail 3.0.1 or django 4.0.5. I'm going to … -
POST http://localhost:8000/api/project/create/ 400 (Bad Request) error when sending POST data from the React app using fetch() to Django API
I am working on a simple DRF + ReactJS app, but when I came across making a POST data from React app to the Django API, this error happens on the web console POST http://localhost:8000/api/project/create/ 400 (Bad Request) and it says the problem is on my Create.jsx This is my Create.jsx file: import React, { useState, useEffect} from 'react' import { useNavigate } from 'react-router-dom' import axios from 'axios' const Create = () => { const history = useNavigate() const [title, setTitle] = useState("") const [body, setBody] = useState("") const createProject = async () => { fetch('http://localhost:8000/api/project/create/', { method: "POST", headers: { 'Content-Type': 'application/json' }, title: JSON.stringify(title), body: JSON.stringify(body), }) console.log('title', title) console.log('BODY', body) } return ( <div className="create-project"> <p> <input type="text" onChange={e => setTitle(e.target.value)} value={title} ></input> <textarea type="text" onChange={e => setBody(e.target.value)} value={body}></textarea> <button onClick={createProject}>Submit</button> </p> </div> ) } export default Create And this is the APIView in django: views.py class CreateProject(CreateAPIView): queryset = Project.objects.all() serializer_class = ProjectSerializer urls.py if needed: path('project/create/', CreateProject.as_view(), name="create-project"), -
How to link properly sphinx index.html file to a view
My sphinx documentation is generated properly with custom theme. The documentation file is called index.html which I use as template in a django view to render the documentation. Problem : I lost the the theme sphinx_rtd_theme and links between pages. Could you please help me? -
CKEditor doesn't load on Django admin site
I deployed my project on Heroku but when I login to the admin site on Django, CKEditor doesn't load. I'm using CKEditor in order to implement RichTextField in my models. This is the error GET https://portfolio-jpl.herokuapp.com/static/ckeditor/ckeditor-init.js net::ERR_ABORTED 404 (Not Found) GET https://portfolio-jpl.herokuapp.com/static/ckeditor/ckeditor/ckeditor.js net::ERR_ABORTED 404 (Not Found) Settings.py file # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', 'general', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' # Other settings STATIC_URL_DEFAULT_IMAGE = '/static/base/img/default.png' STATIC_URL_PROFILE_IMAGE = '/static/base/img/personal/' STATIC_URL_IMG = '/static/base/img/portfolio/' I'm a little confused due to I don't have CKEditor folder in the static directory. -
Change field using setter in Admin panel
I have following structure: (Models) class Lessons(models.Model): status_choice = [ ("COMING", _("Coming soon..")), ("PROGRESS", _("In progress")), ("DONE", _("Done")), ("CANCELED", _("Canceled")) ] _status = models.CharField(max_length=15, choices=status_choice, default=COMING_SOON) @property def status(self): return self._status @status.setter def status(self, value): #some validation self.save() And admin.py: @admin.register(Lessons) class AdminLessons(admin.ModelAdmin): list_display = ("class_name", "get_full_status", "time_start", "time_end") @admin.display(description="Status") def get_full_status(self, obj): return [item[1] for item in Lessons.status_choice if item[0] in obj.status] How to implement a setter when the field is changed by the admin panel? Code (above) works when we got requests for changes but how to implement him when changes are made by the admin panel? I will be grateful for your help! -
How to create users in Django?
I am trying to use Django's user model, but when I cannot create a new user. I already ran python manage.py makemigrations and python manage.py migrate. If I try to run the commands again, I get a "No Changes Detected" message. I was able to create a superuser for Django admin, and I can use that user to log into my web application using the views that I created, but if I try to create a user, it does not appear in Django admin. models.py from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): pass views.py for creating the user from django.db import IntegrityError from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User def register(request): if request.method == "POST": username = request.POST["username"] password = request.POST["password"] confirm = request.POST["confirm"] if password != confirm: return render(request, "capstone/register.html",{ "error_message": "Your passwords must match." }) try: user = User.objects.create_user(username, password) user.save() except IntegrityError: return render(request, "capstone/register.html",{ "error_message": "You will need to pick another username." }) login(request, user) return HttpResponseRedirect(reverse("index")) else: return render(request, "capstone/register.html") I have also added AUTH_USER_MODEL = 'capstone.User' to my project's setting.py. … -
Django - Giving a view access to multiple models
I followed a tutorial on Youtube that makes a website to create posts. Currently, I am working on displaying other people's profiles and their posts on their profile pages. I did it by accessing the author of the first post, but it only works if the user posted something. Is there another way to do it? The view: class UserProfileView(ListView): model = Post template_name = 'blog/user_profile.html' # defaults to <app>/<model>_<viewtype>.html--> blog/post_list.html context_object_name = 'posts' #defaults to objectlist paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') user_profile.html: {% extends 'blog/base.html' %} {% block title %}{{ view.kwargs.username }}'s Profile{% endblock title %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ posts.first.author.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ view.kwargs.username }}</h2> <p class="text-secondary">{{ posts.first.author.email }}</p> <p class="article-content">{{ posts.first.author.profile.bio }}</p> </div> </div> {% if posts.first.author == user %} <a class="btn btn-outline-secondary ml-2" href="{% url 'change_profile' %}">Edit Profile</a> {% endif %} </div> <br> {% if posts.first.author == user %} <h3 class="ml-2 article-title">Blogs You Posted</h3> {% else %} <h3 class="ml-2 article-title">Blogs By {{ view.kwargs.username }}</h3> {% endif %} And the Post and Profile module: class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self) … -
Django upgrade to 4.0 Abstract models cannot be instantiated
I'm upgrading my Django App from 2.2 to 4.0.6. I made different code upgrades and have the APP mostly working. But I get the following error "Abstract models cannot be instantiated" and can't find clues on how to solve this (without downgrading Django versiion as in this post Models class AbstractMes(models.Model): mes = models.DateField(blank=False, null=True) operaciones = models.IntegerField(blank=True, null=True) facturacion = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) unidades = models.IntegerField(blank=True, null=True) diferencia = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) diferencia_porc = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) diferencia_media_movil = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) class Meta: abstract = True def __str__(self): return str(self.mes) class Meses(models.Model): mes = models.DateField(blank=False, null=True) operaciones = models.IntegerField(blank=True, null=True) facturacion = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) facturacion_dolar = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) unidades = models.IntegerField(blank=True, null=True) def __str__(self): return str(self.mes) In views meses = Meses.objects.all() abstract_meses = AbstractMes(meses) Any clues welcome. Thanks! -
Django dependent smart-select not working properly
django smart-select not working properly The first column is working but second column is not working , I added the scripts in the html page , but my problem not solved I added this scripts <script type="text/javascript" src="{% static 'smart-selects/admin/js/chainedfk.js' %}"></script> <script type="text/javascript" src="{% static 'smart-selects/admin/js/chainedm2m.js' %}"></script> <script type="text/javascript" src="{% static 'smart-selects/admin/js/bindfields.js' %}"></script> in url I added urlpatterns = [ path('admin/', admin.site.urls), path('', include('hospitalapp.urls')), path(r'^chaining/', include('smart_selects.urls')), ] -
How dynamically change video resolution on a web-site
I have my own video hosting created on django, and I want to add the ability to change the quality of the video. What is the best way to do this? I save multiple copies of videos with different resolutions, and when users change the quality, I change the displayed video, but how can I dynamically change the resolution and not store many copies? -
choose one value multiple time in many to many field of Django
i'm creating a Ecommerce website & i have a order item model which has many to many relationship with product model so customer can add products to their order. everything is okay with my system but the customer can't order one product twice or more since Many to many field choose an option once! how can i add one value twice in a many to many field?? also if you think there's a better way rather than using this system & many to many field, you can suggest! #my_views_py from django.db import models from django.contrib.auth.models import User class Customer(models.Model): user = models.OneToOneField(User,null=True,blank=True,on_delete=models.SET_NULL) name = models.CharField(max_length=100,null=True) email = models.CharField(max_length=100,null=True) def __str__(self): return self.name or str(self.id) class Product(models.Model): title = models.CharField(max_length=200) price = models.FloatField() image = models.ImageField(upload_to='static/images') def __str__(self): return self.title class Order(models.Model): customer = models.ForeignKey(Customer,on_delete=models.SET_NULL,blank=True,null=True) date = models.DateField(auto_now_add=True,blank=True) complete = models.BooleanField(default=False,null=True,blank=False) transaction_id = models.CharField(max_length=200,null=True,blank=True) def __str__(self): return str(self.id) class OrderItem(models.Model): product = models.ManyToManyField(Product,blank=True) order = models.ForeignKey(Order,on_delete=models.SET_NULL,null=True,blank=True) date = models.DateField(auto_now_add=True) def __str__(self): return str(self.order)