Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
saving in the database form modelform datefield in django
I am new to Django and I am self teaching myself how to develop a complete frontend with a SQLite database backend. I am trying to creat a leave request form, get the user to request a leave, save the request in the DB, let the manager sig in and once accepted, save the request as leave request granted. My model.py is: from django.db import models class StaffDetail(models.Model): staff_member_name = models.CharField(max_length=100) deptartment = models.CharField(max_length=50) manager = models.CharField(max_length=100) email_address = models.CharField(max_length=100) password = models.CharField(max_length=100) date_joined = models.DateField(auto_now_add=True) holidays_allowed = models.DecimalField(default=25, max_digits=4, decimal_places=2) holiday_taken = models.DecimalField(default=0, max_digits=4, decimal_places=2) # last_holiday = models.DateField(null=True, blank=True) def __str__(self): return self.staff_member_name class HolidayRequest(models.Model): leave_requested_by = models.CharField(max_length=100) leave_reason = models.CharField(max_length=50) other_reason = models.CharField(max_length=100) holiday_start = models.DateField(null=True, blank=True) holiday_end = models.DateField(null=True, blank=True) total_days = models.DecimalField(max_digits=4, decimal_places=2) # accept_or_rejected = models.CharField(max_length=100) def __str__(self): return self.leave_requested_by class HolidayRecord(models.Model): leave_requested_by = models.ForeignKey(HolidayRequest, on_delete=models.CASCADE) # leave_reason = models.CharField(max_length=50) # other_reason = models.CharField(max_length=100) # holiday_start = models.DateField() # holiday_end = models.DateField() # total_days = models.DecimalField(max_digits=4, decimal_places=2) # leave_accept_by = models.BooleanField(default=False) def __str__(self): return self.leave_requested_by forms.py: from django import forms from .models import StaffDetail, HolidayRequest class LRForm(forms.ModelForm): # ACCEPT_REJECT_CHOICES =[ # 'accepted', 'Accepted', # 'rejected', 'Rejected', # ] # LEAVE_REASON_CHOICES =[ # 'annual_leave', 'Annual … -
python framework question [django or flask or other]
I want to create a web application of prediction using machine learning, I am lost in the choice of python framework Can you help to choice the framework suitable with machine learning? -
How to prevent user to access login page in django when already logged in?
In my django application, user can access login/signup pages through URL even after logged-in. How to prevent them from accessing these pages? urls.py from django.urls import path from django.contrib.auth import views as auth_views from . import views app_name = 'account' urlpatterns = [ path('signup/', views.register, name='register'), path('', auth_views.LoginView.as_view(), name='login'), ] Though I can write if-else statement for checking authenticated users in views.py, but I haven't used any function for login in views.py. I am using django's default login sysyem and an authentication.py page for custom login (Authentication using an e-mail address). authentication.py from django.contrib.auth.models import User class EmailAuthBackend(object): """ Authenticate using an e-mail address. """ def authenticate(self, request, username=None, password=None): try: user = User.objects.get(email=username) if user.check_password(password): return user return None except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None Please suggest me an efficient way of redirecting already authenticated users to the home page whenever they try to access login or signup pages through typing its URL on the browser. -
programmatically accessing pycharm debug configuration PORT
Pycharm debug config using the run/debug configuration with a port 8000 for testing and my workmates are using other ports was wondering if theres any place in the project this port is written to so i can access it from there /var/projects/XX/manage.py runsslserver --cert /var/projects/XX/config/certs/XX.concat.crt --key /var/projects/XX/config/certs/XX.key XX:8000 i need to import the port in the selenium tests so it doesnt have to be configured each time not in the context of a request, otherwise id use request.META. etc... i need it for selenium before even the page is accessed -
How to fix " Timeout when reading response headers from daemon process" error when using WSGI with Django and Apache
I have installed Django and created a new project using the following commands: mkdir trydjango cd trydjango virtualenv -p python3 . source bin/activate pip install django==2.0.7 When I run pip freeze, I see the following: Django==2.0.7 pkg-resources==0.0.0 pytz==2018.9 Inside my virtualhost I have the following: ServerAdmin webmaster@localhost ServerName django.mydomain.com ServerAlias www.django.mydomain.com DocumentRoot /var/www/django.mydomain.com ErrorLog ${APACHE_LOG_DIR}/django.mydomain.com.error.log CustomLog ${APACHE_LOG_DIR}/django.mydomain.com.access.log combined <Directory root/Dev/trydjango/src/trydjango> <Files wsgi.py> Require all granted </Files> </Directory> WSGIApplicationGroup %{GLOBAL} WSGIDaemonProcess trydjango python-home=root/Dev/trydjango/bin python-path=root/Dev/trydjango/ WSGIProcessGroup trydjango WSGIScriptAlias / /root/Dev/trydjango/src/trydjango/wsgi.py But when I try to access my domain, it time outs. When I access the Apache error log for the domain the following error message is present: [pid 12746] [client xx.xx.xx.xxx:60684] Timeout when reading response headers from daemon process 'trydjango': /root/Dev/trydjango/src/trydjango/wsgi.py How can I fix this timeout problem? I've chowned wsgi.py to www-data:www-data I've also made the folder the app is in exectuable Not sure what else to try with this brand new project to get wsgi working. I found this: Django Webfaction 'Timeout when reading response headers from daemon process' and added WSGIApplicationGroup %{GLOBAL} to the virtualhost and also to apache2.conf but this didn't fix the problem. -
NotImplementedError: Wrong number or type of arguments for overloaded function 'new_RoutingModel'
I was making route optimiser a web app developed in django which was working fine but due to some changes in I guess I wreaked my code of rote optimiser.It is showing me following errors: File "/home/chirag/chirag/smartlogistics/lib/python3.7/site-packages/ortools/constraint_solver/pywrapcp.py", line 3191, in __init__ this = _pywrapcp.new_RoutingModel(*args) NotImplementedError: Wrong number or type of arguments for overloaded function 'new_RoutingModel'. Possible C/C++ prototypes are: operations_research::RoutingModel::RoutingModel(operations_research::RoutingIndexManager const &) operations_research::RoutingModel::RoutingModel(operations_research::RoutingIndexManager const &,operations_research::RoutingModelParameters const &) I was unable to figure the problem, I'm new in django. Any help is appreciated. Thank you. -
How do i create a page with forms without using models in django admin?
I am trying to create a page/view with a form containing few fields in django admin without using models. This form when submitted will make an api call to another project made in django with django rest framework that will be running parallely. How do I go about this? -
how use UpdateView change user password in the django
i have something code 1.When I try to change the user password, the password stored in the database is plain text. 2. The database password is empty when the form is submitted without entering a password. What should I do? thanks class UserUpdate(LoginRequiredMixin, SuccessMessageMixin, UpdateView): model = User template_name = 'users/UserUpdate.html' context_object_name = 'UserUpdate' form_class = UserUpdateForm success_url = reverse_lazy('UserList') success_message = 'update success' def form_valid(self, form): password = form.cleaned_data.get('password') if not password: return super().form_valid(form) return super().form_valid(form) forms class UserUpdateForm(ModelForm): password = forms.CharField( required=False, label="password", max_length=32, strip=False, widget=forms.PasswordInput, ) class Meta: model = User fields = ['username', 'password', 'last_name', 'email', 'is_superuser', 'is_active'] def save(self, commit=True): password = self.cleaned_data.get('password') user = super().save(commit=commit) if password: user.reset_password(password) else: pass return user -
How to convert raw data to excel file in django
In one of my application test case, I have to open the email attachment file and verify the data. The email attachment what I get in the test is like this ` \xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00>\x00\x03\x00\xfe\xff\t\x00\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\t\x00\x00\x00\x00\x00\x00\x00\x00\x10\x00\x00\xfe\xff\xff\xff\x00\x00\x00\x00\xfe\xff\xff\xff\x00\x00\x00\x00\x08\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x How to convert it back to excel file.` -
How to set timeout for yield call in React Redux-Saga
const response = yield call(api.addPost, payload); calling django rest api here. The django backend do heavy processing(usually takes 1.5 minutes) to produce result, in that time, Error: timeout of 60000ms exceeded occurred in react.So, the peer connection is lost. -
Serializer get model from another table. Django
I have 2 different models its auctions and user. I need output information abour auction and in auction i need output user information. So i have this serializer: class LeadsAuctionUsersSerializer(serializers.ModelSerializer): user = LeadUserSerializer(many=False, read_only=True, source="get_user") // custom field what i need output for each auction def get_user(self): user = User.objects.get(pk=10) // for example i take user with id == 10, but then i need output different users(it depend on auction id) return LeadUserSerializer(user, many=False).data class Meta: model = Auction fields = ('user', 'actual_price', ) read_only_fields = ('user', 'actual_price', ) My LeadUserSerializer class LeadUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'email', 'username', 'first_name', 'last_name', 'is_staff', 'address', 'city', 'state', 'zip', 'phone', 'is_active', 'is_ban', 'avatar', 'custom_role') read_only_fields = ('is_ban', 'is_active', 'is_staff', 'groups', 'cars') I have not any users in json. How can i do like i want? -
Django, field interaction in ModelForm requires API call
Imagine that I have 4 fields in a ModelForm. Currency Pair, it is a dropdown with a currency pair ex. BTC-USD or LTC-USD - user's choice Rate (of the chosen currency pair) - API call to an exchange Amount - user's imput Price - calculates automatically, it is the result of Rate*Amount Fields interact with each other. If user changes the Amount, the Price changes - I have managed to make it both, on the backend side and the frontend side (javascript) If user changes the Currency Pair, the Rate updates on the frontend I have a problem with 2, because it requires an API call in order to verify the current rate for a given currency pair. Could somebody give me a hint how I can make the API call once the page is loaded and I only want to update the rate without reloading the page, so it could be used to update the Price? Should I use ajax here? Is it the right direction? I just need a general idea, so I could dig into it. Thank you and hope it makes sense. -
Does django class based views inherit method_decorators defined?
I'm using django class-based views. Suppose there is a ListView like this: @method_decorator(ensure_csrf_cookie, name='dispatch') class SomeView(ListView): ... If another class-based view inherits from SomeView, Does it inherit the "ensure_csrf_cookie" too? Or it has to be defined on every subclasses explicitly? -
Django rest-framework: Spring Boot like model serialization
I am looking forward to build a "mother of REST" rest api with the django REST framework. Therefore I like to have all relationships represented as urls. Using Spring Boot this is pretty easy, but not so for django REST I think. Please correct me if I am wrong. I have to models: class User(AbstractBaseUser): username = models.CharField(max_length=25, unique=True) email = models.EmailField() created_at = models.DateTimeField(auto_now_add=True) class Group(models.Model): admin = models.ForeignKey(User, related_name='groups', on_delete=models.PROTECT) shared_user = models.ManyToManyField(User, related_name='shared_groups') name = models.CharField(max_length=25) description = models.TextField() created_at = models.DateField(auto_now=True) Now I like the model relation ships to be serialized like the following schema (for shortness I only show the User model as json): { "id":1, "username":"user_1", "email":"user_1@test.de", "created_at":"2019-03-08T08:42:34.766951Z", "_links":{ "self":"http://127.0.0.1:8000/users/1/", "groups":"http://127.0.0.1:8000/users/1/groups" } } I know I can get the self url by passing it to the fields, but I like to have it in the _links section. I tried using the serializers.SerializerMethodFieldto add the extra information. But I have no idea to generate the urls for representing the objects. Can anyone help? By the way the serializer: class UserSerializer(serializers.HyperlinkedModelSerializer): _links = serializers.SerializerMethodField('representations') class Meta: model = User fields = ('id', 'username', 'email', 'created_at', 'password', '_links') extra_kwargs = { 'password': {'write_only': True}, 'groups': {'read_only': True} … -
Get context from another CBV with Django
I would like to get your help in order to use context from a Django CBV in another CBV through get_context_data(). Objective: Basically, I have a django ListView() with pagination. I pick up the current page in get_context_data(). Then, I would like to edit an object, so I'm going to UpdateView(). When I post the edit, it should return to the previous pagination. For example, if the object was on page 32, after the POST request, I need to be redirected to page 32. My code: class DocumentListView(AdminMixin, CustomListSearchView): """ Render the list of document """ def get_context_data(self, **kwargs): context = super(DocumentListView, self).get_context_data(**kwargs) actual_page = self.request.GET.get('page', 1) if actual_page: context['actual_page'] = actual_page return context class DocumentFormView(CustomPermissionRequiredMixin, DocumentListView, UpdateView): def get_current_page(self, **kwargs): context = super(DocumentListView, self).get_context_data(**kwargs) actual_page = context['actual_page'] return actual_page def get_context_data(self, **kwargs): context = super(DocumentFormView, self).get_context_data(**kwargs) print(self.get_current_page()) ... return context def post(self, request, pk=None): ... return render(request, 'app/manage_document_form.html', context) Issue: I don't overcome to get the actual_page in my class DocumentFormView. I got this issue : AttributeError: 'DocumentFormView' object has no attribute 'object' I tried to add in my post() function : self.object = self.get_object() But it doesn't solve the issue. Do you have any idea ? -
clean data for request.POST.get()
Searching a way for cleaning data for variables I get with request.POST.get() if form.is_valid(): foo = request.POST.get('foo_id') Like I normally do in POST-Forms: form.cleaned_data [] -
django 2.1 + PostgreSQL 11 + Python 3.7 - Cannot do makemigrations
I'm trying to create a geospatial database with geodjango and postgis following the recommendations of the book : Python Geospatial development, 3rd Edition of Erik Westra, in order to do it I'm trying to configure my django database and to connect it to my PostgreSQL db. After having launched my PostgreSQL database, I've created my django project and django apps. From then I'd like to apply makemigrations command to my shared app with : python manage.py makemigrations shared But then I've go the following error : File "C:\Users\[...]\Anaconda3\lib\site-packages\psycopg2\__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError I've even tried to check migrations with showmigrations but it makes the same error message so I've absolutely no clue what's going on. here's my settings.py file: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'shapeeditor', 'USER': 'shapeeditor', 'PASSWORD': '(password)', } } I've put (password) to hide the real one but I've checked it's the good one. The NAME corresponds to the database name with a USER who has the same name The shared app is written in INSTALLED_APPS so I've checked I didn't forget it. I've looked at the many posts in StackOverflow about the error I got but it doesn't … -
how to run Select and where statement in django
How to Select and Put Where Condition in Django? and how to print in view.py i am trying like this but not works check2 = Project_Time_Status.objects.filter(project_id=project_id).filter(finishing_time__isnull=True).all() if check2: for unit in check2: print (unit.project_id) select * from Project_Time_Status where project_id = projectid AND finishing_time != null> Thanks in advance. -
How can i resolve the ModuleNotFoundError in django web app development to use the modules like bs4, requests in my django project?
I have python script in my views.py , in the 'def results_view(request):' there is one method 'def QF(gen_name):' , which is having 'from bs4 import BeautifulSoup' , 'import requests'. In command prompt, It is showing error - ModuleNotFoundError: No module named 'bs4' How to solve this problem ? The code snippet from views.py is show below: def results_view(request): def QF(gen_name): title_head='Brands for ' from bs4 import BeautifulSoup import requests data = response.text soup = BeautifulSoup(data, 'lxml') #more statements -
Django change wrong column name in DB
in my Database (psql) I've got a table named offers_offer and inside that there is an column named offer_name, which is wrong, because it should actually be just name. I don't know why it has this name, but due to this I can't load any fixtures or create a new object, because I always receive the error that name wasn't found (obviously). Now my model looks like this: class Offer(models.Model): name = models.CharField(default="", verbose_name='Offer Name', blank=False, max_length=255) (some other fields...) and my ONLY initial migration looks like this: from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('crm', '0007_make_gender_mandatory'), ] operations = [ migrations.CreateModel( name='Offer', fields=[ ('name', models.CharField(default='', max_length=255, verbose_name='Offer Name')), (every other field...) ], options={ (some options...) }, ), ] So I don't really know why it's named offer_name in my db, while this was created to have name as field name. Anyway I tried to fix that by making a new migration like: from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('offers', '0001_initial'), ] operations = [ migrations.AlterField( model_name='offer', name='offer_name', field=models.CharField(default='', db_column=b'offer_name', max_length=255, verbose_name='Offer Name'), ), migrations.RenameField( model_name='offer', old_name='offer_name', new_name='name', ), ] … -
How do you fix the apps aren't loaded yet error in Django using django-mysql?
Im getting this error when trying to start Django in pycharm. I don't understand as it was running properly yesterday. django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Here is the full trace back: Traceback (most recent call last): File "/Users/matthew/PycharmProjects/GluIQ/DreamIt/views.py", line 2, in <module> from Home.models import QuestionAwner, userProject, Files File "/Users/matthew/PycharmProjects/GluIQ/Home/models.py", line 4, in <module> from django_mysql.models import JSONField File "/Users/matthew/python3venv/gluiq/lib/python3.7/site-packages/django_mysql/models/__init__.py", line 7, in <module> from django_mysql.models.base import Model # noqa File "/Users/matthew/python3venv/gluiq/lib/python3.7/site-packages/django_mysql/models/base.py", line 11, in <module> class Model(models.Model): File "/Users/matthew/python3venv/gluiq/lib/python3.7/site-packages/django/db/models/base.py", line 110, in __new__ app_config = apps.get_containing_app_config(module) File "/Users/matthew/python3venv/gluiq/lib/python3.7/site-packages/django/apps/registry.py", line 247, in get_containing_app_config self.check_apps_ready() File "/Users/matthew/python3venv/gluiq/lib/python3.7/site-packages/django/apps/registry.py", line 125, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. here is the imports for views.py: from django.shortcuts import render, redirect from Home.models import QuestionAwner, userProject, Files from django.views.generic import View from DreamIt.forms import ProjectMandateForm, StatementOfNeedForm from braces.views import LoginRequiredMixin from django.core.files.storage import FileSystemStorage here is the imports for models.py: from django.db import models from django.conf import settings from django.core.urlresolvers import reverse from django_mysql.models import JSONField Here are my installed apps: INSTALLED_APPS = [ 'Home.apps.HomeConfig', 'DreamIt.apps.DreamitConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_mysql', ] Heres what i have installed: django==1.11.20 PyMySQL==0.9.3 coverage==4.5.2 django-bootstrap3-datetimepicker==2.2.3 django-braces==1.13.0 django-mysql==2.4.1 mysql-connector-python==8.0.15 pip==10.0.1 protobuf==3.6.1 pytz==2018.9 setuptools==39.1.0 … -
please explain its syntax?
class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group def chat_message(self, event): message = event['message'] # Send message to WebSocket self.send(text_data=json.dumps({ 'message': message })) -
potrait image is not displaying correct in django
from django.db import models from PIL import Image class News(models.Model): news_heading = models.CharField(max_length=50) news_date = models.DateTimeField() news_details = models.CharField(max_length=200) image_one = models.ImageField(upload_to="images/news",blank=True) image_one_height = models.BigIntegerField(blank=True,default=300) image_one_width = models.BigIntegerField(blank=True,default=300) image_two = models.ImageField(upload_to="images/news",blank=True) image_two_height = models.BigIntegerField(blank=True,default=300) image_two_width = models.BigIntegerField(blank=True,default=300) def __str__(self): return self.news_heading This is my model.py from django.shortcuts import render from .models import News # Create your views here. def news_view(request): news = News.objects.order_by('-id') context = { 'news':news } return render(request,'news/news.html',context) This is my view.py what should i have to do to make image display correct. Potrait images are displaying rotated left. how to make them display correct. -
How to filter queryset in django inline form?
I want to filter certain modelfield in my inlineform to specific user and company. But was unable to do in django inline formset. This are my models: class Purchase(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) company = models.ForeignKey(Company,on_delete=models.CASCADE,null=True,blank=True) party_ac = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='partyledger') purchase = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='purchaseledger') total = models.DecimalField(max_digits=10,decimal_places=2,null=True,blank=True) purchases class Stock_total(models.Model): purchases = models.ForeignKey(Purchase,on_delete=models.CASCADE,null=True,blank=False,related_name='purchasetotal') stockitem = models.ForeignKey(Stockdata,on_delete=models.CASCADE,null=True,blank=True,related_name='purchasestock') quantity_p = models.PositiveIntegerField() rate_p = models.DecimalField(max_digits=10,decimal_places=2) grand_total = models.DecimalField(max_digits=10,decimal_places=2,null=True,blank=True) My views: class Purchase_createview(ProductExistsRequiredMixin,LoginRequiredMixin,CreateView): form_class = Purchase_form template_name = 'stockkeeping/purchase/purchase_form.html' def get_context_data(self, **kwargs): context = super(Purchase_createview, self).get_context_data(**kwargs) context['profile_details'] = Profile.objects.all() company_details = get_object_or_404(Company, pk=self.kwargs['pk']) context['company_details'] = company_details if self.request.POST: context['stocks'] = Purchase_formSet(self.request.POST) else: context['stocks'] = Purchase_formSet() return context def form_valid(self, form): form.instance.user = self.request.user c = Company.objects.get(pk=self.kwargs['pk']) form.instance.company = c form.instance.counter = counter context = self.get_context_data() stocks = context['stocks'] with transaction.atomic(): self.object = form.save() if stocks.is_valid(): stocks.instance = self.object stocks.save() return super(Purchase_createview, self).form_valid(form) In my forms I have tried this: class Stock_Totalform(forms.ModelForm): class Meta: model = Stock_Total fields = ('stockitem', 'Quantity_p', 'rate_p', 'Disc_p', 'Total_p') def __init__(self, *args, **kwargs): self.User = kwargs.pop('purchases.User', None) self.Company = kwargs.pop('purchases.Company', None) super(Stock_Totalform, self).__init__(*args, **kwargs) self.fields['stockitem'].queryset = Stockdata.objects.filter(User = self.User, Company= self.Company) self.fields['stockitem'].widget.attrs = {'class': 'form-control select2',} self.fields['Quantity_p'].widget.attrs = {'class': 'form-control',} self.fields['rate_p'].widget.attrs = {'class': 'form-control',} self.fields['Total_p'].widget.attrs = {'class': 'form-control',} Purchase_formSet = inlineformset_factory(Purchase, Stock_Total, form=Stock_Totalform, … -
WeasyPrint converting HTML TO PDF failed to generate the perfect result
I am working with WeasyPrint and is converting HTML to PDF. I am trying to replicate a circular percentage progress bar from HTML to PDF. The circular percentage progress bar uses transform and clip property of CSS. But the actual result is different from the expected result. The HTML code is : <html> <head> </head> <style> body, html { font-size: 10px; } </style> <body> <p>Test Page</p> <div style="font-size: 20px;margin: 20px;position: absolute;padding: 0; width: 4.3em;height: 4.3em;background-color: white; transform: rotate(324deg); border-radius: 50%;line-height: 5em;display: block;text-align: center;border: none; "> <span style="position: absolute;line-height: 5em;width: 5em;text-align: center;display: block;color: #53777A;z-index: 2;">10%</span> <div style="border-radius: 50%;width: 5em;height: 5em;position: absolute;"> <div style=" position: absolute;clip: rect(0, 5em, 5em, 2.5em);background-color: #53777A;border-radius: 50%; width: 5em;height: 5em;"></div> <div style="position: absolute; clip: rect(0, 2.5em, 4em, 0); width: 5em; height: 5em; border-radius: 50%; border: 0.45em solid #53777A; box-sizing: border-box; {% if is_pdf %} transform: rotate(324deg); {% else %} transform: rotate(324deg); -webkit-transform: rotate(324deg) translateZ(0); -moz-transform: rotate(324deg); -o-transform: rotate(324deg); -ms-transform: rotate(324deg); {% endif %}"> </div> </div> </div> </body> </html> And after generating the pdf I am not getting the required result. I have also tried wkhtmltopdf with xvfb but did not obtain the desired result. For all of your reference I am also attaching the code to convert …