Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Allowing a single form to update 2 tables at once
I'm having a trouble where I want to use a form to update 2 different tables. My current form have a few variables. Hostname, ipaddr, mgmt, mgmtip etc. What I want to do now is take hostname, ipaddr and add into one table (This one done) and the other 2, mgmt and mgmtip to another table while under the same id. Like for example, hostname and ipaddr is registered under id of 1 (1st row of table 1) and mgmt and mgmtip to table 2 of the same id = 1. I am currently also able to extract the id for the 1st table. But I just cant seem to update the table2 under the same id. Below is my code: def device_add(request): if request.method == "POST": device_frm = DeviceForm(request.POST) ##Part A1 dd_frm = DeviceDetailForm() if device_frm.is_valid(): device_frm.save() ##Part A1 deviceid = Device.objects.aggregate(Max('id')) ##Part A1 - Getting the ID of added device device = Device.objects.all() ##Part A1 if dd_frm.is_valid(): dd_frm.save('id' == deviceid) return render(request, 'interface/device-added.html',{'devices':device}) else: device_frm = DeviceForm() dd_frm = DeviceDetailForm() di_frm = DeviceInterfaceForm() return render(request,'interface/device_add.html',{'form':device_frm, 'dd_form': dd_frm}) -
How to use foreignkey with different models in DJango
I'm stack with this problem, and looking for some solution before asking this question here. Lets say I have a one Model that shares same field in different Models how can I achieve this that when I get the objects of those Models I can include that Model foreign key, I did try to achieve this using Generic Relation in DJango yet it didn't solve my issue. here is the sample what I'm trying to achieve using Generic Relation: Model1(models.Model): .. objects_on_this_model .. Model2(models.Model): .. objects_on_this_model ... # Now this is where the model I could save different models with same field shared SameObjectModel(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntengerField() content_object = GenericForeignKey('content_type', 'object_id') .. objects_on_this_model .. # which is the field that has same field to use in different models So when I try to get the objects from Model(n) how can I achieve or get the SameObjectModel? I have this on my mind that I could do this: Model(n).objects.prefetch_related('fk').all() Seems it is not a good idea, since I do not know where I should put the related_name since the foreign key is the content_type which is the model and there is the object_id represent the field primary_key. -
TypeError when loading MariaDB using Django
DB is trying to be used by calling from a web hosting server. However, an error occurs, and the error is also a TypeError, so I don't know how to solve it. DB version is 10.1.13-MariaDB - MariaDB Server. Python version 3.7(64bit) I'm using only DATABASES of 'setting.py' in Django PS C:\Users\wow\source\repos\ann2> python .\manage.py migrate Traceback (most recent call last): File ".\manage.py", line 22, in <module> main() File ".\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\wow\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", l ine 419, in execute_from_command_line utility.execute() File "C:\Users\wow\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", l ine 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\wow\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\wow\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\wow\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\wow\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\migrat e.py", line 75, in handle self.check(databases=[database]) File "C:\Users\wow\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 423, in check databases=databases, File "C:\Users\wow\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\wow\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\checks\database.py", line 13, in check_database_backends issues.extend(conn.validation.check(**kwargs)) File "C:\Users\wow\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\mysql\validation.py ", line 9, in check issues.extend(self._check_sql_mode(**kwargs)) File "C:\Users\wow\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\mysql\validation.py ", line 13, in _check_sql_mode if not (self.connection.sql_mode & {'STRICT_TRANS_TABLES', 'STRICT_ALL_TABLES'}): File "C:\Users\wow\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\wow\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\mysql\base.py", lin e 406, in sql_mode return set(sql_mode.split(',') if sql_mode else ()) TypeError: a bytes-like object is … -
How to Count the number of distinct keys in a dictionary in django template
The numbers are serial number and the dictionary belongs to that serial number is data. I want to count the length of dictionary belong to distinct serial number in django template. The name of dictionary is redict. {15: [<videoscomment: Reply...byNavneetKaur>, <videoscomment: Reply...byNavneetKaur>], 20: [<videoscomment: 2nd comment reply...byNavneetKaur>]} I have tried the following methods comments.sno is the number and below gets data belong to that number redict|get_val:comments.sno and i put count in the last to get the length of data. redict|get_val:comments.sno.count And remember we have to do that in django template. -
Django views function called inside a render page views function
My goal is to get the form to appear on the screen. Everything works when the image_upload function is called profile. As what it was called before changing the function name (last Stack overflow question). The reason I changed the name was so I could implement other functions easier in the future and so I could understand Full Stack better. One function to render the page and the other to do a task I wanted. If anyone could help that would I would appreciate it. views.py def profile(request): return render(request, "main/profile.html", {}) def image_upload(request): if request.method == "POST": form = User_Profile_Form(request.POST, request.FILES) if form.is_valid(): form.save() obj = form.instance return render(request, "main/profile.html", {"obj":obj}) else: form = User_Profile_Form() img = User_Profile.objects.all() return render(request,"main/profile.html", {"img":img, "form":form}) urls.py urlpatterns = [ path("", views.home, name = "home"), path("profile", views.profile, name = "profile"), path("image_upload", views.image_upload, name = "image_upload"), path("profile_settings", views.profile_settings, name = "profile_settings"), ] profile.html <div class="container"> <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <button type="submit" class="btn btn-lg btn-success">Upload</button> </form> {% if obj %} <h3>Succesfully uploaded : {{img_obj.caption}}</h3> <img src="{{ obj.image.url}}" alt="image" class="img-thumbnail" > {% endif %} <hr> -
How to convert django form to json in python 3
How to convert django form to json The form I want to convert form = WordForm(instance=word) I have tried all of the methods below. serializers.serialize('json', form) error: 'BoundField' object has no attribute '_meta' json.dumps(list(form)), json.dumps(form) error: Object of type BoundField is not JSON serializable And I found this library (https://github.com/WiserTogether/django-remote-forms) through Googling, but python3 is not compatible. How can I convert a django form to json? -
AUTH_USER_MODEL refers to model 'users.CustomUser' that has not been installed
models.py User = get_user_model() class CustomUser(AbstractUser): sign = models.ImageField(upload_to=image_saving) objects = CustomUserManager() this is my models.py I tried to add just an extra field to django User model. setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'django_restful_admin', 'django_jalali', 'm', 'users', ] AUTH_USER_MODEL = 'users.CustomUser' I've added AUTH_USER_MODEL to my setting.py. here is my installed apps. managers.py class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) here is my managers.py ... I wanna add a sign culumn to my User models. -
how read specific line from csv file in django
i am trying to read csv file in django but i dont know how to achieve it, i am fresher recently joined organization and working singly, please any one help me from django.shortcuts import render from django.http import HttpResponse import csv from csv import reader def fun(request): with open(r"C:\Users\Sagar\Downloads\ULB_Sp_ThreePhaseUpdate.csv") as file: reader = csv.reader(file) ip = request.GET["id"] flag = False for rec in reader: if rec[1]=="id": return HttpResponse("MID: ",rec[2]) return render(request, "index.html") -
Django breaking after adding extend and load static tags
so I used template inheritance in django. After I used {% extends 'basic.html' %} {% load static %} the html and css doesnt update. What I mean by that if for example when I change the page title then save and refresh [both by ctrl f5 and ctrl r] it doesnt do anything. The extending works fine but when I use load static first of all it doesn't load it second when I update or add any html its like "I dont care" and doesnt update anything. The code {% extends 'basic.html' %} {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Do</title> </head> <body> <p> Help </p> </body> </html> basic.html <div class="upper"> <p class="blogtitle"> Utsab's Blogs </p> <a href="/" class="homebutton"> Home </a> <a href="blogs" class="blogsbutton"> Blogs </a> <a href="contact" class="contactbutton"> Contact </a> </div> <style> .upper{ background-color: black; height: 40px; position: absolute; top: 0%; left: 0%; right: 0%; } .blogtitle { text-align: center; } .name { text-align: center; font-weight: bolder; font-size: larger; } .text { text-align: center; font-size: large; } .homebutton { font-family: 'Roboto', sans-serif; position: absolute; top: 10px; left: 29%; text-decoration: none; color: azure; } .blogsbutton { position: absolute; left: … -
Best practice of refreshing JWT tokens from mobile and web simultaneously
We are building a customer application. For that, we are using accounting software (ZOHO). Items will be fetched from the accounting software and bills will be generated directly on accounting software using API. API is using JWT for authentication. To generate JWT tokens for each user then is a 'user consent page', which should be manually approved from the web browser. So, for each customer we are not going to register as a user, we are planning to create them as just customers. What we are actually planning to do now, is create one JWT token pair (After manual approval) and use it for all customers for all API calls. My first concern, is that will be a good approach? The second concern, the Token has an expiry of 1 hour. After that, we should use the refresh token to generate the new token. How we can efficiently handle this on the web and mobile (Customers on the web and mobile simultaneously using the same tokens for API calls and the Token change should reflect on all client devices)? Doing this is a good idea? -
Is there any another way to python manage.py crontab run in django server?
i have created a scheduled job in django with django_crontab package. i have added the job. its successfully added but its only get executed whenever i run python manage.py crontab run daeea9e88c171494b1610bdebfasd123 not with runserver command. what might be the issue, this is my view. cron.py file def my_scheduled_job(): file = open('geek.txt','w') now = timezone.now() file.write("This is the write command") file.write("It allows us to write in a particular file") file.write(str(now)) file.close() print(now) return True settings.py CRONTAB_LOCK_JOBS = False CRONTAB_DJANGO_PROJECT_NAME = 'api' CRONTAB_DJANGO_SETTINGS_MODULE = 'api.settings' CRONJOBS = [ ('*/1 * * * *', 'app.cron.my_scheduled_job') ] what i want is its job get executed every minute whenever i run python manage.py runserver. Is there anything missing please help me out. -
How to combine two loops in the same excel page for xlsxwriter
I'd like to add a blank line and some data after items in my model are looped. I tried it out but it cant work as expected. I think I do not know how to grab the last item and put a command to create a blank line and thereafter write the additional data. Here is what I tried. def ExportsView(request): output = io.BytesIO() workbook = xlsxwriter.Workbook(output, {'in_memory': True}) worksheet = workbook.add_worksheet('books') title = workbook.add_format({'bold': True,'font_size': 15,'align': 'center','valign': 'vcenter','border': 1}) header = workbook.add_format({'bold': True,'color': 'black','align': 'left','valign': 'top','border': 1}) boarders = workbook.add_format({'border': 1,'font_size': 8}) student_borrowings = request.session.get('student_borrowings') the_stude = Student.objects.get(school=request.user.school,student_id=student_borrowings) no_of_books = Issue.objects.filter(borrower_id__school_id=request.user.school.id,borrower_id__student_id=student_borrowings).count() all_books = Issue.objects.filter(borrower_id__school=request.user.school,borrower_id_id=the_stude) worksheet.set_landscape() worksheet.center_horizontally() worksheet.set_margins(left=0.25, right=0.25, top=0.75, bottom=0.75) worksheet.merge_range('A1:I1',"ADM: " + str(the_stude).upper() + " - CURRENTLY BORROWED BOOKS: " + ( str(no_of_books)),title) col = 0 #Begins from the first column for index, data in enumerate(all_books): row = 2 + index worksheet.write(row, col, index + 1,boarders) worksheet.write(row, col + 1, data.book_id.book_name,boarders) worksheet.write('A2', 'No', header) worksheet.write('B2', 'Name', header) #Borrowing History ever_borrowed = Issue.deleted_objects.filter(borrower_id__school=request.user.school,borrower_id_id=the_stude) if ever_borrowed.count() > 0: worksheet.merge_range("A1:I1", " ",title) worksheet.merge_range('A1:I1',"RETURNED BOOKS: " + ( str(ever_borrowed.count())),title) for index, data in enumerate(ever_borrowed): worksheet.write(row, col, data.book_id.book_name,boarders) worksheet.write(row, col + 1, data.book_id.reg_no,boarders) row += 1 worksheet.write('A2', 'Name', header) worksheet.write('B2', 'Reg No', header) … -
how do you print a receipt using Star TSP 650 II?
Does anyone know a beginner friendly tutorial for Star TSP 650II (using parallel port) to print something from django/python? I can't seem to figure out how it works. -
Trying to run Django, Redis, Celery and Supervisor on Ubuntu 18.04 but not working
Hi I have made an application where I pull data and display in real time on my website. On local, it works perfectly fine when I run the following: celery -A proj_name beat -l INFO celery -A proj_name worker -l INFO -p gevent I use gevent because I am on Windows. On the Ubuntu server, I do not think I would need that. So now on the server, I have followed the below article to the letter: https://realpython.com/asynchronous-tasks-with-django-and-celery/#running-remotely When I get to the last part: sudo supervisorctl start pichacelery it gives me the following error: bscscanapicelery: ERROR (no such file) These are my files: bscscanapi_celery.conf ; ================================== ; celery worker supervisor example ; ================================== ; the name of your supervisord program [program:bscscanapicelery] ; Set full path to celery program if using virtualenv command=/home/djangoadmin/.virtualenvs/bscscanapi/bin/celery worker -A bscscanapi --loglevel=INFO ; The directory to your Django project directory=/home/djangoadmin/stalker-nichan/bscscanapi ; If supervisord is run as the root user, switch users to this UNIX user account ; before doing any processing. user=djangoadmin ; Supervisor will start as many instances of this program as named by numprocs numprocs=1 ; Put process stdout output in this file stdout_logfile=/var/log/celery/bscscanapi_worker.log ; Put process stderr output in this file stderr_logfile=/var/log/celery/bscscanapi_worker.log … -
Django submit file form won't save to models through front-end
So the goal is to get the user to upload images inside the application, and for the images to be displayed on the screen. The problem is that the forms will not save to the models I made. I am following Django Central https://djangocentral.com/uploading-images-with-django/ for guidance for uploading my images. What I have at the moment is where the user can type inside the form for their caption and where the user can select a file for their image, but nothing happens when they click the upload button. All that happens, is that it redirects me to the homepage for some reason, but I can fix that later. The only way for the images to be displayed on the website is if I manually go into the admin panel and upload the image there. If anyone could help I would much appreciate it. view.py def profile(request): if request.method == "POST": form = User_Profile_Form(data = request.POST, files = request.FILES) if form.is_valid(): form.save() obj = form.instance return render(request, "main/profile.html", {"obj":obj}) else: form = User_Profile_Form() img = User_Profile.objects.all() return render(request,"main/profile.html", {"img":img, "form":form}) models.py class User_Profile(models.Model): caption = models.CharField(max_length = 100) image = models.ImageField(upload_to = "img/%y", blank=True) def __str__(self): return self.caption forms.py from django … -
Django: redirecting to an external URL stored in the dB
I'm building a Django application. My end goal is for the user to be able to click a link to be redirected to an external site. Here's my code: models.py class Entry(models.Model): manufacturer = models.CharField(max_length=255) source_url = models.URLField(blank=True) views.py def purchase(request, entry_id): entry = get_object_or_404(Entry, pk=entry_id) return redirect(entry.source_url) entries.html {% if user.is_authenticated %} <a href="{% url 'purchase' %}">Purchase!</a> {% endif %} urls.py urlpatterns = [ path('', views.index, name='index'), path('entries/<int:entry_id>', views.entry, name='entry'), ] The data in the database looks as follows: id manufacturer source_url 1 Mercedes https://www.mbusa.com/en/home 2 BMW https://www.bmw.com/en/index.html 3 Audi https://www.audiusa.com/us/web/en.html The error message I'm getting is: Exception Value: Reverse for 'purchase' not found. 'purchase' is not a valid view function or pattern name. As a test, I changed the following line of code: From: <a href="{% url 'purchase' %}">Go to Source!</a> To: <a href="www.google.com">Go to Source!</a> This eliminated the "reverse" error, but the URL that it created was: http://127.0.0.1:8000/entries/www.google.com Is the "reverse" error caused by the lack of a URL route for "purchase" in urls.py? If yes, how would I define this? Thanks in advance for helping this Django newbie! -
Basic Question - Django Database PostgreSQL shuts down after pgAdmin app is closed
I am an absolute beginner with Django and have been trying to learn. I am currently stuck on one thing. I have a Django app that runs with PostgresSQL. I use Amazon RDS to host my database. It works just fine. I understand that I need to have the inbound rules set to my IP address. However, when I close the pgAdmin app on my computer (mac) the database shuts down. I can't run the django app anywore with the following error: Is the server running on host "XXX.cds3kvmdaz5k.us-east-2.rds.amazonaws.com" (3.141.229.116) and accepting TCP/IP connections on port 5432? Is there any way to not have the pgAdmin app open and still run the project? I know its a dumb question, but there has to be a way consdering in production it should not run based off of one computer running an app or not. -
Django MPTT how to remove indentation from html template
I am using django MPTT model in my template and just want to remove indentation. Now it's look like this: how to remove indentation from html template? here is my html: {% load mptt_tags %} {% recursetree contact %} {{node.message}} {% if not node.is_leaf_node %} <div class="children pl-2 pl-md-5"> {{ children }} {% endif %} {% endrecursetree %} -
How to parametrize a test's django settings?
Normally when you want to override settings for a test you can do with self.settings(API_KEY=None): To run that test with API_KEY unset. I'm trying to parametrize a pytest to check that certain settings have been set: @pytest.mark.parametrize('blank_setting', [API_KEY_1, API_KEY2]) def test_improperly_configured(self, client, blank_setting): with self.settings(blank_setting=None): response = client.get(reverse('api:info')) assert response.status_code == 500 But of course it says name 'API_KEY_1' is not defined Is it possible to parametrize settings this way? -
Implement webhook in Django
I have never implemented a webhook before. I am working on a payment confirmation, where I need to know if a payment is successful and if it is the client should be redirected to payment complete site. Below is the view for the checkout page class Payment(View): def __init__(self): #Get model webshopRestaurant data for hd2900 restaurant for location id for this restaurant self.hd2900RestaurantObject = RestaurantUtils(restaurantName = restaurantName) def get(self, request, *args, **kwargs): #Check if session is still valid sessionValid = webshopUtils.checkSessionIdValidity(request = request, session_id_key = session_id_key, validPeriodInDays = self.hd2900RestaurantObject.restaurantModelData.session_valid_time) #In this case the session has expired and the user will be redirected if sessionValid is False: return redirect('hd2900_takeaway_webshop') if 'pickupForm' in request.GET: deliveryType ='pickup' elif 'deliveryForm' in request.GET: deliveryType = 'delivery' elif ('deliveryForm' not in request.GET) and ('pickupForm' not in request.GET): #Here is where I need to implement the webhook pass #Write the customer info into the data base webshopUtils.create_or_update_Order(session_id_key=session_id_key, request=request, deliveryType = deliveryType) #Calculate the total price followed by creation of paymentID from NETS if 'pickupForm' in request.GET: totalPrice = webshopUtils.get_BasketTotalPrice(request.session[session_id_key]) + self.hd2900RestaurantObject.restaurantModelData.bagFee elif 'deliveryForm' in request.GET: totalPrice = webshopUtils.get_BasketTotalPrice(request.session[session_id_key]) + self.hd2900RestaurantObject.restaurantModelData.delivery_fee + self.hd2900RestaurantObject.restaurantModelData.bagFee #Create an order reference and link that to NETS reference reference = webshopUtils.get_order_reference(request = request, … -
Project file window is yellow in pycharm
I'm working with pycharm 2019 and django, in win 10 in a project that I haven't opened in a year. The Project files window is showing up as yellow, which seems new. What does this mean and how to I get the files to appear as white. -
How to implement multichat in Django channels
I am implementing a real-time chat functionality using Django channels 3 and Django rest framework, where I have two types of users clients and admins , what I am trying to do is to create for every user a chat room in order to discuss with the admins, I tried to use multiple rooms and it doesn't work because the admin is unaware of the newly created user room , my second choice is to use room_group_name , but so far I don't really understand it, if someone can clarify or help I would be grateful . Consumer.py async def connect(self): self.user = self.scope["user"] print(self.user.is_superuser) print(self.user.is_staff) if self.user.is_superuser: self.room_name = "chat" self.room_group_name = 'admin_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() if self.user.is_client: self.room_name = "chat" self.room_group_name = 'client_%s'.format(self.user) % self.room_name admin = 'admin_%s' % self.room_name await self.channel_layer.group_add( # self.room_group_name, self.room_group_name, self.channel_name ) await self.accept() So far I can separate the two groups, but the trick is how to add admin users to the client group room ?? -
Can you limit the records count for each user Django
Can you set a database constraint to allow the users to add only a specific amount of records that have the a specific value field? Example: class Example(models.Model): CHOICES = ( ('1', '1'), ('2', '2'), ('3', '3'), ) user = models.ForeignKey(User) choice = models.Charfield(choices=CHOICES) I want to allow each user to be able to add only 4 records with choice 3, is there a current way to do it at the database level? -
I need to do a function that calculates the item prices dynamically without storing them in the database django
I need to do a function which calculates the prices of the items dynamically without storing them in the database because the prices of the items change daily, I have scratched the price of the day and I need the items to be calculated based on this price models.py class Product(models.Model): prdct_name = models.CharField(max_length=17, verbose_name=_("Article ")) prdct_category = models.ForeignKey("Category", on_delete=models.CASCADE, blank=True, null=True) prdct_description = models.TextField(verbose_name=_("Description")) prdct_img = models.ImageField(upload_to='product/',verbose_name=_("Image"), blank=True, null=True) # prdct_img prdct_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name=_("Prix ")) prdct_cost = models.DecimalField(max_digits=10, decimal_places=2, verbose_name=_("Prix promotionel ")) prdct_weight = models.DecimalField(max_digits=10, decimal_places=2, verbose_name=_("Poid ")) prdct_created = models.DateTimeField(auto_now=False, auto_now_add=False, verbose_name=_("Date Creation ")) prdct_genre = models.CharField(max_length=50, verbose_name=_("Genre ")) prdct_matiere = models.CharField(max_length=50, verbose_name=_("Matiere ")) prdct_titrage = models.CharField(max_length=50, verbose_name=_("titrage ")) prdct_in_stock = models.BooleanField(verbose_name=_("in_stock ")) prdct_slug = models.SlugField(blank=True, null=True) the function to scrape the price from the site def get_prixmatiere(): # get price from cpor import requests from bs4 import BeautifulSoup response = requests.get("https://www.gold.fr/cours-or-prix-de-l-or/") soup = BeautifulSoup(response.text , 'lxml') product_price = soup.find_all("td",{"class" : "price"})[0].text.replace('€', '').replace(' ', '') # calculate price prixdug = float(product_price) / 4 * 3 / 1000 * 210 - 500 prixmatiere = float(product_price) / 4 * 3 / 1000 * 210 return prixmatiere i need to get the price of the item def calc_price_item(self): self.dailyprice … -
Python convert text of SVG to PNG without Cairo
I have been working for about 20+ hours and I'm stuck. I have a Django app deployed on azure web apps. In one of my django views, I was able to successfully convert an svg to png on my local device with Cairo, however, Cairo requires homebrew to execute brew install pango. As such, Cairo is completely out of the picture to convert SVG to PNG. I also looked into using svglib and running from svglib.svglib import svg2rlg, however svg2rlg(input) requires input to be the name of a file. Because I'm using Django and I'm running a webapp, I certainly want to avoid creating files. How would one go about converting svg to png without cairo. Can I somehow input text, something like string="""<?xml version="1.0" standalone="no"?> <svg width="200" height="250" version="1.1" xmlns="http://www.w3.org/2000/svg"> <line x1="10" x2="50" y1="110" y2="150" stroke="orange" stroke-width="5"/> <polyline points="60 110 65 120 70 115 75 130 80 125 85 140 90 135 95 150 100 145" stroke="orange" fill="transparent" stroke-width="5"/> </svg>""" into svg2rlg? Can I simply download the Cairo library to the Django project folder?