Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django debug toolbar not showing view class name
I am using a django-debug-toolbar==3.4.0 with Django==4.0.5. Everything works except I see this on the debug toolbar: The expected string should be the class name: DashboardView not "backend_base.views.view". Tha class itself is very simple: class DashboardView(LoginRequiredMixin, NavBarMixin, TemplateView): template_name = 'dashboard.html' In the old version of the same project the result was exactly the classname. What am I missing? -
drf_yasg @swagger_auto_schema not showing the required parameters for POST Request
I am using django-yasg to create an api documentation. But no parameters are showing in the documentation to create post request. Following are my codes: After that in swagger api, no parameters are showing for post request to create the event model.py class Events(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(EventCategory, on_delete=models.CASCADE) name = models.CharField(max_length=250, null=True) posted_at = models.DateTimeField(null=True, auto_now=True) location = models.CharField(max_length=100, null=True) banner = models.ImageField(default='avatar.jpg', upload_to='Banner_Images') start_date = models.DateField( auto_now=False, auto_now_add=False, blank=True, null=True) end_date = models.DateField( auto_now=False, auto_now_add=False, blank=True, null=True) description = models.TextField(max_length=2000, null=True) completed = models.BooleanField(default=False) def __str__(self): return f'{self.name}' class Meta: verbose_name_plural = "Events" serializers.py class EventSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True, many=False) category = EventCategorySerializer(read_only=True, many=False) class Meta: model = Events fields = '__all__' views.py @api_view(['POST']) @permission_classes([IsAuthenticated]) @user_is_organization @swagger_auto_schema( request_body=EventSerializer ) def registerEvent(request): """ To Register an events, you must be an organization """ data = request.data print("==================") print(data) print("==================") try: Event = Events.objects.create( user = request.user, category=EventCategory.objects.get(category=data['category']), name=data['name'], location=data['location'], start_date=data['start_date'], end_date=data['end_date'], description=data['description'], completed=data['completed'], ) serializer = EventSerializer(Event, many=False) Event = Events.objects.get(id=serializer.data['id']) Event.banner = request.FILES.get('banner') Event.save() serializer = EventSerializer(Event, many=False) return Response(serializer.data) except: message = {'detail': 'Event with this content already exists'} return Response(message, status=status.HTTP_400_BAD_REQUEST) -
I Want to get 2 types of Events, that are, Past Events and Future Events from my Events Model in a Debating Society Website made using Django
I have made a Website for the Debating Society of our College using Django. I would like to have 2 types of events Past and Upcoming (Future) according to the date_of_competition, i.e., if the date and time of competition is past current date and time then return it in past events, and if the date and time of competition is in future of the current date and time then return it in future events Here are my views.py file and models.py file for events models.py from django.db import models class Format(models.Model): format_name = models.CharField(max_length=100, null=False, unique=True) def __str__(self): return self.format_name class Organiser(models.Model): organiser_name = models.CharField(max_length=140, null=False, unique=True) def __str__(self): return self.organiser_name class Event(models.Model): banner_image = models.ImageField(upload_to="events") event_name = models.CharField(max_length=150, null=False) organiser_of_event = models.ForeignKey(Organiser, on_delete=models.CASCADE) format_of_event = models.ForeignKey(Format, on_delete=models.CASCADE) date_of_event = models.DateTimeField(auto_now_add=False) registration_fees = models.IntegerField(default=0, help_text="Enter Registration Fees For The Event in Rupees") details = models.TextField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.event_name view.py from django.shortcuts import render from .models import Event # Create your views here. def events(request): context = { 'title': 'Events', 'events': Event.objects.all() } return render(request, 'main/Events.html', context) What logic should be written in order to get both future and past events from my … -
java.lang.ClassNotFoundException: solr.LatLonType when starting solr with a schema from django build_solr_schema
I want to connect a search functionality to Django. I use django-haystack and solr. with a newly created Solr core I get the following error when starting Solr with a new schema.xml generated from python manage.py build_solr_schema Caused by: java.lang.ClassNotFoundException: solr.LatLonType at java.net.URLClassLoader.findClass(URLClassLoader.java:445) ~[?:?] at java.lang.ClassLoader.loadClass(ClassLoader.java:588) ~[?:?] at java.net.FactoryURLClassLoader.loadClass(URLClassLoader.java:872) ~[?:?] at java.lang.ClassLoader.loadClass(ClassLoader.java:521) ~[?:?] at java.lang.Class.forName0(Native Method) ~[?:?] at java.lang.Class.forName(Class.java:488) ~[?:?] at java.lang.Class.forName(Class.java:467) ~[?:?] at org.apache.solr.core.SolrResourceLoader.findClass(SolrResourceLoader.java:527) ~[?:?] at org.apache.solr.core.SolrResourceLoader.newInstance(SolrResourceLoader.java:604) ~[?:?] at org.apache.solr.core.SolrResourceLoader.newInstance(SolrResourceLoader.java:598) ~[?:?] at org.apache.solr.schema.FieldTypePluginLoader.create(FieldTypePluginLoader.java:74) ~[?:?] at org.apache.solr.schema.FieldTypePluginLoader.create(FieldTypePluginLoader.java:43) ~[?:?] at org.apache.solr.util.plugin.AbstractPluginLoader.load(AbstractPluginLoader.java:144) ~[?:?] at org.apache.solr.schema.IndexSchema.readSchema(IndexSchema.java:531) ~[?:?] at org.apache.solr.schema.IndexSchema.<init>(IndexSchema.java:188) ~[?:?] at org.apache.solr.schema.ManagedIndexSchema.<init>(ManagedIndexSchema.java:119) ~[?:?] at org.apache.solr.schema.ManagedIndexSchemaFactory.create(ManagedIndexSchemaFactory.java:279) ~[?:?] at org.apache.solr.schema.ManagedIndexSchemaFactory.create(ManagedIndexSchemaFactory.java:51) ~[?:?] at org.apache.solr.core.ConfigSetService.createIndexSchema(ConfigSetService.java:342) ~[?:?] at org.apache.solr.core.ConfigSetService.lambda$loadConfigSet$0(ConfigSetService.java:253) ~[?:?] at org.apache.solr.core.ConfigSet.<init>(ConfigSet.java:49) ~[?:?] at org.apache.solr.core.ConfigSetService.loadConfigSet(ConfigSetService.java:249) ~[?:?] at org.apache.solr.core.CoreContainer.createFromDescriptor(CoreContainer.java:1550) ~[?:?] at org.apache.solr.core.CoreContainer.lambda$load$10(CoreContainer.java:950) ~[?:?] how can i fix my schema.xml? apache solr 9.0 django 4.0 -
Stripe payment intent throw invalid integer
I have been trying to generating stripe payment intent but I see this error of invalid Integer Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/asgiref/sync.py", line 472, in thread_handler raise exc_info[1] File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 42, in inner response = await get_response(request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 253, in _get_response_async response = await wrapped_callback( File "/usr/local/lib/python3.8/site-packages/asgiref/sync.py", line 435, in __call__ ret = await asyncio.wait_for(future, timeout=None) File "/usr/local/lib/python3.8/asyncio/tasks.py", line 455, in wait_for return await fut File "/usr/local/lib/python3.8/concurrent/futures/thread.py", line 57, in run result = self.fn(*self.args, **self.kwargs) File "/usr/local/lib/python3.8/site-packages/asgiref/sync.py", line 476, in thread_handler return func(*args, **kwargs) File "/usr/local/lib/python3.8/contextlib.py", line 75, in inner return func(*args, **kwds) File "/usr/local/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/generic/base.py", line 84, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/yacht-away/bookings/views.py", line 94, in post print(payment.create_payment_intent()) File "/yacht-away/bookings/payments.py", line 14, in create_payment_intent payment = stripe.PaymentIntent.create( File "/usr/local/lib/python3.8/site-packages/stripe/api_resources/abstract/createable_api_resource.py", line 22, in create response, api_key = requestor.request("post", url, params, headers) File "/usr/local/lib/python3.8/site-packages/stripe/api_requestor.py", line 122, in request resp = self.interpret_response(rbody, rcode, rheaders) File "/usr/local/lib/python3.8/site-packages/stripe/api_requestor.py", line 399, in interpret_response self.handle_error_response(rbody, rcode, … -
Django admin How to tract the user time-in and time-out?
I've been searching all day on how to track the users time-in and time-out of the user, I just want that if the user(employee permission) login ( in django admin) it will insert record/track same goes with if the user logout. is it possible to do it on django? -
Django DETAIL: Failing row contains (..., null)
Error - DETAIL: Failing row contains (6, 2022-06-18 09:50:32.722841+00, 2022-06-18 00:00:00+00, NE, something, something, null). I got 3 models: Patient => Hospitalization&Consults(ForeignKey=Patient), OneToMany. I know there, on "null" spot, must be the Patient ID, but I don t know how to get this ID. Models.py: class Patient(models.Model): NameandLastName = models.CharField(max_length = 50) ... class Consult(models.Model) Patient = models.ForeignKey(Patient, on_delete = models.CASCADE) simptoms = models.CharField(max_length = 50) option_pay = models.CharField(max_length = 40, choices = pay_method) ... Views.py class Consult(LoginRequiredMixin, CreateView): model = Consult template_name = 'Manage/ConsultAdd.html' form_class = forms.FromConsultAdd def form_valid(self, form): form.instance.autor = self.request.user messages.success(self.request, f"smth") return super().form_valid(form) I think I have to put smth on views, but idk what. -
How to solve Process 'ForkPoolWorker-1' pid:2133000 exited with 'signal 9 (SIGKILL)'?
I am using django, celery and xhtml2pdf to generate pdfs. Small size pdf are created but when pdf size gets larger and few images is added. I get following error. Process 'ForkPoolWorker-1' pid:2133000 exited with 'signal 9 (SIGKILL)' Can somebody help to solve this? -
Python Django unhashable type slice error while trying to paginate class based 'Category' list view
I am trying to create a 'Category' page that filters out posts by its category, everything is fine till I try to add pagination option to its class in 'views.py'. Here is the error: This is what I have in 'views.py': class CatListView(ListView): template_name = 'academy/category.html' context_object_name = 'catlist' paginate_by = 2 def get_queryset(self): content = { 'cat': self.kwargs['category'], 'posts': ContentPost.objects.filter(category__name=self.kwargs['category']) } return content def category_list(request): category = Category.objects.exclude(name='default') context = { 'category' : category, } return context and this is what I have in 'urls.py': path('academy/category/<category>/', CatListView.as_view(),name='academy-category'), I appreciate your help in advance... Thanks -
login() takes 1 positional argument but 2 were given using django
I dont know why i receiving this error login() takes 1 positional argument but 2 were given, ive just follow this tutorial that after sign-up it will login automatic https://www.csestack.org/django-sign-up-registration-form/ def login(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): print("test") user = form.save() user.refresh_from_db() user.first_name = form.cleaned_data.get('first_name') user.last_name = form.cleaned_data.get('last_name') user.contact_number = form.cleaned_data.get('contact_number') user.email = form.cleaned_data.get('email') user.save() insert = Customer( user=user, first_name=user.first_name, last_name=user.last_name, contact_number=user.contact_number, email=user.email ) insert.save() raw_password = form.cleaned_data.get('password1') users = authenticate(username=user.username, password=raw_password) login(request, users) return redirect('Homepage') else: form = SignUpForm() return render(request, 'mysite/login.html', {'form': form}) this is the traceback Traceback (most recent call last): File "C:\Users\clair\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\clair\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\clair\OneDrive\Desktop\Thesis\mysite\myapp\views.py", line 36, in login login(request, users) Exception Type: TypeError at /login/ Exception Value: login() takes 1 positional argument but 2 were given -
how to fetch latest record based on some paramter in django restframework
i am trying fetch latest record based on parameter but when use( latest(), last(), earliest(), order_by('-id')[0], latest('-id') )all this method in queryset then i got empty record, please help me out. @api_view(['GET']) @permission_classes((IsAuthenticated,)) def details(request): if request.method == 'GET': category=request.query_params.get('category') name=request.query_params.get('name') try: d=Employee.objects.filter(category=category,name=name).latest() response_data=EmployeeSerializer(d,many=True).data return JsonResponse({"message": "detail retrieval","error":False,"code":200,"results":{"totalItems":d.count(),"pageData":response_data,"totalPages":1,"currentPage":0}}, status=HTTP_200_OK) except: return JsonResponse({"message": "details not exist","error":True,"code":200,"results":{}}, status=HTTP_200_OK) -
Django - problem with writing to database
I have a problem, the urls form works but I can't see the records in url/admin, can I ask for help, thank you :D class Note(models.Model): """...""" notes = models.CharField(max_length=100, unique=True) description = models.TextField() class Meta: verbose_name = "Note" verbose_name_plural = "Notes" def __str__(self): return self.notes class NoteView(View): def get(self, request): if request.method == 'POST': textN = Note.objects.all().order_by('notes') form = NoteAddForm(request.POST) if form.is_valid(): form.save() return redirect('Files/menu') else: textN = NoteAddForm() return render(request, 'Files/note.html', {'textN': textN}) class NoteAddForm(forms.ModelForm): """New note add form""" class Meta: model = Note fields = '__all__' -
Postive and Negative Validation Check is Not Working In Django Forms
I am working this validation check in django , i have to check postiva values. I have values a,b,c,d if (a,b) also (c,d) positive value will not allowed, i wrote the code this way but do not know why is not checking the validation. I am working on django forms.py for i in range(count): a = int(self.data.get(f'runtime_set-{i}-a') or 0) b = int(self.data.get(f'runtime_set-{i}-b') or 0) c = int(self.data.get(f'runtime_set-{i}-c') or 0) d = int(self.data.get(f'runtime_set-{i}-d') or 0) if a ==b==c==d: continue if (a + b) > 0 + (c + d) > 0: raise ValidationError( "When A '{a}' , B '{b}' is postive then C '{c}' and d'{d}' positive value is not allowed ") -
Foreign key is not assigned to a model in database
I recently started learning django and was making a CRM. models.py: class Complaint(models.Model): SOURCE_CHOICES=( ('email','E-mail'), ('call','Call'), ('ticket','Ticket') ) store_name=models.CharField(max_length=20) store_contact_no=models.IntegerField(max_length=10) store_id=models.CharField(max_length=7) source=models.CharField(choices=SOURCE_CHOICES, max_length=10) agent=models.ForeignKey("Agent", null = True, blank = True, on_delete=models.SET_NULL) category=models.ForeignKey("Category", related_name="complaints", null = True, blank = True, on_delete=models.SET_NULL) description = models.TextField() customer = models.ForeignKey("Customer", null = True, blank = True, on_delete=models.SET_NULL) def __str__(self): return f"{self.store_name} {self.store_id}" class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.username forms.py class CustomerComplaintForm(forms.ModelForm): class Meta: model = Complaint fields = ( 'store_name', 'store_id', 'store_contact_no', 'description', ) views.py class CustomerComplaintCreateView(OwnerCustomerAndLoginRequiredMixin, generic.CreateView): template_name = "customercomplaint_create.html" form_class = CustomerComplaintForm def get_success_url(self): return "/complaints" def form_valid(self, form): complaint = form.save(commit=False) complaint.Customer = self.request.user.username complaint.source = 'ticket' complaint.save() return super(CustomerComplaintCreateView, self).form_valid(form) html template: {% extends "base.html" %} {% load tailwind_filters %} {% block content %} <div class="max-w-lg mx-auto"> <a class="hover:text-blue-500" href="/complaints">Go back to complaints </a> <div class="py-5 border-t border-gray-200"> <h1 class="text-4xl text-gray-800"> Create a new complaint </h1> </div> <form method='post' class="mt-5"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="w-full bg-blue-500 text-white hover:bg-blue-600 px- 3 py-2 rounded-md">Create</button> </form> </div> {% endblock content %} The problem here is that, the source field gets filled in the database with Ticket as intended. But the 'Customer' field is not populated … -
I want to get datatables checkbox data from html template to views.py in django
I have used this example (https://jsfiddle.net/snqw56dw/3182/) to get checkboxes on my html table. I am getting the selected boxes data via the datatable script but I need to send this data to views.py on submission. I have used AJAX but it seems that I have been doing something wrong. Could you please help. Javascript on html: $(document).ready(function() { var table1 = $('#pgnum').DataTable({ 'columnDefs': [ { 'targets': 0, 'checkboxes': { 'selectRow': true } } ], 'select': { 'style': 'multi' }, 'order': [[1, 'asc']] }); // Handle form submission event $('#eg').on('submit', function(e){ var arr = []; var form = this; var rows_selected = table1.column(0).checkboxes.selected(); // Iterate over all selected checkboxes $.each(rows_selected, function(index, rowId){ // Create a hidden element arr.push(rowId); }); $.ajax({ type: "POST", url: "{% url 'add_user_eng' %}", data: {arr: 'arr'}, }); }); }); urls.py url(r'^eng_edit_admin/eng_add_user', views.add_user_eng, name='add_user_eng'), views.py def add_user_eng(request): token = request.session['eng_id'] eng_id = str(token) user_list = User.objects.all() if request.method == 'POST': print("HELLO") print(request.POST.getlist('data[]')) return render(request, 'main/add_user_to_engagement.html',{'user_list':user_list}) form id="eg" I am getting an empty list even when I submit or reload the page. Any sort of help is appreciated. Thank you -
Django save on model
I just want that it will automatic compute when it save on the database class Order(models.Model): quantity = models.IntegerField(null=True, blank=True) price = models.IntegerField(null=True, blank=True) total_price = models.IntegerField(null=True, blank=True) def save(self, *args, **kwargs): self.total_price = self.price * self.quantity return (Order, self).save(*args, **kwargs) the error i received is 'tuple' object has no attribute 'save' -
Python django parallel process large amount of data
In my order models, I have around 5M dummy records, I am calculating these and pushing to another database. It is working great but very slow ! Coz, there mazzine amount of fake data. I am writing a django command to this and trying to split all the records in multiple process, al that It can finish quickly. from django.core.management.base import BaseCommand, CommandError from multiprocessing.pool import Pool from multiprocessing import Manager from order.models import Order class Command(BaseCommand): help = 'Scrape all the site parrally..' def handle(self, *args, **options): order_count = Order.objects.all().count() for ord in Order.objects.all(): calculate_n_push(ord) Can anyone advice me what could be the best way to handle this? -
How to check if the object is assigned to another object | Django
I am working on a django case like below: models.py class Room(models.Model): name = models.CharField("Room No.",max_length=200) class Meta: verbose_name_plural = "Room" def __str__(self): return self.name class Student(models.Model): name = models.CharField("name",max_length=200) father_name = models.CharField("father Name",max_length=200) cell_no = models.CharField("cell No",max_length=200) address = models.CharField("address",max_length=500) room = models.ForeignKey(Room, on_delete=models.CASCADE, null=True, blank=True, related_name='all_rooms') class Meta: verbose_name_plural = "Student" def __str__(self): return self.name views.py def room(request): allrooms= Room.objects.all() form = RoomForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() messages.success(request, "Room added successfully.") return redirect('/room') context = {'allrooms':allrooms, 'form':form} return render(request, 'room.html', context) In templates in room.html I want to show the status Vacant/Occupied based on the fact if a room is assigned to some student or not. I have the following code in template but it shows 'Vacant' status for all rooms. <table id="example1" class="table table-bordered table-striped"> <thead> <tr> <th>Room</th> <th class="text-center">Status</th> <th class="text-center">Action</th> </tr> </thead> <tbody> {% for room in allrooms %} <tr> <td>{{ room.name }}</td> <td class="text-center"> {% if room.student_set.all %} <small class="badge badge-danger">Occupied</small> {% elif not room.student.all %} <small class="badge badge-success">Vacant</small> {% endif %} </td> <td class="text-center"><a href="{% url 'updateroom' room.id %}"><i class="fas fa-edit"></i></a></td> </tr> {% endfor %} </tbody> </table> Please help someone to show he status of the room. -
Creating a nested form field or something like that
I'm not entirely sure about the correctness of the question. In fact, I doubt whether I can express exactly what I am looking for. Question: How can I create additional fields based on the previous selection before submitting the form? Let's take the number of pets and the name of the pet in our example. I want how many pet names to be entered first class UrlForm(forms.Form): INT_CHOICES = [(x, x) for x in range(11)] number_of_pets = forms.ChoiceField(choices=INT_CHOICES) and then create as many Charfield fields as the selected value based on the previous selection: #new fields as many as the number of pets pet1 = forms.CharField() pet2 = forms.CharField() Of course, the variable name issue is a separate issue. Question 2: As an alternative approach, can I create a pet name field like a tag field? As in the image: Image taken from here. The question is appropriate but a ReactJs topic. You can share the topic, title, term, article, anything that I need to look at. Thanks in advance. Edit: The pet example is purely fictional. Influenced by the image, I used this topic. -
Django - Autocomplete dropdown field amidst other fields in a form
I am trying to make 1 field in a form an autocomplete dropdown box which lists values from another model, but no success. It is a 'Create' form to feed in employees details. I am new to application developing. So finding difficult in understanding the concepts to implement. Kindly help. here is my model. class State(models.Model): StateCode = models.CharField(max_length=2) StateTIN = models.IntegerField() StateName = models.CharField(max_length=100) def __str__(self): return self.StateName class EmployeeM(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) Name = models.CharField(max_length=200) Email = models.EmailField() Contact = models.CharField(max_length=20) State = models.ForeignKey(State,on_delete=models.SET_NULL,null=True) def __str__(self): return self.Name Here is my views, #Create1 html view def create(request): form = EmployeeMForm() if request.method == 'POST': form = EmployeeMForm(request.POST) if form.is_valid(): form.save() return redirect('employeem-list') context = { 'form': form, } return render(request,'EmployeeM/create.html', context) #List States def state_list(request): states = State.objects.all() context = { 'states': states } return render(request, 'State/statelist.html', context) Here is my part of HTML codes where I am trying to make the field 'State' as dropdown box as well as searchable. {% csrf_token %} {{ form.non_field_errors }} {{ form.source }} <table border="1" cellpadding="10px"> <tr> <th>{{ form.Name.label_tag }}</th> <td> {{ form.Name.errors }} {{ form.Name }} </td> </tr> <tr> <th>{{ form.Email.label_tag }}</th> <td> {{ form.Email.errors }} {{ … -
How to provice access for specific users to view certain APIs in django rest framework
I have three APIs created by inheriting APIView class class API1View(APIView): def get(self, request): return Response("API 1 view") class API2View(APIView): def get(self, request): return Response("API 2 view") class API3View(APIView): def get(self, request): return Response("API 3 view") I have three users user1 user2 user3 I three kind of users. customer manager employee Different kind of users should have access to different APIs The Manager can only able to view the API1 and API2 The Customer can only able to view the API1 The Employee can only able to view the API3 In future, I need to able to revoke access of a certain user to certain API. Is it good to use Django Groups or is there any better ways to do it? Or is there any DRF way to do it? (I have seen DRF permissions but I'm not sure if that will work for this scenario.) -
associate vimeo with products using django
I am new to vimeo. I have a database in django that has products, in the table i have a field for video. I need to show the video in my site so i need to use vimeo (embended) but how to associate the video file from vimeo for each product? Is there an attribute where i can put product id in vimeo embendded code? {% for order in item_list %} <tr> <td>{{ forloop.counter }}</td> <td>{{ order.product.name }}</td> <td>{{ order.product.category }}</td> <td><a href="{{order.product.video_file}}">{{order.product}}</a> <br/></td> </tr> <br/><br/> {% endfor %} instead of the link for video file i need to play the vimeo video inside my site (embendded), how to do that? -
django How to pass list of data or dictionary using ajaz
i am trying to pass multiple data to my views but it works on single data if i pass list or dictionary i am getting csrf_token incorrect error $.ajax({ type: 'POST', url: '{% url "BugApp:addcomment" %}', data: $("#" + button).serialize(), cache: false, success: function (json) { if(json.status == 1){ $('<div id="" class="my-2 p-2" style="border: 1px solid grey"> \ <div class="d-flex justify-content-between">By ' + json['user'] + '<div></div>Posted: Just now!</div> \ <div>' + json['result'] + '</div> \ <hr> \ </div>').insertBefore('#' + placement); $('.commentform').trigger("reset"); }else{ window.location.href = 'http://127.0.0.1:8000/account/login' } -
Setting the correct "my_app/static/my_app/example.jpg" static tree structure in Django
According to step 4 in Django's Static Article, best practise is to set up your app's static tree structure as such: my_app/static/my_app/example.jpg ...in order to mitigate duplicate/naming issues when you later run collectstatic as two apps COULD have the same named static files. So how do I set up my app's settings and templates to allot for this kind of structure? Right now, I just have a static folder within each app, and my files inside it. I have my settings.py as such: # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = str(BASE_DIR) + "/media/" # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '/media/' # Absolute path to the directory that holds static files. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = str(BASE_DIR) + "/static/" # URL that handles the static files served from STATIC_ROOT. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' ...and my templates that import from their respective static folders looks like this: <link rel="stylesheet" href="{% static "style.css"%}" /> In order to implement what the article says, do I … -
JsPdf only get one png image element instead of all element
So i kinda confused to use jsPdf and Html2canvas. I have some page like this, https://i.stack.imgur.com/gspxL.png[1] And i need to download whole element on the page except the video. Its already work but instead of printing the whole element, it only takes the face cropped images part like this [https://i.stack.imgur.com/u10vS.png] I use jspdf with html2canvas. And here is the code for the pages <div class="container"> <a class="nav-link" href="{%url 'kepalsuan:home'%}"> <div class="logo text-center mt-1 mb-3"><img src="{% static 'images/logo1.png'%}" alt="Logo"></div> </a> <hr /> <div class="result text-center"> <div id="printedPart"> <!-- <h3>Play to see the Result!</h3> --> <h2>It Takes <span style="font-size:40px;font-weight:600;">{{ duration }}</span> seconds to detect It!</h2> <div class="hasilakhir mt-3"> {%if output == "REAL" %} <img src="{% static 'images/realstamp.png'%}" alt="real" height="100px" width="auto" style="float:left; padding-left:350px;"> <h1 id="realaccuracy" style="color:green; float:right; padding-right:400px; padding-top:20px;">{{ confidence }} %</h1> {%else%} <img src="{% static 'images/fakestamp.png'%}" alt="fake" height="100px" width="auto" style="float:left; padding-left:350px;"> <h1 id="fakeaccuracy" style="color:red; float:right;padding-right:400px;padding-top:20px;">{{ confidence }} %</h1> {%endif%} </div> <hr> <!-- <h1 class="mx-auto mt-5" style="font-weight:900;">Result</h1> --> <h3 style="margin-top:125px;">Face Cropped Frames</h3> <div id="faces_images" class="col-12 mb-2"> {% for each_image in faces_cropped_images %} <img src="{%static each_image%}" class="faces" width="auto" height="150" /> {%endfor%} </div> </div> <video height="320" width="640" id="predict-media" controls> <source src="{{MEDIA_URL}}{{original_video}}" type="video/mp4" codecs="avc1.4d002a" /> </video> </div> <div class="text-center"> <a class="btn btn-warning mt-5 btn-lg" href="javascript:downloadResult()" style="color:white;font-weight: …