Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Use Ready Made Custom Forms in Django
So, I am in the process of learning Django. And creating a simple RSS app. I need a login/registration form. I found this pretty looking form on Codepen and I want to use it. Slide Login and Signup Form It uses a lot of DIVs with classes and is confusing me on how to write the form template for this. Also, would be possible to use the same URL for registration as well as login. Suppose this myapp/login Both login and registration will use POST requests and what would be the best way to differentiate them? to identify whether an event is user registration or login. Need help for this, thanks. I don't really need code... if anyone can just explain this that'd be great. -
Django include tag is displayed in browser not the actual include
I am trying to seperate a navbar in an extra file and import/include it into my base template. The problem is {% include 'sidebar.html %} is just displayed in the browser and does not work as I think it would... Folder structur |-project |-static |-css |-js |-templates |-base.html |-sidebar.html |- static |- ... |-app0 |-templates |-home.html |-... |-manage.py src/project/templates/base.html <html> <head> {% load static %} <link rel="stylesheet" href="{% static 'css/style.css' %}"> <title>Profile</title> </head> <body> {% include 'sidebar.html' %} {% block content %} {% endblock content %} </body> </html> src/project/templates/sidebar.html <div class="sidebar"> <a href="/"> Home</a> <h3>Headline0</h3> <a href="/test0">Test0</a> <h3>Headline 1</h3> <a href="/test1">Test1</a> </div> src/app0/templates/home.html {% extends "base.html" %} {% load static %} {% block content %} Hi <span id="name"></span> <div id="counter"></div> <script src="{% static 'js/index.js' %}" charset="UTF-8"></script> {% endblock %} Browser output: Does have anyone some ideas about it? -
How to set a foreignkey field in views
I'm trying to save the customer field on the Test model, I'm not getting any errors but it's not saving the field either, how do I fix it? Models class Test(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) email = models.EmailField(max_length=200, blank=False) Forms class TestForm(forms.Form): email = forms.EmailField(required=True) class Meta: model = Test fields = ("email") def save(self, commit=False): # Creating the customer object Test.objects.create(email=self.cleaned_data['email']) Views def test_view(request): customer = request.user.customer if form.is_valid(): email = form.cleaned_data['email'] customer = customer form.save() -
"detail": "CSRF Failed: CCSRF token missing." when sending post data from angular 13 to django connected database
i need to send the post data from angular to DRF through angular form but geeting the error i checked almost all the answers available on the internet but did not found and useful answer. "detail": "CSRF Failed: CSRF token missing." //post logic sources.service.ts import { Injectable } from '@angular/core'; import { sources } from './sources'; import { HttpClient } from '@angular/common/http'; import { Observable , of, throwError } from 'rxjs'; import { catchError, retry } from 'rxjs/operators'; import { HttpHeaders } from '@angular/common/http'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', // Authorization: 'my-auth-token', cookieName: 'csrftoken', headerName: 'X-CSRFToken', // X-CSRFToken: 'sjd8q2x8vs1GJcOOcgnVGEkdP8f02shB', // headerName: 'X-CSRFToken', // headerName: , }) }; @Injectable({ providedIn: 'root' }) export class SourcesService { API_URL = 'http://127.0.0.1:8000/sourceapi.api'; constructor(private http: HttpClient) { } /** GET sources from the server */ Sources() : Observable<sources[]> { return this.http.get<sources[]>(this.API_URL); } /** POST: add a new source to the server */ // addSource(data: object) : Observable<object>{ // return this.http.post<object>(this.API_URL,data, httpOptions); // } addSource(source : sources[]): Observable<sources[]>{ return this.http.post<sources[]> (this.API_URL, source, httpOptions); //console.log(user); } } //add-source.component.ts import { Component, OnInit } from '@angular/core'; import { sources } from '../sources'; import { SourcesService } from '../sources.service'; import { FormGroup, FormControl, ReactiveFormsModule} from … -
how to set attributes in html datepicker input in django
i want to use the html input date in a django forms. I already have done that. forms.py class DateInputPicker(forms.DateInput): input_type = 'date' class Form(forms.Form): date = forms.DateField( widget=DateInputPicker, label='Date') But i want to add attributes like min, max and set a default value. How can i do that? Thanks! -
How to check whether the html value is 1 in django
home.html {% if stud.scrapper_status == 1 %} <td>{{stud.scrapper_status}} --> Started</td> {% else %} <td>{{stud.scrapper_status}} --> Completed</td> {% endif %} Output Image If my value is 1 I should get started but for all the value its getting Completed, How to check the value if 1 or not in html -
Django Expression contains mixed types: DateTimeField, IntegerField. You must set output_field
When I am trying to create new post from admin model, I m getting this error. I search many errors like that in google and everywhere wrote that query expression(aggregate, annotation) causes this error, but the reason why I stucked on that error is, I am not using query expression, like aggregation and annotation FieldError at /admin/blog_post/post/add/ Expression contains mixed types: DateTimeField, IntegerField. You must set output_field. Request Method: POST Request URL: http://127.0.0.1:8000/admin/blog_post/post/add/ Django Version: 4.1.3 Exception Type: FieldError Exception Value: Expression contains mixed types: DateTimeField, IntegerField. You must set output_field. I cant do anything because i am not using query expresison can someone tell me where is the main reason and solution? -
'no python application found' in Django
I tried to deploy my Django project on server with uwsgi. I can initial uwsgi withuwsgi --ini conf/uwsgi.ini But when I tried to visit the website, I got this error --- no python application found, check your startup logs for errors --- [pid: 11228|app: -1|req: -1/1] 127.0.0.1 () {46 vars in 946 bytes} [Mon Nov 28 17:06:37 2022] GET / => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0) I put my repo at https://github.com/dolphinfafa/MyLife Anyone knows how to resolve this? Anyone knows how to resolve this? -
Opinion on a project before applying to jobs
I've been working on this project for a year > https://dusan.pythonanywhere.com/ . I am interested in your opinions and suggestions before applying for jobs. Thanks in advance! I used Html, CSS, Django, Python and Javascript -
How to overcome error: 'ManyToOneRel' object has no attribute 'verbose_name' in Django application
In my app I have the following models: class Category(BaseStampModel): cat_id = models.AutoField(primary_key=True, verbose_name='Cat Id') category = models.CharField(max_length=55, verbose_name='Category') class MasterList(BaseStampModel): master_list_id = models.AutoField(primary_key=True, verbose_name='Master List Id') mast_list_category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, verbose_name='Category') # Other fields ... My BaseModel looks like this: class BaseStampModel(models.Model): created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='%(class)s_created', blank=True, null=True, on_delete=models.SET_NULL, verbose_name='Created by') created_on = models.DateTimeField(auto_now_add = True, null=True, blank=True) With this I am able to display the model objects and create/update instances. In my view, when I want to retrieve the verbose_name from model "Category" using: `model_fields = [(f.verbose_name, f.name) for f in Category._meta.get_fields()]` I am getting the following error in my browser: AttributeError: 'ManyToOneRel' object has no attribute 'verbose_name' If I remove the the FK relationship from the field mast_list_category (make it a simple CharField) I don't get the error. Gone through millions of pages, but no solution yet. Any help is much appreciated. -
How to decrypt encrypted <path:pk> and pass it to functions at generics.RetrieveUpdateDestroyAPIView - Django
I want to pass encrypted ids of object in Response, therefore I used AES. now I want accept the encrypted pk which is a path 'xx/xxxx/xxxx', and decrypt it first thing in the view. ` import base64, re from Crypto.Cipher import AES from Crypto import Random from django.conf import settings import codecs # make utf8mb4 recognizable. codecs.register(lambda name: codecs.lookup('utf8') if name == 'utf8mb4' else None) class AESCipher: def __init__(self, key, blk_sz): self.key = key self.blk_sz = blk_sz def encrypt( self, raw ): # raw is the main value if raw is None or len(raw) == 0: raise NameError("No value given to encrypt") raw = raw + '\0' * (self.blk_sz - len(raw) % self.blk_sz) raw = raw.encode('utf8mb4') # Initialization vector to avoid same encrypt for same strings. iv = Random.new().read( AES.block_size ) cipher = AES.new( self.key.encode('utf8mb4'), AES.MODE_CFB, iv ) return base64.b64encode( iv + cipher.encrypt( raw ) ).decode('utf8mb4') def decrypt( self, enc ): # enc is the encrypted value if enc is None or len(enc) == 0: raise NameError("No value given to decrypt") enc = base64.b64decode(enc) iv = enc[:16] # AES.MODE_CFB that allows bigger length or latin values cipher = AES.new(self.key.encode('utf8mb4'), AES.MODE_CFB, iv ) return re.sub(b'\x00*$', b'', cipher.decrypt( enc[16:])).decode('utf8mb4') ` I tried … -
Django - How to Use same view function for multiple different URL Endpoints, but different "parameter" sent?
I'm fairly new to Django and here's my case. If i have 3 endpoints that i can't modify, and i need to point them to one same View function such as : urls.py urlpatterns = [ ... url(r'^a/', views.functionz.as_view(), name='a'), url(r'^b/', views.functionz.as_view(), name='b'), url(r'^c/', views.functionz.as_view(), name='c'), ... ] If I'm restricted from changing the endpoints a/, b/, and c/ to something else that accepts parameters like xyz/a or xyz/b, how can my view function functionz identify the difference between them when it is being called? Can I do something like this pseudocode? views.py Class XYZ(API View): def post(self, request, format=None): if request.endpoint == '/a/': # do things if and only if the client hits /a/ -
django | Celery Async Task Result Pagination
I use celery and redis as backend for my async tasks. I like to paginate my results in the template. I use Javascript (ajax Requests) to request the data. Now I like to paginate the results also with Javascript after request the data. I hope someone can help me. Thats my javascript: $(document).ready(() => { console.log('Sanity Check!'); }); $('.button').on('click', function() { $.ajax({ url: '/tasks/', data: { type: $(this).data('type'),}, method: 'POST', }) .done((res) => { getStatus(res.task_id); getStatusConfluence(res.task_id_confluence); }) .fail((err) => { console.log(err); }); }); function getStatus(taskID) { $.ajax({ url: `/tasks/${taskID}/`, method: 'GET' }) .done((res) => { num_hosts = res.value.length for (i=0; i < num_hosts; i++){ const html = ` <tr> <td>${res.value[i]['name']}</td> <td>${res.value[i]['OK']}</td> <td>${res.value[i]['WARN']}</td> <td>${res.value[i]['CRIT']}</td> </tr> ` $('#result').prepend(html); } const taskStatus = res.task_status; if (taskStatus === 'SUCCESS' || taskStatus === 'FAILURE') return false; setTimeout(function() { getStatus(res.task_id); }, 1000); }) .fail((err) => { console.log(err) }); } function getStatusConfluence(taskID) { $.ajax({ url: `/tasks/${taskID}/`, method: 'GET' }) .done((res) => { num_hosts = res.value.length for (i=0; i < num_hosts; i++){ const html = ` <tr> <td>${res.value[i]['title']}</td> </tr> ` $('#result_confluence').prepend(html); } }) .fail((err) => { console.log(err) }); } -
auto fill a field in model via function django
I was searching to find a way to fill a field of a model via a function. example : def myfunction(): return a_file class SomeModel(models.Model): a_field_name=models.FileField(value=my_function()) I some how was thinking to rewrite the create().share with me your idea -
How to catch an element from a for loop in Django template?
I'm looping through to different categories and rendering results (of its name and its associated pages). This code is rendering correctly. {% for category in categories %} <div class="row"> <div class="col-lg-4"> <h3><a href="{{category.get_absolute_url}}"></a>{{category.category_name}}</h3> {% for page in category.page_set.all %} <p><a href="{{page.get_absolute_url}}">{{page.page_title}}</p> {% endfor %} </div> </div> {% endfor %} I'd like to catch an specific element inside the for loop (to be precise the 4th one in the forloop counter) and customize it (adding some html and text only to that one). I tried using the forloop.counter like this: {% if forloop.counter == 4 %} <!-- modified content --> {% endif %} But there isn't any results (not showing any changes). Is there any way to do this? -
Nginx shows requests to endpoints, not in my API, And unknown requests
Nginx works in Docker compose with Django, react, postgress containers Nginx shows requests for PHP, testPHP endpoints with status code 200 1.171.112.23 - - [27/Nov/2022:09:37:21 +0000] "GET /phpMyAdmin5.2/index.php?lang=en HTTP/1.1" 200 557 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36" "-" 1.171.112.23 - - [27/Nov/2022:09:37:21 +0000] "GET /2phpmyadmin/index.php?lang=en HTTP/1.1" 200 557 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36" "-" 1.171.112.23 - - [27/Nov/2022:09:37:21 +0000] "GET /wp-content/plugins/portable-phpmyadmin/wp-pma-mod/index.php?lang=en HTTP/1.1" 200 557 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36" "-" 1.171.112.23 - - [27/Nov/2022:09:37:21 +0000] "GET /phpmyadmin4/index.php?lang=en HTTP/1.1" 200 557 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36" "-" 1.171.112.23 - - [27/Nov/2022:09:37:22 +0000] "GET /mysql/sqlmanager/index.php?lang=en HTTP/1.1" 200 557 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36" "-" 1.171.112.23 - - [27/Nov/2022:09:37:22 +0000] "GET /phpmyadmin2016/index.php?lang=en HTTP/1.1" 200 557 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36" "-" 1.171.112.23 - - [27/Nov/2022:09:37:22 +0000] "GET /db/myadmin/index.php?lang=en HTTP/1.1" 200 557 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36" "-" 1.171.112.23 - - [27/Nov/2022:09:37:22 +0000] "GET /sql/websql/index.php?lang=en HTTP/1.1" 200 557 "-" … -
django channels deploying with daphne error Requested setting INSTALLED_APPS, but settings are not configured
Hello I'm following this tutorial https://github.com/mitchtabian/HOWTO-django-channels-daphne to deploy mn django channels app and I'm having problem with starting the daphne. I created the daphne.service so far ; [Unit] Description=WebSocket Daphne Service After=network.target [Service] Type=simple User=root WorkingDirectory=/home/django/Petsly/src ExecStart=/home/django/CodingWithMitchChat/venv/bin/python /home/django/CodingWithMitchChat/venv/bin/daphne -b 0.0.0.0 -p 8001 newo.asgi:application Restart=on-failure [Install] WantedBy=multi-user.target after starting the daphne with systemctl start daphne.service , the status of daphne first shows me no error and active after a second it shows this error: ● daphne.service - WebSocket Daphne Service Loaded: loaded (/etc/systemd/system/daphne.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Mon 2022-11-28 07:20:24 UTC; 2s ago Process: 122863 ExecStart=/home/django/Petsly/venv/bin/python /home/django/Petsly/venv/bin/daphne -b 0.0.0.0 -p 8001 > Main PID: 122863 (code=exited, status=1/FAILURE) Nov 28 07:20:24 ubuntu-g1-small3-fr-1 systemd[1]: daphne.service: Main process exited, code=exited, status=1/FAILURE Nov 28 07:20:24 ubuntu-g1-small3-fr-1 systemd[1]: daphne.service: Failed with result 'exit-code'. Nov 28 07:20:24 ubuntu-g1-small3-fr-1 systemd[1]: daphne.service: Scheduled restart job, restart counter is at 5. Nov 28 07:20:24 ubuntu-g1-small3-fr-1 systemd[1]: Stopped WebSocket Daphne Service. Nov 28 07:20:24 ubuntu-g1-small3-fr-1 systemd[1]: daphne.service: Start request repeated too quickly. Nov 28 07:20:24 ubuntu-g1-small3-fr-1 systemd[1]: daphne.service: Failed with result 'exit-code'. Nov 28 07:20:24 ubuntu-g1-small3-fr-1 systemd[1]: Failed to start WebSocket Daphne Service. and sudo journalctl -u daphne.service v 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]: File "/usr/lib/python3.8/importlib/__init__.py", line … -
Django modelformset_factory: how to create field with constant value
Say I have a bakery which bakes 10 pies in a batch (i.e. all 10 pies go into the same oven). The objective is simply to record the weight (in grams) and cost of each pie (in $). Cost = weight * 0.01. So each pie is modelled as a PieRecord object, which has weight and cost: models.py from django.db import models class PieRecord(models.Model): """this will be in a modelformset """ # pie_name is a dummy field just to play with text input pie_name = models.CharField(max_length=20) pie_weight_grams = models.FloatField() # calculated: cost($) = pie_weight_grams * 0.01 cost = models.FloatField(default=0.0) I use modelformset_factory to generate 10 PieRecord forms at a shot, and surface on the web page (see views.py below). My question is: I would like to attach some fields that are specific to each batch of 10 pies (not each pie), e.g.: cook time (minutes, FloatField) cook name (CharField) cook date (DateField) cook temperature (degC, FloatField) If I simply add these fields to my PieRecord class, this would result in the user having to enter the same values 10 times (e.g. cook_name James baked this batch of 10 pies), which results in a lot more data entry than is needed; … -
How to implement tooltip with django form
I have a model form based on this model: class MyModel(TimeStampedModel): MY_CHOICES = [tuple([x,x]) for x in range(1,8)] p1 = models.IntegerField("P1”, default='1', help_text=‘text1’) p2 = models.IntegerField(“P2”, default=‘1’, , help_text=‘text2’) Parent = models.ForeignKey(ParentModel, on_delete=models.CASCADE) The form itself looks like: class MyModelForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_id = 'id-CaseForm' self.helper.form_class = 'blueForms' self.helper.form_method = 'post' self.helper.form_tag = False self.helper.help_text_inline = False self.helper.form_show_labels = False self.helper.layout = Layout( Row(Field(PrependedText('p1', ‘field_label1’, wrapper_class='col-12 col-lg-6 pe-0 stretchprepend'))), Row(Field(PrependedText('p2’, ‘field_label2’, wrapper_class='col-12 col-lg-6 pe-0 stretchprepend’)))) CHOICES = [tuple([x,x]) for x in range(1,8)] p1 = IntegerField( label='field_label1', widget=Select(choices=CHOICES)) p2 = IntegerField( label='field_label2’, widget=Select(choices=CHOICES)) class Meta: model = MyModel fields = ['p1', 'p2’,] And this is displayed as a crispy form in the template: {% crispy panss_form %} I want the user to see some help text when they hover over the fields. This help text could be the help_text from the model, or I am happy to put it somewhere else (although it should go in either the model or the form, not in the template). Any help appreciated. -
How to paginate in django for filtered datas
views.py import datetime from .filters import MyModelFilter from django.shortcuts import render import pymysql from django.http import HttpResponseRedirect from facligoapp.models import Scrapper from django.db.models import Q from django.utils import timezone import pytz from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger users = "" def index(request): if request.method == "POST": from_date = request.POST.get("from_date") f_date = datetime.datetime.strptime(from_date,'%Y-%m-%d') print(f_date) to_date = request.POST.get("to_date") t_date = datetime.datetime.strptime(to_date, '%Y-%m-%d') print(t_date) get_records_by_date = Scrapper.objects.all().filter(Q(start_time__date=f_date)|Q(end_time__date=t_date)) print(get_records_by_date) filtered_dates = MyModelFilter(request.GET,queryset=get_records_by_date) page = request.GET.get('page', 1) paginator = Paginator(filtered_dates.qs, 5) global users try: users = paginator.get_page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) else: roles = Scrapper.objects.all() page = request.GET.get('page', 1) paginator = Paginator(roles, 5) try: users = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) return render(request, "home.html", {"users": users}) return render(request, "home.html", {"users": users}) filters.py: import django_filters from.models import Scrapper class MyModelFilter(django_filters.FilterSet): class Meta: model = Scrapper # Declare all your model fields by which you will filter # your queryset here: fields = ['start_time', 'end_time'] home.html <!DOCTYPE html> <html> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script> <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <body> <style> h2 {text-align: center;} </style> <h1>Facilgo Completed Jobs</h1> <form action="" method="post"> {% csrf_token %} <label for="from_date">From Date:</label> <input type="date" id="from_date" name="from_date"> … -
Django - Display the number of users currently watching a live stream
I'm developing a Django site for a sports streaming service. It is necessary to display the number of users who are currently watching the broadcast. You can watch the broadcast only after authorization. What is the best way to implement this? At the moment I think that the best solution would be to send a js request to the Django server, but I think there is a better way. -
When i use latest version of drf-yasg to doing api documentation but it is not working
enter image description here but I have seen GitHub repository of Drf-Yasg , there is this package enter image description here I have done QuickStart that in its docs . -
I want to create pagination in django
**This is my view.py coding. it was working but when I add pagination then show some error ** def car(request): all_products = None all_category = category.get_all_category() categoryid = request.GET.get('category') paginator=Paginator(categoryid,4) page=request.GET.get('page') try: all_category.paginator.page(page) except PageNotAnInteger: all_category=paginator.page(1) except EmptyPage: all_category=paginator.page(paginator.num_pages) else: all_category = Product.get_all_products() if categoryid: all_products = categoryid.get_all_products_by_id(categoryid) data = {} data['products'] = all_products data['category'] = all_category all_location = location.get_all_location() all_products = Product.get_all_products() all_team = teams.get_all_team_members() data['product'] = all_products data['location'] = all_location data['teams'] = all_team return render(request, 'car.html', data, {'all_category':all_category, 'categoryid':categoryid, 'category':category(), 'page':page}) **This is my pagination.html file ** <div class=""> <span class=""> {% if page.has_previous %} <a href="?page={{ page.previous_page_number }}">Previous</a> {% endif %} <span class=""> Page {{ page.number }} of {{ page.paginator.num_pages }}. </span> {% if page.has_next %} <a href="?page={{ page.next_page_number }}">Next</a> {% endif %} </span> </div> This is my car.html file. <div class="container-fluid py-1 justify-content-between p-2 m-2"> <div class="container"> <h6 class="display-4 text-uppercase text-center mb-5" style="font-size: 40px">Filters</h6> {% for category in category %} <a href="{% url 'car' %}?category={{ category.id }}"> <button type="button" class="btn btn-outline-secondary rounded">{{ category.name }}</button> </a> {% endfor %}<hr> <h1>{% include 'pagination.html' with page=all_category %}</h1> </div> </div> Actually I want to display all cars data by pagination same all cars categories by patination. I am following this … -
How to create a customized printout report (like crystal reports)? I'm using Django and MYSQL
I'm new to django and python. I'm trying to create a Daily Time Record printout. I'm using Django and Mysql as my database. How to create a report? Is there a designer tool like Crystal reports? enter image description here The output should be like the image shown. -
how can i stop to run path with same parameter on continue path
here i send my details how can i stop this for example if i run http://127.0.0.1:7000/search_acctable/?txt=Kalpesh but if now i again run my code this is run like http://127.0.0.1:7000/search_acctable/?txt=Kalpesh/search_acctable/?txt=any in django how can i solve this i need help to solve this problem views.py def s_index(request): current_url = request.build_absolute_uri() #print(current_url) src = request.POST.get('txt_search') #if request.POST['btn_clear']: # return HttpResponseRedirect(request.META.get('HTTP_REFERER')) # return to previous page if request.POST['btn_search']: rec=accmaster.objects.filter(Q(acc_name__contains=src) | Q(acc_city__contains=src)| Q(acc_op__contains=src) ).values() # for filter with and conition onyl put comma if want or condition use pipe sign and Q if rec.exists(): rec=accmaster.objects.filter(Q(acc_name__contains=src)| Q(acc_city__contains=src)| Q(acc_op__contains=src)).values() grp_city=accmaster.objects.filter( Q(acc_name__contains=src) | Q(acc_city__contains=src)| Q(acc_op__contains=src)).values('acc_city').annotate(Sum('acc_op')).order_by('acc_city') template=loader.get_template('index.html') output=accmaster.objects.filter(Q(acc_name__contains=src)| Q(acc_city__contains=src)| Q(acc_op__contains=src)).values().aggregate(Sum('acc_op')) context ={ 'rec':rec, 'output':output['acc_op__sum'], 'grp_city':grp_city, } return HttpResponse(template.render(context,request)) else : return HttpResponseRedirect(request.META.get('HTTP_REFERER')) # return to previous page urls.py from django.urls import path from . import views urlpatterns=[ path('',views.index,name='index'), path('addacc/',views.add,name='addacc'), path('addacc/addrecord/',views.addrecord,name='addrecord') , path('delete/<int:id>',views.delete,name='delete') , path('update/<int:id>',views.update,name='update'), path('update/updaterecord/<int:id>',views.updaterecord,name='updaterecord'), path('index/',views.s_index,name='s_index'), #path('',views.form_view,name='mform') ] index.html {% load static %} <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> function printreport(){ //var divtoprint=document.getElementById("maindiv"); var printcontext=document.getElementById("maindiv").innerHTML; var originalcontext=document.body.innerHTML; var nwin=window.open(""); nwin.document.open(); nwin.document.write('<html><head><link rel="stylesheet" media="print" href="{% static 'mystyleprint.css' %}" ></head><body>'); nwin.document.write(printcontext); nwin.document.write("</body></html>"); //document.write(printcontext); //document.body.innerHTML=printcontext; //printWindow.document.write(divtoprint); nwin.print(); nwin.document.close(); nwin.close(); } </script> <link rel="stylesheet" href="{% static 'mystyle.css' %}" > <link rel="stylesheet" href="{% static 'mystyleprint.css' %}" media="print"> <!-- make seprate css for …