Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
getting list index out of range when function is being called Django
I am trying get total here, whenever i add the new record i got the error i don't know why i got list index out of range i m calling the function in admin.py this is my model file class Buyer(models.Model): buyer_name = models.CharField(max_length=256,unique=True) def __str__(self): return self.buyer_name def buyerdebittotal(self): queryset = Buyer.objects.filter(policybuyer__buyer_id = self.id).annotate(total=Sum('policybuyer__buyerdebit',)) return queryset[0].total class Policy(models.Model): buyer = models.ForeignKey(Buyer,on_delete=models.DO_NOTHING,related_name='policybuyer') buyerdebit = models.FloatField(default=0) def get_absolute_url(self): return reverse("insurance:updatepolicy", kwargs={"id": self.id}) -
Why can't I find the Dockerfile?
I'm making a Python (Django) and MySQL project. After creating some files, I get an error when I run the command. docker-compose up -d ERROR: Cannot locate specified Dockerfile: Dockerfile Why am I getting an error when I have a Dockerfile in the current directory? MYAPP -django --__init__.py --asgi.py --settings.py --urls.py --wsgi.py -docker-compose.yml -Dockerfile -manage.py -requirement.txt -wait-for-in.sh docker-compose.yml version: '3' services: db: image: mysql:5.7 command: mysqld --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci volumes: - .:/var/www/django restart: always environment: MYSQL_ROOT_PASSWORD: django MYSQL_DATABASE: django MYSQL_USER: django MYSQL_PASSWORD: django web: build: django command: sh -c "./wait-for-it.sh db:3306; python3 manage.py runserver 0.0.0.0:8000" volumes: - .:/var/www/django ports: - "8000:8000" depends_on: - db Dockerfile FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir -p /var/www/django WORKDIR /var/www/django ADD requirements.txt /var/www/django/ RUN pip install -r requirements.txt ADD . /var/www/django/ -
Why after assigning data to a variable outside the ajax block, the variable remains empty [duplicate]
I'm trying to load data for chart drilldown with ajax, in success block i'm assign data to data_by_days(declared outside ajax block), but after ajax block this variable is empty chart.listen('pointClick', function (e) { let pointId let data_by_days=[] if (e.point.get('drillDown')!=null) { chart.getSeries(0).data(e.point.get('drillDown')); } else { pointId = e.point.get('x') $.ajax({ url: '/month_drill_down/', method: 'POST', data: {pointId: pointId}, success: function (data) { data_by_days = data; console.log(data_by_days) }, error: function (d) { console.log(d); } }); console.log(data_by_days) chart.getSeries(0).data(data_by_days); } }); chart.container('container3').draw(); } -
Pie chart of chart.js is not showing label while using ajax
I am working with Chart.Js to show a pie chart. I need to call ajax for fetching data from my database. ajax function: function monthlyAttendanceReport(){ $("#selected-month").html(); array = yearMonthArr($("#selected-month").html()); year = array[0]; month = array[1]; $.ajax({ type: 'GET', url: '{% url "attendance:ajax-user-monthly-attendance-report" %}', data: { 'employee_id': '{{ employee.id }}', 'month': month, 'year': year }, dataType: 'json', success: function (data) { chart(); } }); } pie.js: function chart(){ // Get pie chart canvas var context = $("#monthly-attendance-status-pie-chart"); //pie chart data var monthlyAttendanceStatusdata = { labels: ["match1", "match2", "match3", "match4", "match5"], datasets: [{ label: "Attendance Status", data: [10, 50, 25, 70, 40], backgroundColor: [ "#DEB887", "#A9A9A9", "#DC143C", "#F4A460", "#2E8B57" ], borderColor: [ "#CDA776", "#989898", "#CB252B", "#E39371", "#1D7A46" ], borderWidth: 1 }] }; //create Chart class object var monthlyAttendanceStatusChart = new Chart(context, { type: "pie", data: monthlyAttendanceStatusdata, }); } $(document).ready(function() { $("#selected-month").html(initCurrentMonth()); $('#month-next-btn').attr('disabled', true); // chart(); monthlyAttendanceReport(); }); when I try this lines of code I find that pie chart is generating but without anylabel.. But when I call chart() function in document ready scope and do not call ajax function, pie is generating with all the labels. So, when I use ajax request, no label is showing. But when I do not … -
How to upload multiple images in django, group them per post and display them per post
class Iphones(models.Model): image = models.ImageField(upload_to='images/') class SelliPhone(forms.ModelForm): class Meta: model = Iphones fields = ['image'] widgets ={'image':forms.FileInput(attrs={'class': 'custom-file', 'multiple': True}) -
Setting a forms initial value to a value not in form choices
I'm trying to set the initial value of a form to something that was one of the choices, but is now no longer available. Here is my forms.py choices: list_DB_genius_status= ( ('Bound', 'Bound'), ('Cancelled', 'Cancelled'), ('Closed', 'Closed'), ('Declined', 'Declined'), ('Extended', 'Extended'),) and my class: DB_Genius_Status = forms.TypedChoiceField(label = 'DB Genius Status', choices=list_DB_genius_status) in views.py, I try to set the initial value to "Expired", as this is the default value, but on load it defaults to "Business Exception" def RPA_tool(request, Policy_Number): RPAPolicy = getRPADetails(Policy_Number) print(RPAPolicy) policyNumber = (RPAPolicy.loc[RPAPolicy.index[0], 'Policy_Number']) geniusTransactionType = (RPAPolicy.loc[RPAPolicy.index[0], 'Transaction_Desc']) RPAStatus = (RPAPolicy.loc[RPAPolicy.index[0], 'Status_Desc']) form = RPA_tool_form(initial={'Policy_Number':policyNumber, 'RPA_status': 'Expired'}) return render(request, 'admin_tool/RPA_tool.html', {'form':form}) RPA_tool.html: {% extends "home/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class = "content-section"> <form method ="POST"> {% csrf_token %} <Fieldset class="form-group"> <legend class="border-bottom mb-4"> Edit RPA Details </legend> {{form|crispy}} </Fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit"> Submit </button> </div> </form> </div> {% endblock content %} Is there a way to set the default value to "Expired" or to another value that isn't defined in choices? -
i just want to slide, but i dont know how
since days i try to find a proper code to slide this images in the template but i couldnt make it happen, i need your help bro, lets make it burn. Models 1 : class MyFamily(models.Model): author = models.ForeignKey(Profile, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True) update = models.DateField(auto_now=True) title = models.CharField(max_length=100) explanatipon = models.TextField(blank=True) photo1 = models.ImageField(upload_to='posts/photos/') photo2 = models.ImageField(upload_to='posts/photos/') photo3 = models.ImageField(upload_to='posts/photos/') photo4 = models.ImageField(upload_to='posts/photos/') photo5 = models.ImageField(upload_to='posts/photos/') active = models.BooleanField(default=True) @property def photos(self): photos = [self.photo1, self.photo2, self.photo3, self.photo4, self.photo5] return [photo for photo in photos if photo is not None] def __str__(self): return str(self.title)[:30] profile : class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField() updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.user.username) views : def photo(request): myfamily = MyFamily.objects.filter(active=True) context = { 'myfamily':myfamily } return render(request, 'posts/create-form.html') template : <div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> {% for photo in myfamily.photos %} <div class="carousel-item {% if forloop.first %}active{% endif %}"> <img class="d-block w-100" src="{{ photo.url }}" alt="First slide"> </div> {% endfor %} </div> </div> -
In-memory caching using Cherrypy wsgi server
I use Django to serve my model/application. To improve the response time for coming requests, i use django lrucache_backend caching to cache the model in memory like this: In my model.py file: from django.core.cache import caches model = caches.get(model_cache_key) ## get model from cache if model is None: model = Estimator.load_model_bytes(self.trained_model_file) cache.set(model_cache_key, model, None) ## save model in the cache django SETTINGS.PY : CACHES = { 'default': { 'BACKEND': 'lrucache_backend.LRUObjectCache', 'OPTIONS': { 'MAX_ENTRIES': 1001, 'CULL_FREQUENCY': 1001 }, 'NAME': 'just-a-test' } } Since django runserver is not a production ready server, i want to use Cherrypy to serve my django application. I have 2 questions: Is Cherrypy a good choice to serve my django application that receives high load ? How do i implement in-memory caching using Cherrypy ? Note: I do not want to use any reverse proxy server infront of WSGI server. -
In query set can we use distinct with exclude and orderby in django
I am working in a django project. The query set is longestPendingTask = WorkAssignment.objects.filter(isActive=True,client_id = request.session["clientId"],expectedDate__lte=today).exclude(status="Completed").order_by("expectedDate") It is having exclude and order_by. I want to use distinct to show only unique records, but it does not work. Also the field in distinct is foreign key from another table. Please guide me how to show distinct records. -
Django rest framework's StringRelatedField is throwing KeyError
I have the following model classes. class Categories(models.Model): id = models.UUIDField(primary_key=True, auto_created=True, default=uuid.uuid4, unique=True) business = models.ForeignKey(Business, related_name='category_business', on_delete=models.CASCADE) name = models.CharField(max_length=128) class Meta: unique_together = ('business', 'name') class Menu(models.Model): id = models.UUIDField(primary_key=True, auto_created=True, default=uuid.uuid4, unique=True) business = models.ForeignKey(Business, related_name='menu_business', on_delete=models.CASCADE) name = models.CharField(max_length=128) description = models.CharField(max_length=128) category = models.ForeignKey(Categories, related_name='menus', on_delete=models.CASCADE) price = models.IntegerField() class Meta: unique_together = ('business', 'name', 'category') def __str__(self): return '%s %s %s' % (self.name, self.price, self.description) and I have imported these classes as following as they are located in a separate package Categories = apps.get_model('business', 'Categories') Menu = apps.get_model('business', 'Menu') and this is my serializer class class GetCategoriesSerializer(serializers.ModelSerializer): menus = serializers.StringRelatedField(many=True) class Meta: model = Categories fields = ('name', 'menus') and views is class GetCategories(generics.ListAPIView): """ Returns a list of businesses to the user. It'd read only and no authentication is needed """ permission_classes = [ReadOnly] queryset = Categories.objects.values() serializer_class = GetCategoriesSerializer and url has the following path('customer/<str:pk>/categories', GetCategories.as_view()), I am getting the following error KeyError: 'menus' I looked into the DRF example and this seems to be a simple thing to achieve. https://www.django-rest-framework.org/api-guide/relations/#api-reference But I am kind of stuck at this point. Am I doing anything wrong? Thanks in advance for any help. -
I need a good way to divide a list in Django list view
Hi i'm quite new in django I'm making a student man\ agement program. Currently, the paging and search function have been coded as query and It works in combination , but since we receive new students every year, school_year is important. I want to see the student list by school_year that I want by pressing the year on the top right. I've been thinking about implementing it as a query, but it seems too complicated(I think it's too complicated to combine with the queries that have already been created.), and it's too unnecessary to make a listview for each grade. pls give me some good idea or solution thanks ! listveiw template IMG my views.py here ''' class StudentList(ListView): model = Student template_name = 'student/orders.html' context_object_name = 'students' paginate_by = 12 def get_queryset(self): keyword = self.request.GET.get('keyword') if keyword: object_list = self.model.objects.filter( Q(name__icontains=keyword) | Q(email__icontains=keyword) | Q(student_mobile__icontains=keyword) ) else: object_list = self.model.objects.all() return object_list def get_context_data(self, **kwargs): context = super(StudentList, self).get_context_data(**kwargs) paginator = context['paginator'] page_numbers_range = 5 # Display only 5 page numbers max_index = len(paginator.page_range) page = self.request.GET.get('page') current_page = int(page) if page else 1 start_index = int((current_page - 1) / page_numbers_range) * page_numbers_range end_index = start_index + page_numbers_range if … -
Images from Media directory doesn't show up
My diretory looks something like this: project |_app |_ media |_ profile_pics |_ 1x1.jpg |_ templates |_ urls.py ... I already specified the MEDIA settings on the settings.py: # This part is right below the BASE_DIR MEDIA_DIR = os.path.join(BASE_DIR, 'media') # This part is right at the end of the file # Media MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' On my urls.py: from django.conf.urls.static import static from pro_five import settings from . import views app_name = 'my_app' urlpatterns = [ url('^$', views.index, name='index'), url(r'^registration/', views.register, name='register'), url(r'^login/', views.user_login, name='user_login'), url(r'^logout/', views.user_logout, name='logout'), url(r'^profile/', views.profile, name='profile') ] urlpatterns += static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT) And finally on my template: <img src="media/profile_pics/1x1.jpg" alt="asdasdasd"><br> I don't know why but it just doesn't show up. I followed a lot of solutions only but seems nothing to work for me. I'm relatively new to Django so please forgive my naiveness. Any advices? Thanks a ton! -
Cannot send null to state in order to make ImageField change to null in React and Django
What I want to do Set null in ImageField. And I want to make the value of ImageField that a models has null. Problem When I send Patch request, I got an error like below. The submitted data was not a file. Check the encoding type on the form. Actually, I send image data as file which comes from input type="file". When I send this request to set an image in a model, it works well. But when I send this request again to delete the image that the models has, it doesn't work. How could I set null to ImageField? Or, how could I delete an image that a model already has? I am a beginner to React and Django so I would like you to help me out. I post my code related to my question below. Thank you very much. models.py class User(AbstractUser): # AbstractUserでpasswordは定義済みのため、ここではpasswordを再定義しない(DBにはちゃんと保存される。) username = models.CharField(max_length=150, unique=True) email = models.EmailField(max_length=100, unique=True) profile = models.TextField(max_length=800, blank=True, null=True) icon = models.ImageField(upload_to="images/", blank=True, null=True) background = models.ImageField(upload_to="images/", blank=True, null=True) # AbstractUserはfirst_name,last_nameを保持しているため無効化 first_name = None last_name = None is_staff = models.BooleanField( ('staff status'), default=True, help_text=( '管理サイトへのアクセス権を持っているかどうか'), ) is_active = models.BooleanField( ('active'), default=True, help_text=( 'ユーザーがアクティブかどうか' ), ) is_superuser = models.BooleanField( … -
Show only loaded images in a Carousel/Modal - Bootstrap
below is the layout of a modal in my website: The problem is: in the database there are only 2 images to be displayed in this modal but as I'm using a preconfig Boostratp it is showing always 4 images, regardeless the amount it'd be necessary. My goal is to display, in this case, only 2 images, something like this: In the backend I'm working with Django. Below, my template: <!-- modal area start--> {% for product in products %} <div class="modal fade" id="modal_box-{{ product.id }}" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <div class="modal_body"> <div class="container"> <div class="row"> <div class="col-lg-5 col-md-5 col-sm-12"> <div class="modal_tab"> <div class="tab-content product-details-large"> <div class="tab-pane fade show active" id="tab1" role="tabpanel" > <div class="modal_tab_img"> <a href="#"><img src="{{ product.image.url }}" alt=""></a> </div> </div> <div class="tab-pane fade" id="tab2" role="tabpanel"> <div class="modal_tab_img"> {% if product.image2 %}<a href="#"><img src="{{ product.image2.url }}" alt=""></a>{% endif %} </div> </div> </div> <div class="modal_tab_button"> <ul class="nav product_navactive owl-carousel" role="tablist"> <li > <a class="nav-link active" data-toggle="tab" href="#tab1" role="tab" aria-controls="tab1" aria-selected="false"><img src="{{ product.image.url }}" alt=""></a> </li> {% if product.image2 %} <li> <a class="nav-link" data-toggle="tab" href="#tab2" role="tab" aria-controls="tab2" aria-selected="false"><img src="{{ product.image2.url }}" alt=""></a> </li> {% endif %} </ul> … -
How to call specific data respective to a particular choice in django?
So I am new to django. Suppose I want to choose a particular option from a dropdown box and show the data regarding that particular option in the website in the same webpage considering the fact that i am trying to make a single page app. Also I am trying to pull the data from an API. -
ctrl+click feature is broken in Django project in Pycharm
Hi I have a Django project that I could nicely navigate from view, to template file by ctrl+click on the html file. I made some changes to project and split my setting.py into base, local,production and put them in a settings folder. I made some changes in settings.py on BASE_DIR to reflect the changes accordingly. Now the project is working, however ctrl+click feature is broken and not working. any Idea, why this is lost? -
How do I pass a variable in the URL to a Django list view?
First things first, I want to state I have seen the post created here. The problem is that I am still very new to the Django framework and every attempt I had at implementing this strategy into my code , failed. Anyways, I was curious about how I could pass a string value from the URL into my listview. In my case, the variable named item so I can do a filtered query. This was extremely easy to do on function based views, but I am struggling to do the same on these class based views. Thanks! Class Based View: class PostListView(ListView): model = Post.objects.get(subject_name=item) template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 Routing: path('<str:item>/', PostListView.as_view(), name='post-view') -
Why Django send email function is sending email twice?
I have Used Django EmailMessage function . Here is views.py file. def send_bill_mail(request): context_dict={ "name": "SANKET" } html_message = render_to_string('home/email_templates/bill_generation.html', context_dict) try: email = EmailMessage( ' Welcome to store', html_message, to=['abc@gmail.com'] ) email.content_subtype = "html" email.send() except Exception as e: messages.error(request,"Something Went Wrong !") return redirect('home:dashboard') Here Is settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'xyz@gmail.com' EMAIL_HOST_PASSWORD = 'xyz' EMAIL_PORT = 587 Following Exception is Occured During processing of views. Exception happened during processing of request from ('127.0.0.1', 50522) Traceback (most recent call last): File "C:\Users\sanke\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "C:\Users\sanke\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Users\sanke\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 720, in __init__ self.handle() File "C:\Users\sanke\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "C:\Users\sanke\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Users\sanke\AppData\Local\Programs\Python\Python37\lib\socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine -
How to customize user profilesingup when using django-allauth
I am trying to create a form class that asks users for additional data for my custom user model only on signup. Currently in my aap/forms.py I have: class SetUniversityForm(forms.ModelForm): program = forms.CharField( required=False, widget=forms.TextInput( attrs={ "placeholder":"What are you studying?", "class": "form-control", } ) ) university = forms.ChoiceField( label='', required=True, choices = UNIVERSITY_CHOICES, widget=MySelect( attrs={ "class":"form-control", } ), ) class Meta: model = Profile fields = ('university','program') def signup(self, request, user): user.university = self.cleaned_data['university'] user.program = self.cleaned_data['program'] user.save() And be default user model is: class Profile(AbstractUser): bio = models.TextField() university = models.CharField(max_length=50) program = models.CharField(blank=True,max_length=100) In my settings.py I have: ACCOUNT_SIGNUP_FORM_CLASS = 'app.forms.SetUniversityForm' However, upon user signup for the first time using Google it still redirects to my LOGIN_REDIRECT_URL. How can I implement this? I have looked at: How to customize user profile when using django-allauth But I couldn't fix it. I have also tried using adapters. But I only require this information on signup. -
Display each element of a queryset separated with an <br> inside of a <td> in django template
Model class Tesis(models.Model): descripcion = models.CharField(max_length=50, blank=False, null=True) año = models.PositiveSmallIntegerField(blank=False, null=True) carrera = models.ForeignKey( Carrera, related_name="tesis_carrera", on_delete=models.SET_NULL, null=True) tutor = models.ForeignKey( Tutor, on_delete=models.SET_NULL, null=True, related_name="tutor_tesis") alumno = models.ManyToManyField(Alumno, related_name="alumno_tesis") class Meta: verbose_name_plural = "Tesis" verbose_name = "Tesis" def __str__(self): return self.descripcion VIEW class Listar_TesisListView(LoginRequiredMixin,ListView): queryset = Tesis.objects.all() template_name = "listar_tesis_cargadas.html" model = Tesis TEMPLATE <div class="table-container"> <table class="table"> <thead> <tr> <th class="has-text-centered" colspan="6"> LISTADO DE TESIS </th> </tr> <th>DESCRIPCIÓN</th> <th>AÑO</th> <th>CARRERA</th> <th>TUTOR</th> <th>ALUMNO</th> </thead> <tbody> {% for item in object_list %} <tr> <td>{{ item.descripcion }}</td> <td>{{ item.año}}</td> <td>{{ item.carrera }}</td> <td>{{ item.tutor}}</td> <td><{{item.alumno.all}}</td> {% for al in item.alumno.all %} <td> {{al}} <br> </td> {% endfor %} </tr> {% endfor %} </tbody> </table> </div> WHAT I GET WHAT I WANT In the same <td> when the alumno queryset has 2 elements print the first and then make a breaking line and print the next one. Like this: Alumno Depru1 Alu2 depru2 I also tried this: {% if item.alumno.count > 1 %} {% for al in item.alumno.all %} <td> {{al}} <br>{{al}} </td> {% endfor %} {% else %} {% for al in item.alumno.all %} <td> {{al}} </td> {% endfor %} {% endif %} and I get: Also tried: % for al … -
Trouble with Fetch from JS to Django view
I could use assistance understanding and fixing my error for the following: Javascript calls the following function during some event on the page: function load_homePage() { // Pull all posts fetch('/homepage') .then(response => response.json()) .then(posts => { // Print all posts posts.forEach( function(post) { console.log(post) }) }) } Eventually, I will have JS create dynamic Div's to display all the data that comes in from the call. Fetch is calling to the following view: @csrf_exempt @login_required def view_homePage(request): posts = Post.objects.all() # Return entire set of posts to webpage return JsonResponse([post.serialize() for post in posts], safe=False) Here all I want is for Django to query the database, pull all the data from the Post model, and send it back to the page. The model is as follows: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class Post(models.Model): posterID = models.ForeignKey("User", on_delete=models.CASCADE, related_name="post") content = models.TextField(blank=False) timestamp = models.DateTimeField(auto_now_add=True) def serialize(self): return { "id": self.id, "posterID": self.posterID, "content": self.content, "timestamp": self.timestamp } The Url.py file is also complete: urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("post", views.new_post, name="posts"), path("homepage", views.view_homePage, name="homepage") ] When I try to get the event to … -
My web Page displays nothing when i use load static
Been Practicing Django for a month now.I have learnt the basics,i downloaded a frontend template and i am trying to build a website but when i load my server ,it just keeps on loading without displaying anything.No images or text just keeps loading on and on.I have watched tutorials and done exactly what is done there,then i found out that it does that when i use {%load static}.I already have my static directory and templates in my project. Please I need answers ASAP,Been at it for 4 straight days. enter code here ``URLS.PY from django.contrib import admin from django.urls import path,include from . import views urlpatterns = [ path('', views.estate,name='Estate'), ] -
How to display Ajax response data in Popup?
I have some data in response but I want to display that data in the popup, please let me know how I can display Ajax data in the popup. here is my views.py file... def myview(request): datas=TestForm.objects.all template_name='test.html' context={'datas':datas} return render(request, template_name, context) def myview(request, id): display=TestForm.objects.get(pk=id) template_name='test.html' context={'display':display} return render(request, template_name, context) here is my html file... {% for a in datas %} <a href="javascript:void()" class="btn btn-primary" onclick"exampleModal({{a.id)}})" data-url="{% url 'myap:list_single' a.id %}"> {{a.product_id}} </button> {% endfor %} here is my popup code...where I want to dispslay AJAX data... <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria- labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <tr> <td>{{datas.name}}</td> <td>{{datas.price}}</td> <td>{{datas.category}}</td> </tr> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> here is my AJAX code... function exampleModal(id){ $.ajax({ url: $(this).attr("data-url") type: 'get', dataType: "HTML" success: function(res) { $('.exampleModal').html(res); $("#exampleModal").modal("show"); } }); } -
Django queryset filter with if condition
How to apply a filter in django queryset only if a condition is met. I have a filter object that contains forms list. if forms contains "all" then i want to fetch all objects of the AnswerDetails model else i want to fetch only the u_id in the forms list Code: fil = self.d.get('filter', None) f_uid = fil.get('forms',["all"]) if "all" in f_uid: f_uid = [] a = AnswerDetails.objects.filter(proj=_p, form__u_id__in=f_uid).order_by('-saved_on') -
Django Can't open Admin page (Url Change and get message)
I am getting a message while trying to page Admin. This is default url page I change url to this When I click enter , url was change and get message How to fix this?