Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AssertionError: Cannot filter a query once a slice has been taken. Python Django
When trying to check the form of validity if _dict['form'].is_valid()gives an error message AssertionError: Cannot filter a query once a slice has been taken. I understand that the error in phone = ChoiceTxtField(queryset=Clients.objects.order_by('-phone')[:1]) in forms.py. How to avoid this error when adding a form? some.py def checkRelatedAddForm(self, **kwargs): context= {} request_post = kwargs['request_post'] related_form = RelatedAddForm(request_post, prefix=self.prefix) related_form.prefix = self.prefix context['form'] = related_form if related_form.is_valid(): #some code else: #some code 2 #ERROR AssertionError: Cannot filter a query once a slice has been taken return context forms.py class ListTextWidget(forms.Select): template_name = 'include/_forms_clients_datalist.html' def format_value(self, value): if value == '' or value is None: return '' if self.is_localized: return formats.localize_input(value) return str(value) class ChoiceTxtField(forms.ModelChoiceField): widget=ListTextWidget() class RelatedAddForm(forms.ModelForm): phone = ChoiceTxtField(queryset=Clients.objects.order_by('-phone')[:1]) # class Meta: model = Clients fields = ['name', 'phone'] widgets = { 'name': forms.TextInput(attrs={'class': 'form-control', 'autocomplete': 'off'}), } include/_forms_clients_datalist.html {% block javascript %} <script> $(document).ready(function () { $('#ajax_phone_{{ widget.name }}').keyup(function () { // create an AJAX call $.ajax({ data: $(this).serialize(), // get the form data url: "{% url 'ajax_request' %}?related=clients&data={{ widget.name }}", // on success success: function (response) { if (response.is_exist == true) { $("#ajax-{{ widget.name }}").text(response.is_taken.name); var dataList = document.getElementById('{{ widget.name }}'); var input = document.getElementById('ajax_phone_{{ widget.name }}'); var request … -
Accessing nested field from Queryset in Django
so I have 4 models class User(models.Model): userID = models.CharField(pk = True) ...... class Producer(models.Model): userID = models.OneToOneField('Users.User',on_delete=CASCADE,primary_key=True) ..... class Buyer(models.Model): userID = models.OneToOneField('Users.User',on_delete=CASCADE,primary_key=True) ..... class Inventory(models.Model): item_id = models.UUIDField(primary_key=True,auto_created=True,default=uuid.uuid4) producerID = models.ForeignKey('Producers.Producer',on_delete=CASCADE) ..... class Cart(models.Model): userID = models.OneToOneField(Buyer, on_delete = CASCADE,primary_key = True) last_updated = models.DateTimeField(auto_now = True) class Cart_Item(models.Model): cart_item_id = models.UUIDField(primary_key=True,auto_created=True,default= uuid.uuid4) item_id = models.ForeignKey('Inventory.Inventory', on_delete= SET_NULL,null=True) userID = models.ForeignKey(Cart,on_delete=CASCADE) ...... I then have a post-only view which processes all cart Items in order to create an order as follows class PlaceOrderView(generics.CreateAPIView): def post(self, request, *args, **kwargs): user = request.user cart = Cart_Item.objects.select_for_update().filter(userID = user).order_by('item_id__producerID') order = {'producer':'', 'items': [] } for item in cart: if order['producer'] == item.values('item_id.producerID'): order['items'].append(item) else: self.placeOrder(order) order['producer'] = item.values('item_id.producerID') order['items'] = [] order['items'].append(item) def placeOrder(self,order): with transaction.atomic(): #Business logic on order. What Im trying to do is to group all cart Items by items owned by specific producers, and then place an order for that group of cart Items. Where I am having trouble is in accessing the nested field "producerID" of cart Item, which needs to be done in order to group all of my cart Items. My placeOrder method, uses the cartItem object and so they are passed directly … -
Passing values into nested for loops in django
I am getting hung up between tutorials and documentation for backwards relationships. I think my issue is that I'm not passing the right information from my view into the template, but I'm unsure how to address it. I want to be able to pass all of the "lift" values from the LiftSets object to thier specific Session. My for loop for Sessions (or total_workouts) is working, but I cannot get anything to populate the nested for. # views.py def workout(request): total_workouts = Session.objects.all() total_sets1 = LiftSet.objects.all() context = { 'total_workouts' : total_workouts, 'total_sets1' : total_sets1, } return render(request, 'blog/workout.html', context=context) # workout.html {% for workout in total_workouts %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ workout.author }}</a> <small class="text-muted">{{ workout.date_posted|date:"F d Y" }}</small> </div> <h2><a class="article-title" href="">{{ workout.name }}</a></h2> <p class="article-content"> test {% for child in total_sets1.session_set.all %} {{ child.lift }} {% endfor %} </p> </div> </article> {% endfor %} Foreign key in LiftSet to associate to Session. class Session(models.Model): name = models.CharField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name class LiftSet(models.Model): lift_options = ( ('S', 'Squat'), ('B', 'Bench'), ('O', 'OHP'), ('R', 'Row'), ) lift = models.CharField( max_length=1, choices=lift_options, blank=True, default='m', help_text='What Lift', … -
how do we create server side templates with django
let's take the example of Fiverr to explain what is basically my question. When an offer is generated on Fiverr, they say today is 5% off and a pop/modal is seen. you press cross it closes. what I want to know is this an example of server-side templates? and how to get started with server-side templates with Django -
Django AND query using Q objects
Given I have a Product model and a one-to-many ProductTag model. class Product(models.Model): [...] class ProductTag(models.Model): product = models.ForeignKey(Product) tag_value = models.CharField() [...] If I have 3 products with some tags: ProductA [TagA] ProductB [TagB] ProductC [TagB/TagC] I want to dynamically query "products" with some tags. This query returns just "ProductA" (as expected). Product.objects.filter(Q(producttag__tag_value="TagA")) This query returns all 3 products (as expected). Product.objects.filter( Q(producttag__tag_value="TagA") | Q(producttag__tag_value="TagB") ) I would expect the following query to return just "ProductC" Product.objects.filter( Q(producttag__tag_value="TagB") & Q(producttag__tag_value="TagC") ) But I get an empty queryset. Why does query #3 not work? Using __in query also returns wrong results (as expected) Product.objects.filter(producttag__tag_value__in=["TagB", "TagC"]) The above query returns both ProductB / ProductC. -
How to integrate OpenCV webcam with Django and React?
I have a barcode reader which I implemented by using opensource Dynamsoft API and OpenCV. Now I need to integrate it with Django and display on my website in React. I have no idea how to do that, I tried passing the code to my views.py but don't know what I should do next. Here is my code for barcode reading: import cv2 from dbr import * import time reader = BarcodeReader() def text_results_callback_func(frame_id, t_results, user_data): print(frame_id) for result in t_results: text_result = TextResult(result) print("Barcode Format : ") print(text_result.barcode_format_string) print("Barcode Text : ") print(text_result.barcode_text) print("Exception : ") print(text_result.exception) print("-------------") def get_time(): localtime = time.localtime() capturetime = time.strftime("%Y%m%d%H%M%S", localtime) return capturetime def read_barcode(): video_width = 0 video_height = 0 vc = cv2.VideoCapture(0) video_width = vc.get(cv2.CAP_PROP_FRAME_WIDTH) video_height = vc.get(cv2.CAP_PROP_FRAME_HEIGHT) vc.set(3, video_width) vc.set(4, video_height) stride = 0 if vc.isOpened(): rval, frame = vc.read() stride = frame.strides[0] else: return windowName = "Barcode Reader" parameters = reader.init_frame_decoding_parameters() parameters.max_queue_length = 30 parameters.max_result_queue_length = 30 parameters.width = video_width parameters.height = video_height parameters.stride = stride parameters.image_pixel_format = EnumImagePixelFormat.IPF_RGB_888 parameters.region_top = 0 parameters.region_bottom = 100 parameters.region_left = 0 parameters.region_right = 100 parameters.region_measured_by_percentage = 1 parameters.threshold = 0.01 parameters.fps = 0 parameters.auto_filter = 1 reader.start_video_mode(parameters, text_results_callback_func) while True: cv2.imshow(windowName, frame) … -
How to Submit and Retrieve data in one view in Django?
I have a little confusion in my app. I have html page in which I have added one form (form data submitting) and one table (to display the submitted data). For which I have a view that submit and retrieve the data at the same time but unfortunately, data is successfully storing in the table but in retrieving time, it gives me the error which is mentioned below. Error NoReverseMatch at /staff/add_staff_type Reverse for 'student_profile' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['student/profile/(?P[0-9]+)$'] Views.py def add_staff_type(request): if request.method == 'POST': designation = request.POST.get('designation') salary = request.POST.get('salary') datetime = request.POST.get('datetime') add_staff_type = staff_type.objects.create(designation=designation, salary=salary, datetime=datetime) add_staff_type.save() messages.info(request, "Staff type has been Added.") return redirect('add_staff_type') else: #fetching records from the database table display_staff_type = staff_type.objects.all() return render(request, 'staff/staff_type.html',{'display_staff_type':display_staff_type}) urls.py urlpatterns = [ path("", views.index, name="index"), path("student/Add_Student", views.Add_Student, name="Add_Student"), path("student/display_students", views.Display_Student, name="display_students"), path("student/edit/<int:id>", views.student_edit, name="student_edit"), path("student/update/<int:id>", views.student_update, name="student_update"), path("student/profile/<int:id>", views.student_profile, name="student_profile"), path("student/delete/<int:id>", views.student_delete, name="student_delete"), #below url is for staff_type on which i am currently workin path("staff/add_staff_type", views.add_staff_type, name="add_staff_type"), ] staff_type.html <div class="card"> <div class="card-header"> <h3 class="card-title">Add Staff Type</h3> </div> <!-- /.card-header --> <!-- form start --> <form class="needs-validation" action="add_staff_type" method="POST" enctype="multipart/form-data" novalidate > {% csrf_token %} <div class="card-body"> <div class="form-row"> … -
pass values from one form to another and save in django
i have 2 Forms , In the first form i want to put some values and then move to second form passing values from first form , add few values in second form and save all, so far what im saving is empty rows and is duplicated (using modals to display forms if that helps) forms.py class AddCityForm(forms.Form): duration = forms.ChoiceField(widget=forms.RadioSelect(attrs={ 'style': 'background-color: #FAF9F9', 'class': 'mb-3, form-check-inline'}), choices=DURATION_CHOICES) country = forms.ChoiceField(widget=forms.RadioSelect(attrs={ 'style': 'background-color: #FAF9F9', 'class': 'mb-3, form-check-inline'}), choices=CITY_CHOICE) class AddCityFormSec(forms.ModelForm): something = forms.CharField(widget=forms.TextInput(attrs={ 'style': 'background-color: #FAF9F9', 'class': 'mb-3'})) class Meta: model = Cities exclude = ['city', 'duration', 'something'] views.py def add_city(request): data = dict() if request.method == 'POST': form = AddCityForm(request.POST) city = request.POST.get('country') duration = request.POST.get('duration') something = request.POST.get('something') if form.is_valid(): form = form.save(commit=False) form.city = city form.duration = duration form.something = something form = form.save() data['form_is_valid'] = True else: data['form_is_valid'] = False else: form = AddCityForm() context = dict(form=form) data['html_form'] = render_to_string('cites/modal_1.html', context, request=request) return JsonResponse(data) def add_city_2(request): data = dict() if request.method == 'POST': form = AddCityFormSec(request.POST) city = request.POST.get('country') duration = request.POST.get('duration') something = request.POST.get('something') if form.is_valid(): form.city = city form.duration = duration form.something = something form = form.save() data['form_is_valid'] = True else: data['form_is_valid'] = False … -
How do I search for a certain item in multiple models django?
I am new to django and I am trying to build web site for my friend how makes handmade lamps. My problem is that I have 3 different models that contains different types of lamps, and I want to get access to certain picture in any of this 3 models and display a picture and description on the other page,but it shows only some pictures from first model and for others throws an error. this is my html and views.py codes. <div class="image-selected__lamps"> <a href="{% url 'project_detail' q.pk%}"> <img src="{{q.image.url }}"> </a> enter image description here def project_detail(request, pk): project = (LampType1.objects.get(pk=pk), LampType2.objects.get(pk=pk), LampType3.objects.get(pk=pk)) context = { 'project': project, } return render(request, 'project_detail.html', context) -
how do i add multiple models in one django Model field using ForeignKey
I want to pass gamingpc and pcComponent on OrderItem item field how can I do that class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey( gamingpc, on_delete=models.CASCADE, blank=True, null=True) product = models.ForeignKey( PcComponent, on_delete=models.CASCADE, blank=True, null=True) -
Django context processor not sending data
I created context_processors.py in my main app folder and am using the following code in this file: from notifications.models import Notification def get_notifications(request): print("In get notifs") notifications = "" try: user = request.user notifications = Notification.objects.filter(user=user) except: pass return {'notifications': notifications} Defined this in my settings.py as: TEMPLATE_CONTEXT_PROCESSORS = ('<app_name>.context_processors.get_notifications',) (I put the name of the application in <app_name>) I am then using the context preprocessor in a navbar partial: <div class="dropdown-menu" id="notification-dropdown"> {% if notifications %} Notifications! {% else %} No notifications {% endif %} </div> But I have noticed that the notifications in the navbar partial is always empty. I also haven't seen an output from the print statement that I defined in the context_processors.py -
TemplateSyntaxError while including javascript code in template
I am trying to follow this site to create a multi step form in my django app, from this code {% render_field form.car_make class="form-control" placeholder=form.car_make.label oninput="this.className = ''" %} i am getting the following error TemplateSyntaxError at /newcar1/ Could not parse the remainder: '"this.className = '' from '"this.className = '' I tried escaping the js thus {% render_field form.car_make class="form-control" placeholder=form.car_make.label oninput="this.className = ''"|escapejs %} but still getting the same error. Any help will be greatly appreciated. -
Django. How can I get data for an authenticated user and display it in the template?
I have subscriber and subscription models, how to display data from the Subscription model (respectively, the end_date, start_date, subscription_status fields), through the UserMembership model, for an authorized user? I need the {{subscription.end_date}}, {{subscription.start_date}} and {{subscription.subscription_status}} data for an authorized user. models.py class UserMembership(models.Model): slug = AutoSlugField(populate_from=['user', 'membership', 'created']) user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) membership = models.ForeignKey( Membership, on_delete=models.SET_NULL, null=True) created = models.DateTimeField(auto_now_add=True, verbose_name="Время создания") class Subscription(models.Model): slug = AutoSlugField(populate_from=['user_membership', 'created']) user_membership = models.ForeignKey( UserMembership, on_delete=models.CASCADE, verbose_name="Пользователь") subscription_status = models.CharField( choices=MEMBERSHIP_CHOICES, default='НЕ СПЛАЧЕНА', max_length=30, verbose_name="Название статуса") start_date = models.DateTimeField(auto_now=False, null=True, verbose_name="Дата начала подписки") end_date = models.DateTimeField(blank=True, null=True, verbose_name="Дата окончания подписки") active = models.BooleanField(default=False, verbose_name="Активный") created = models.DateTimeField(auto_now_add=True, verbose_name="Время создания") -
Receiving [Errno 111] Connect call failed ('127.0.0.1', 6379) using Django via Heroku
I'm running Django in a production environment and my websockets will connect but won't send any data. I do however receive [Errno 111] Connect call failed ('127.0.0.1', 6379) as an error. I heard that it's because of my settings.py, but so far I haven't found a solid fix. Here's what I have so far. Setup Procfile: web: daphne API.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: python manage.py runworker background -v2 settings.py: CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("127.0.0.1", 6379)], }, }, } asgi.py: application = ProtocolTypeRouter({ 'http': django_asgi_app, 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( [ url('timer', TestConsumer.as_asgi()), ] ) ) ), 'channel': ChannelNameRouter({ 'background': BackgroundConsumer.as_asgi() }) }) Redis Addon for Heroku was added, but I didn't take any further steps to run it. It does however, display that its "Available" in its settings. Problem/Logs The output is a [Errno 111] Connect call failed ('127.0.0.1', 6379) error when signaling the Redis server. Websockets dont seem to do anything other than simply connect. Logs: ConnectionRefusedError at /API/1/ [Errno 111] Connect call failed ('127.0.0.1', 6379) Request Method: PUT Request URL: http://example.herokuapp.com/API/1/ Django Version: 3.2.3 Exception Type: ConnectionRefusedError Exception Value: [Errno 111] Connect call failed ('127.0.0.1', 6379) Exception Location: /app/.heroku/python/lib/python3.8/asyncio/selector_events.py, line 528, … -
django.urls.exceptions.NoReverseMatch: Reverse for 'quiz' not found. 'quiz' is not a valid view function or pattern name
I am getting this error even though everything is all right. Help me debug this problem. This is my views.py file : def definition(request): return render(request, 'search/definition.html') def facts(request): return render(request, 'search/facts.html') def news(request): return render(request, 'search/news.html') This is my urls.py file : urlpatterns = [ path('', views.home, name='rios-home'), path('rios-search/', views.search_content, name='rios-search'), path('search/', views.search, name='search'), path('autosuggest/', views.autosuggest, name='autosuggest'), path('discover/', views.discover, name='discover'), path('content/', views.content, name='content'), path('about-us/', views.about_us, name='about-us'), path('definition/', views.definition, name='definition'), path('facts/', views.facts, name='facts'), path('news/', views.news, name='news'), ] And Finally this is my html file : <div class="ctg"> <a href="{% url 'definition' %}" class="ctg-option"><p>definition</p></a> <a href="{% url 'facts' %}" class="ctg-option"><p>facts</p></a> <a href="{% url 'news' %}" class="ctg-option"><p>news</p></a> </div> I had previously written quiz instead of facts but it's not written now anywhere else. So I am bewildered, why I am still getting this error -
Django Heroku: Can access file from Model, but not from media folder
I don't get how this is working. I have a django project setup on Heroku with this model: class MyModel(models.Model): csv = models.FileField(upload_to='csvs') I'm using Whitenoise for staticfiles, but nothing for MEDIA uploads. I have my MEDIA_ROOT and MEDIA_URL set in django settings in the most common way: # Settings MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = '/media/' # urls.py urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The part I don't understand is about how, after I make an instance of my model through a form and upload a file, I'm able to work with the file's data when I get it from an instance of the model like so: >>> csv = MyModel.objects.first().csv >>> do_something_with_csv_file_data(csv) # How on earth is this working and it works with that csv as if it exists. However, if I go to the url myapp.herokuapp.com/media/csvs/asdf.csv I get a 404 error. It doesn't exist and I'm unable to download it like I'm able to locally on my computer (DEBUG=True on local, DEBUG=False on production of course). Again, I don't have S3 or anything setup for this project yet. If I ls in heroku bash, there is no media file, so it's understandable why I get a 404 error … -
How can I check if this instance initing from database or it is new object
I have django model of a Task. In my website Tasks can be repeated and not repeated. So I override init method in this way: def __init__(self, *args, **kwargs): """Init new Task :param period - timedelta object. How often should task be repeated :param repeated - if true task will be repeated :param end_date - datetime until which tasks will be repeated or it will be repeated for 10 years """ if not self.from_database() # I don't now how to do it if kwargs.get("repeated"): period = kwargs["period"] end_date = kwargs["end_date"] or kwargs["date_time"] + TEN_YEARS base_task = self date = base_task.date_time + period with transaction.atomic(): while date <= end_date: base_task.clone_task(date) date += period try: del kwargs["repeated"] del kwargs["period"] del kwargs["end_date"] except KeyError: pass super().__init__(*args, **kwargs) But i have problem. How can I check if this instance initing from database or it is new object. -
How long does it take for a Djoser access token until expire?
So Djoser JWT provided an access token when you login, how long until that token expires? -
how to save custom ModelForm fields in django
i have custom fields in ModelForm and there is no any values on save. im just confuse what to use in view.py to save with data form.py class AddCityForm(forms.ModelForm): duration = forms.ChoiceField(widget=forms.RadioSelect(attrs={ 'style': 'background-color: #FAF9F9', 'class': 'mb-3, form-check-inline'}), choices=DURATION_CHOICES) country = forms.ChoiceField(widget=forms.RadioSelect(attrs={ 'style': 'background-color: #FAF9F9', 'class': 'mb-3, form-check-inline'}), choices=CITY_CHOICE) something = forms.CharField(widget=forms.TextInput(attrs={ 'style': 'background-color: #FAF9F9', 'class': 'mb-3'})) class Meta: model = Cities exclude = ['city', 'duration', 'something'] view.py def add_city(request): data = dict() if request.method == 'POST': form = AddCityForm(request.POST) if form.is_valid(): form = form.save(commit=False) form.city = request.POST.get('country') form.duration = request.POST.get('dur') form.something = request.POST.get('something') form = form.save() messages.success(request, f'Test for Added Successfully') data['form_is_valid'] = True else: data['form_is_valid'] = False else: form = AddCityForm() context = dict(form=form) data['html_form'] = render_to_string('cites/modal_1.html', context, request=request) return JsonResponse(data) can any one help with this ? -
Django with Celery
How to periodically say every 24 hours delete a user who hasn't registered their email. I'm kind of confused how to start. I already pip installed it and put it in my installed_apps but what do I do now. Every tutorial I'm watching is just confusing me even more. Can anyone help? -
API views dealing with the user model is too slow (I have a custom user model)
I have this Modelviewset for my custom user model. Any API calls to this views takes a really long time that I see this thing called "(Broken Pipe)" something. It eventually does load, but my question is why is it so slow? I initially thought it might be because I use the get_user_model() function that django provides to import the model, and that function perhaps takes time. So, then I changed to the typical way of importing a model from the app itself. But even after that, any API calls are too slow. Anyone to enlighten me?? -
I can replace a '...' value to a parameter in my function's input in django-view
I'm working on a django project. In one of my views, I have a function named "glassnode". It needs a few input data, but I replace the goode ones with ... . U can see in code below: def glassnode(endpoint, ...): response = req.get( f'https://api.glassnode.com{endpoint}', { ... }, df = response.json() return df In the working version of my code endpoint fill in this way: farray2 = glassnode('/v1/metrics/market/price_usd_close', ...) But I need to enter the endpoint from the django-url. It comes to me in this way. path('charts/drawchart/v1/metrics/<str:category>/<str:detail>/', charts.views.drawchart, name='drawchart'), So I made my url in this way: def drawchart(request, category, detail): userendpoint = '/v1/metrics/'+category+'/'+detail farray1 = glassnode(userendpoint,... ) ... And it's not work! :((( the page rendered with this error: JSONDecodeError at /charts/drawchart/v1/metrics/addresses/receiving_from_exchanges_count/ -
Python. Django. An Error "No file was submitted. Check the encoding type on the form" with UpdateView class
I new with Django. I hope you could help me with this error "No file was submitted. Check the encoding type on the form". I've read several questions on stackoverflow, but there was problems with absence of "save()" in function in views.py, or absence of method "post", or absence of "csrf_token" in HTML. But I use UpdateView class and method "post" and "csrf_token" are included in HTML file. I have no any idea what the problem is. This is a blog-service with the function of adding/ updating/ deleting cities and trains. I use CreateView/ UpdateView/ DeleteView classes. Information regarding to cities and trains is stored in linked tables. All classes in the "cities" app work without problems, the same classes copied to the "trains" app don't work for creating and changing data through the form on the site. It raise an error right on the page: "Not a single file was sent. Check the encoding type of the form". At the same time, the deletion works correctly on the site. And create/ update/ delete work correctly through the admin panel. The corresponding models and forms have been created for the "trains" app. Both apps are registered in settings.py. Please tell … -
How to add watermark to video file while saving using django
I manage to add watermark, but when i save it, it saves without watermark. I need to save with watermark in media, insted of common saving video without watermark. Here is my MODEL.py class Video(models.Model): title = models.CharField(max_length=100) slug = AutoSlugField(populate_from='title') photo = models.ImageField(upload_to='photo/%Y/%m/%d') video_uploaded = models.FileField(upload_to='video/%Y/%m/%d',blank=True,null=True) here is my view.py def add_video(request): if request.method == "POST": form = VideoUploaderForm( data=request.POST, files=request.FILES, ) if form.is_valid(): obj = form.save(commit=False) vid = request.FILES['video_uploaded'] clip = VideoFileClip(vid.temporary_file_path()) # watermark video = VideoFileClip(clip.filename) logo = (ImageClip('faiklogo.png') .set_duration(video.duration) .resize(height=50) .margin(right=8, top=8, opacity=0) .set_pos(("center", "bottom"))) final_ = CompositeVideoClip([video, logo]) final_.write_videofile('videwithwatermark.mp4') obj.save() else: form=VideoUploaderForm() return render(request, 'firstapp/add_video.html', {"foenter code hererm": form}) here is my form.py class VideoUploaderForm(forms.ModelForm): class Meta: model = Video fields = '__all__' -
Django database querysets with javascript drop down
Hello i have a FAQ model..and i have crated three FAQs.. html: <div class="accordion accordion-solid accordion-panel accordion-svg-toggle mb-10"> <!--begin::Item--> {% for i in faqs %} <div class="card p-6 header-click" id="header" data-idd="{{ i.id }}"> <!--begin::Header--> <div class="card-header"> <div class="card-title font-size-h4 text-dark"> <div class="card-label">{{ i.ques }}</div> <span class="svg-icon svg-icon-primary"> <!--begin::Svg Icon | path:assets/media/svg/icons/Navigation/Angle-double-right.svg--> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24px" height="24px" viewBox="0 0 24 24" version="1.1"> <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"> <polygon points="0 0 24 0 24 24 0 24" /> <path d="M12.2928955,6.70710318 C11.9023712,6.31657888 11.9023712,5.68341391 12.2928955,5.29288961 C12.6834198,4.90236532 13.3165848,4.90236532 13.7071091,5.29288961 L19.7071091,11.2928896 C20.085688,11.6714686 20.0989336,12.281055 19.7371564,12.675721 L14.2371564,18.675721 C13.863964,19.08284 13.2313966,19.1103429 12.8242777,18.7371505 C12.4171587,18.3639581 12.3896557,17.7313908 12.7628481,17.3242718 L17.6158645,12.0300721 L12.2928955,6.70710318 Z" fill="#000000" fill-rule="nonzero" /> <path d="M3.70710678,15.7071068 C3.31658249,16.0976311 2.68341751,16.0976311 2.29289322,15.7071068 C1.90236893,15.3165825 1.90236893,14.6834175 2.29289322,14.2928932 L8.29289322,8.29289322 C8.67147216,7.91431428 9.28105859,7.90106866 9.67572463,8.26284586 L15.6757246,13.7628459 C16.0828436,14.1360383 16.1103465,14.7686056 15.7371541,15.1757246 C15.3639617,15.5828436 14.7313944,15.6103465 14.3242754,15.2371541 L9.03007575,10.3841378 L3.70710678,15.7071068 Z" fill="#000000" fill-rule="nonzero" opacity="0.3" transform="translate(9.000003, 11.999999) rotate(-270.000000) translate(-9.000003, -11.999999)" /> </g> </svg> <!--end::Svg Icon--> </span> </div> </div> <!--end::Header--> <!--begin::Body--> <div class="hide-ans" id="{{ i.id }}" style="display: none;"> <div class="card-body pt-3 font-size-h6 font-weight-normal text-dark-50" data-id="{{ i.id }}">{{ i.ans }}</div> </div> <!--end::Body--> </div> {% endfor %} <!--end::Item--> </div> now this is showing me my three faqs which is perfect but the problem is i want them to hide the answers which i did with display =none property...and i have created a …