Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django {% url %} template looping
my url.py app_name="application_name" urlpatterns=[ url(r"^staff/",include('application_name.staff_url', namespace='staff')), url(r"^customer/",include('application_name.customer_url', namespace='customer')), ] staff_url.py from application_name import views app_name="staff" urlpatterns=[ url(r"^customers/",views.customers, name='customers'), url(r"^orders/$", views.orders, name='orders'), url(r"^payments/$", views.payments, name='payments'), ] customer_url.py from application_name import views app_name="customer" urlpatterns=[ url(r"^items/",views.items, name='items'), url(r"^checkout/$", views.checkout, name='checkout'), url(r"^make_payment/$", views.make_payment, name='make_payment'), ] staf url would be staff/orders or staff/payments customer urls would be customer/items or customer/checkout etc In my view file I have put every link inside a list which would be iterated inside the template and placed it inside a session This is my view.py staffLink=[ {'linkfield':"customers", 'name':"Customers",'slug':"staff"}, {'linkfield':"orders", 'name':"Orders",'slug':"staff"}, {'linkfield':"payments", 'name':"payments",'slug':"staff"}] links=staffLink request.session['links']= links request.session['sub']= 'staff' context_dict = {'links':links} This is my html template {% for link in request.session.links %} {% if request.session.sub =="staff" %} <a href="{% url 'application_name:staff' link.linkfield as the_url %}" class="nav-link"> {% elif request.session.sub =="customer" %} <a href="{% url 'application_name:customer' link.linkfield as the_url %}" class="nav-link"> {% endif %} {% endfor %} Pl This are the following result When I include the if statement i.e. {% if request.session.sub =="staff" %}. The following error is produced django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '=="staff"' from '=="staff"' When I exclude the if statement so making it just <a href="{% url 'application_name:staff' link.linkfield as the_url %}" class="nav-link"> I did this for … -
Django Paypal: How To Cancel Subscription From View
I am trying to cancel a subscription from the view but when i view the response all i get is namemessagedebug_iddetailslinks on the page. i used the docs (search for cancel subscription) to send this api call. if i view the source of the response i get TIMESTAMP=2021%2d06%2d23T00%3a45%3a18Z&CORRELATIONID=bce3e4b335473&ACK=Failure&VERSION=86&BUILD=55100925&L_ERRORCODE0=10002&L_SHORTMESSAGE0=Security%20error&L_LONGMESSAGE0=Security%20header%20is%20not%20valid&L_SEVERITYCODE0=Error views.py: def manage_subs(request): header_params = { "Accept": "application/json", "Accept-Language": "en_US", } param = { "grant_type": "client_credentials", } cid = settings.PAYPAL_CLIENT_ID secret = settings.PAYPAL_CLIENT_SECRET token_i = requests.post('https://api-m.sandbox.paypal.com/v1/oauth2/token', auth=(cid, secret), headers=header_params, data=param).json() token = token_i["access_token"] bearer_token = 'Bearer x'.replace('x', token) headers = { 'Content-Type': 'application/json', 'Authorization': bearer_token, } p = { 'reason': "Not satisfied with the service" } url = 'https://api-m.sandbox.paypal.com/v1/billing/subscriptions/*/cancel' # * is replaced with the subscription_id response = requests.post(url, headers=headers, data=p).json() return HttpResponse(response) -
Django models subtraction issue
class Finances(models.Model): student_id = models.ForeignKey(Student, on_delete=models.CASCADE) student_name = models.CharField(max_length=100, default={Student.student_name}) total_fees = models.IntegerField(default=3500) paid_amount = models.IntegerField(default=0) balance = total_fees - paid_amount balance_fees = models.IntegerField({balance}) I need the balance_fees model to hold the value of a subtraction of total_fees - paid_amount which is held by the balance. I get an error when making migrations 'TypeError: unsupported operand type(s) for -: 'IntegerField' and 'IntegerField' How can I resolve this? -
Displaying Django Models data in html file
I want to display data taken from my Django models in my html file. So in the code bellow instead of a 0 I want the donation model data. Can someone please help? Thank you! Model.py class userdetails(models.Model): donations = models.IntegerField(blank=True, null = True,) points = models.IntegerField(blank=True, null = True,) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, ) HTML: <div class="box"> <span class="value">0</span> <span class="parameter">Donations</span> </div> -
User signup system in Django with custom fields
I am trying to make a user Signup system along with his profile. my models.py: class myCustomeUser(AbstractUser): username = models.CharField(max_length=50, unique="True", blank=False) password = models.CharField(max_length=200, blank=False) USERNAME_FIELD = 'username' class Profile(models.Model): user = models.OneToOneField(myCustomeUser, null=True, on_delete=models.CASCADE) bio = models.TextField() profile_pic = models.ImageField(null=True, blank=True, upload_to="images/profile/") my forms.py: class SignUpForm(ModelForm): class Meta: model = Profile fields = '__all__' my views.py: class index(generic.CreateView): form_class = SignUpForm template_name = 'index.html' Now here my problem is, the form gives me an option to choose any user (with dropdown) to create a profile.... but I want to create a user also on that page (not pick an option from dropdown). How can I try for that? -
Missing Python.h file for mod_wsgi
I am following some instruction here to install apache2 and mod_wsgi in order to host Django app. At the step: git clone https://github.com/GrahamDumpleton/mod_wsgi.git ./configure --with-python=/path/to/your/python/exec make The make command gives the following error message: src/server/wsgi_python.h:26:10: fatal error: Python.h: No such file or directory #include <Python.h> What is the this Python.h file and where should I get it from? This thread discusses similar issue of missing Python.h file. I am using Ubuntu and have already installed both : sudo apt-get install python-dev sudo apt-get install python3-dev Reading package lists... Done Building dependency tree Reading state information... Done python3-dev is already the newest version (3.6.7-1~18.04). 0 upgraded, 0 newly installed, 0 to remove and 16 not upgraded. Reading package lists... Done Building dependency tree Reading state information... Done python-dev is already the newest version (2.7.15~rc1-1). 0 upgraded, 0 newly installed, 0 to remove and 16 not upgraded. What is missing still? -
Why will my django website not load correctly with runserver?
Urgent! I am currently working on a django project. One moment my local server, that I ran using "python manage.py runserver", was working fine, I messed around a little with the bootstrap classes, and now, the page is forever loading, nothing is clickable (left-click or right-click), and I can't even open up developer tools. I have tried the following: Restart the server Restart VSCode Try different browser Restart browser Restart computer Clear browser cache (because why not) Tried opening in a private browser (to avoid extensions) Nothing seems to work. I'm not getting any errors in the terminal. What's going on? -
type object 'Profile' has no attribute 'USERNAME_FIELD'
I am building a custom User class in django to use in creating a signup application and I keep on getting the error above every time I try to run the code. my models.py: class myCustomeUser(AbstractUser): username = models.CharField(max_length=50, unique="True", blank=False) password = models.CharField(max_length=200, blank=False) USERNAME_FIELD = 'username' def __str__(self): return self.username class Profile(models.Model): user = models.OneToOneField(myCustomeUser, null=True, on_delete=models.CASCADE) bio = models.TextField() profile_pic = models.ImageField(null=True, blank=True, upload_to="images/profile/") facebook_url = models.CharField(null=True, blank=True, max_length=255) twitter_url = models.CharField(null=True, blank=True, max_length=255) instagram_url = models.CharField(null=True, blank=True, max_length=255) linkdin_url = models.CharField(null=True, blank=True, max_length=255) def __str__(self): return str(self.user) my forms.py: class SignUpForm(UserCreationForm): class Meta: model = Profile fields = '__all__' in views.py: class index(generic.CreateView): form_class = SignUpForm template_name = 'index.html' It says following error after run the code: AttributeError at / type object 'Profile' has no attribute 'USERNAME_FIELD' Kindly suggest how can I fix it? -
Missing Python.h in mod_wsgi to host Django app [duplicate]
I am following some instruction here to install apache2 and mod_wsgi in order to host Django app. At the step: git clone https://github.com/GrahamDumpleton/mod_wsgi.git ./configure --with-python=/path/to/your/python/exec make The make command gives the following error message: src/server/wsgi_python.h:26:10: fatal error: Python.h: No such file or directory #include <Python.h> What is the this Python.h file and where should I get it from? -
Django form not working once I change URL's
Very new to Django, but have followed a tutorial to create a SQLite3 DB which is added to and updated from forms on various html pages. Once I try to change the URL's involved from path('',include('members.urls')), to path('members/',include('members.urls')), issues arise. The submit button for changing the entries for the database keeps POST'ing to "127.0.0.1:8000/update/1" instead of "127.0.0.1:8000/members/update/1" Here is what I think might be relevant code in case someone can help out? Project urls.py urlpatterns = [ path('admin/', admin.site.urls), path('members/',include('members.urls')), path('',include("django.contrib.auth.urls")) ] Members views.py def update(request,id): if request.method=='POST': time=request.POST['time'] player1=request.POST['player1'] player2=request.POST['player2'] player3=request.POST['player3'] Post.objects.filter(id=id).update(time=time,player1=player1,player2=player2,player3=player3) messages.success(request,'Data has been updated') post=Post.objects.get(id=id) return render(request,'update.html',{'post':post}) Members urls.py urlpatterns = [ path('',views.home,name='home'), path('teetimes/',views.teetimes,name='teetimes'), path('add/',views.add,name='add'), path('update/<int:id>',views.update,name='update') ] Members teetimes.html <h3>All Times</h3> {% for post in posts %} <div> <table class="table table-bordered"> <th><h5>{{post.time}} <br> <a href="/update/{{post.id}}" class="btn-sm btn-success">Update</a></h5></th> <th><h6>{{post.player1}}</h6></th> <th><h6>{{post.player2}}</h6></th> <th><h6>{{post.player3}}</h6></th> </table> </div> {% endfor %} Members update.html % if messages %} {% for msg in messages %} <p class="text-success">{{msg}}</p> {% endfor %} {% endif %} <form method="post" action="/update/{{post.id}}"> {% csrf_token %} <table class="table table-bordered"> <tr> <th>Time</th> <td> <input value="{{post.time}}" type="text" name="time" class="form-control"> </td> </tr> <tr> <th>Player 1</th> <td> <input value="{{post.player1}}" type="text" name="player1" class="form-control"> </td> </tr> <tr> <th>Player 2</th> <td> <input value="{{post.player2}}" type="text" name="player2" class="form-control"> </td> </tr> <tr> … -
How can I filter using uuid of Foreign Key in Django?
I have three tables Token, Auth, UserProfile class Token(models.Model): token = models.CharField(primary_key=True, max_length=255, default=uuid.uuid4().__str__()) auth = models.ForeignKey(Auth, models.DO_NOTHING, blank=True, null=True) class Auth(models.Model): id = models.UUIDField(primary_key = True, default = uuid.uuid4, editable = False) password = models.CharField(max_length=255, blank=True, null=True) user_id = models.CharField(unique=True, max_length=255) role = models.CharField(max_length=255, blank=True, null=True) source = models.CharField(max_length=255, blank=True, null=True) class UserProfile(models.Model): id = models.UUIDField(primary_key = True, default = uuid.uuid4, editable = False) name = models.CharField(max_length=255, blank=True, null=True) phone_number = models.CharField(max_length=255, blank=True, null=True) auth = models.ForeignKey(Auth, models.DO_NOTHING) How can I get UserProfile as I have Token class's object I tried user = UserProfile.objects.get(auth=token.auth) which gives me the error UserProfile matching query does not exist. -
How to use middleware for group route in django like in Laravel?
I am a Laravel developer. I am building web site using Django. I have a problem in development with Django. Route::group(['middleware' => ['checkEAdmin']], function () { Route::post(....); Route::post(....); Route::post(....); Route::post(....); Route::post(....); }); I used middleware for group routes. how can I use middelware in django like this? please help me Thank you. -
Django channels in docker compose error `not found: /ws/`?
When I access ws://domain.com/ws/ from my machine it runs just fine but when I try to access it from docker- compose upI got that error not found: /ws/ I tried to change host configuration in channels layers in the settings but nothing changed also i tried to change refis and Channels versions -
Django, sending email
I'm trying to make a feedback form on my site. my settings.py DEFAULT_FROM_EMAIL = '****@****.**' EMAIL_HOST = '*****' EMAIL_PORT = 465 EMAIL_HOST_USER = DEFAULT_FROM_EMAIL EMAIL_HOST_PASSWORD = '********' EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' my form is simple and I don't thing that mistake is in that file, but I think I should show it my forms.py: class SuggestionForm(forms.Form): email = forms.EmailField(label='', initial='Ваш Email', required=True) subject = forms.CharField(label='', initial='Тема вашего сообщения', required=True) message = forms.CharField(label='', initial='Сообщение для администрации сайта', widget=forms.Textarea, required=True) and my views.py def suggestion_view(request): if request.method == 'GET': form = SuggestionForm() elif request.method == 'POST': form = SuggestionForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] email = form.cleaned_data['email'] mess = form.cleaned_data['message'] try: send_mail(subject=f'{subject} от {email}', message=mess, from_email=DEFAULT_FROM_EMAIL, recipient_list=['saw.danil@yandex.ru'], fail_silently=False, auth_user=DEFAULT_FROM_EMAIL, auth_password=EMAIL_HOST_PASSWORD) except BadHeaderError: return HttpResponse('Ошибка в теме письма') return redirect('success') else: return HttpResponse('Неверный запрос') return render(request, 'main/suggestion.html', {'form': form}) I have no idea why this is not working and I'll be grateful for any help. -
Working with formulas in Django using Javascript
I am getting the formula from a csv file. Suppose, the formula is score = x * 5 + y. Now I'm getting x and y value from the user. Any idea how should i proceed? I want to calculate the score. I'm using Django framework and want to calculate the score using JS. -
How to split a menu within a wagtail model?
I'm trying to create a navigation menu, that when the number of objects within the menu is even puts an image between the two halves of the menu. Here is the code that I tried to use within my menu model and templates to create the effect. """Splitting the menu in half for the frontend.""" @property def is_even(self): if (self.objects.count() % 2) == 0: return True else: return False @property def find_halves(self): first_half = self.objects[0:self.objects.count()/2] second_half = self.objects[self.objects.count()/2:self.objects.count()] return first_half, second_half <nav class="main-nav"> {% image navigation.logo fill-115x115 as logo %} <ul class="nav-links"> {% if navigation.is_even %} {% for item in navigation.menu_items.first_half.all %} <li><a href="{{ item.link }}" {% if item.open_in_new_tab %} target="_blank" {% endif %}>{{ item.title }}</a></li> {% endfor %} <img src="{{ logo.url }}" alt="CCCR Logo" class="logo"> {% for item in navigation.menu_items.second_half.all %} <li><a href="{{ item.link }}" {% if item.open_in_new_tab %} target="_blank" {% endif %}>{{ item.title }}</a></li> {% endfor %} {% else %} <img src="{{ logo.url }}" alt="CCCR Logo" class="logo"> {% for item in navigation.menu_items.all %} <li><a href="{{ item.link }}" {% if item.open_in_new_tab %} target="_blank" {% endif %}>{{ item.title }}</a></li> {% endfor %} {% endif %} </ul> </nav> However, when I run the code it goes to the else statement even … -
How to inject HTML code with static file reference to Django template
I have a simple use case in which I need to dynamically add rows to a table in my HTML template. I am using the following javascript code to add this on a button click: function add_row(){ row_html = '<tr><td><img src="path/to/my/file.png"></td></tr>' $('#table-id').append(row_html); } The only problem is that the image is not being found. I have also tried using Django template language, doesn't work. One solution is defining the src in the script tag in my HTML template like in this question. However I am not sure this is the optimal approach. What is the correct approach to solve this problem? -
No module named 'asgiref.base_layer'
When starting my server (python manage.py run server) I get the following error. File "/Users/thomasallen/PycharmProjects/Channels_and_Signals/venv/lib/python3.9/site-packages/asgi_redis/core.py", line 19, in from asgiref.base_layer import BaseChannelLayer ModuleNotFoundError: No module named 'asgiref.base_layer' The offending line 19 in .../core.py is from asgiref.base_layer import BaseChannelLayer The packages I have installed are: Django 3.2.4 channels 3.0.3 channels-redid 3.2.0 aspired 3.3.4 asgi-redis 1.1.0 I'm not sure where the mismatch is. -
UpdateView not filling datalists html input and other fields
please i need you help. I have an UpdateView wich update every field correctly except that field that are filled via "datalist" html5, like "cliente", "fecha" and "isin". the question is, ¿how can i fill that information like the others fields?.what do i am doing wrong? Could you give me some guide about that? thanks in advance! views.py class ordenes_updatea_orden(UpdateView): model = rfi_tsox form_class = IngresoOrdenesRFIModelForm template_name = template_name = 'ordenes/rfi-ingreso-ordenes-modelform.html' success_url = reverse_lazy('listado_ordenes') Modelform class IngresoOrdenesRFIModelForm(ModelForm): def __init__(self,*args, **kwargs): super(IngresoOrdenesRFIModelForm,self).__init__(*args, **kwargs) self.fields['fecha_ingreso'].widget.attrs = {'class':'form-control','type':'date'} self.fields['orden_tipo'].widget.attrs = {'class':'form-control'} self.fields['nominales'].widget.attrs = {'class':'form-control'} self.fields['precio'].widget.attrs = {'class':'form-control'} self.fields['papel'].widget.attrs = {'class':'form-control'} self.fields['rating'].widget.attrs = {'class':'form-control'} self.fields['duracion'].widget.attrs = {'class':'form-control'} self.fields['payment_rank'].widget.attrs = {'class':'form-control'} self.fields['ytm'].widget.attrs = {'class':'form-control'} self.fields['sector'].widget.attrs = {'class':'form-control'} self.fields['notas'].widget.attrs = {'class':'form-control'} self.fields['pais'].widget.attrs = {'class':'form-control'} self.fields['sector'].widget.attrs = {'class':'form-control'} self.fields['cliente'].widget.attrs = {'class':'form-control'} cliente = forms.ChoiceField(choices = [(x.fondo,x.fondo) for x in clientes_rfi.objects.all()]) fecha_ingreso = forms.DateField(widget=forms.DateInput(attrs={'class':'form-control','type':'date'}),initial = datetime.date.today) orden_tipo = forms.ChoiceField(choices = [('cliente compra','cliente compra'),('cliente vende','cliente vende')]) isin = forms.ChoiceField(choices=listado_isin(),required=False) papel = forms.CharField(required=False) rating = forms.MultipleChoiceField(choices = [('Todos','Todos'),('IG','IG'),('HY','HY')],initial='Todos',required=False) duracion = forms.MultipleChoiceField(choices=[('Toda la curva','Toda la curva'),('x<=3','x<=3'),('3<x<=5','3<x<=5'),('x>5','x>5')],initial='Toda la curva',required=False) nominales = forms.CharField(required=False) sector = forms.MultipleChoiceField(choices=lista_sector(),initial='Todos',required=False) precio = forms.CharField(required=False) payment_rank = forms.MultipleChoiceField(choices=lista_paymentRank(),initial='Todos',required=False) ytm = forms.MultipleChoiceField(choices=[('Todos','Todos'),('0 a 100','0 a 100'),('101 a 200','101 a 200'),('201 a 300','201 a 300'),('301 a 400','301 a 400'),('sobre 400','sobre 400')],initial='Todos',required=False) … -
Error when hiding django secret_key in miniconda environment
I'm a total newbie and I'm trying to do this project this is my first time, and it's almost done. I tried every method mentioned in this SO thread to move secret key from settings. In every method i got some kind of error, even from this official django doc mathod. I couldn't find where I'm making mistake. When the secret key is inside the settings.py, everything is working super smooth. But I need to push my code in git, so i have to hide it from settings.py. Right now im adding the details when i tried using django-environ, to keep secret key outside of settings.py. im putting the contents inside the root project folder. im using miniconda: 4.10.1. here is my requirement.txt. # platform: linux-64 _libgcc_mutex=0.1=main _openmp_mutex=4.5=1_gnu appdirs=1.4.4=py_0 asgiref=3.3.4=pyhd3eb1b0_0 attrs=21.2.0=pyhd3eb1b0_0 black=19.10b0=py_0 ca-certificates=2021.5.30=ha878542_0 certifi=2021.5.30=py39hf3d152e_0 click=8.0.1=pyhd3eb1b0_0 django=3.2.4=pyhd3eb1b0_0 django-environ=0.4.5=py_1 importlib-metadata=3.10.0=py39h06a4308_0 krb5=1.17.1=h173b8e3_0 ld_impl_linux-64=2.35.1=h7274673_9 libedit=3.1.20210216=h27cfd23_1 libffi=3.3=he6710b0_2 libgcc-ng=9.3.0=h5101ec6_17 libgomp=9.3.0=h5101ec6_17 libpq=12.2=h20c2e04_0 libstdcxx-ng=9.3.0=hd4cf53a_17 mypy_extensions=0.4.1=py39h06a4308_0 ncurses=6.2=he6710b0_1 openssl=1.1.1k=h7f98852_0 pathspec=0.7.0=py_0 pip=21.1.2=py39h06a4308_0 psycopg2=2.8.6=py39h3c74f83_1 python=3.9.5=h12debd9_4 python_abi=3.9=1_cp39 pytz=2021.1=pyhd3eb1b0_0 readline=8.1=h27cfd23_0 regex=2021.4.4=py39h27cfd23_0 setuptools=52.0.0=py39h06a4308_0 six=1.16.0=pyh6c4a22f_0 sqlite=3.35.4=hdfb4753_0 sqlparse=0.4.1=py_0 tk=8.6.10=hbc83047_0 toml=0.10.2=pyhd3eb1b0_0 typed-ast=1.4.2=py39h27cfd23_1 typing_extensions=3.7.4.3=pyha847dfd_0 tzdata=2020f=h52ac0ba_0 wheel=0.36.2=pyhd3eb1b0_0 xz=5.2.5=h7b6447c_0 zipp=3.4.1=pyhd3eb1b0_0 zlib=1.2.11=h7b6447c_3 settings.py import os import environ from pathlib import Path env = environ.Env( # set casting, default value DEBUG=(bool, False) ) # reading .env file environ.Env.read_env() # Build paths inside the … -
Custom, user-definable "wildcard" constants in SQL database search -- possible?
My client is making database searches using a django webapp that I've written. The query sends a regex search to the database and outputs the results. Because the regex searches can be pretty long and unintuitive, the client has asked for certain custom "wildcards" to be created for the regex searches. For example. Ω := [^aeiou] (all non-vowels) etc. This could be achieved with a simple permanent string substitution in the query, something like query = query.replace("Ω", "[^aeiou]") for all the elements in the substitution list. This seems like it should be safe, but I'm not really sure. He has also asked that it be possible for the user to define custom wildcards for their searches on the fly. So that there would be some other input box where a user could define ∫ := some other regex And to store them you might create a model class RegexWildcard(models.Model): symbol = ... replacement = ... I'm personally a bit wary of this, because it does not seem to add a whole lot of functionality, but does seem to add a lot of complexity and potential problems to the code. Clients can now write their queries to a db. Can they … -
'SafeString' object has no attribute 'get'
I want to render string to a template and I think I misunderstand something. Here is my code : context = { 'order': order, 'ordered_items': ordered_items, 'change': change, } return render_to_string('order/receipt.html', context) And I use them like this: <div id="capture"> <div class="print_container"> <h3>Market Name</h3> <span>---------------------------------------</span> <br> <span>Order number: {{ order.code }} </span> <br> <br> <span>Order time: {{ order.created }}</span> <br> <br> <span>Cashier: {{ order.waiter }}</span> <br> <span>---------------------------------------</span> <div class="section4"> <div> <table> <thead> <tr> <th width="110">Product name</th> <th width="80">Unit price</th> <th width="30">Quantity</th> </tr> </thead> <tbody> {% for item in ordered_items %} <tr> <td>{{ item.food.title.tm }}</td> <td>{{ item.food_size.price }}</td> <td>{{ item.quantity }}</td> </tr> {% endfor %} </tbody> </table> </div> <br> <span>---------------------------------------</span> <br> <div class="total"> <span>Total : {{ order.total_cost }}</span> <br><br> <span>Paid : {{ order.paid }} </span> <br><br> <span>Change : {{ change }} </span> </div> <br> <span>---------------------------------------</span> </div> <div class="section5"> <span>Thank you for your patronage! </span> </div> </div> </div> I'm going to use this html template to print a receipt via thermal printer. And also I want to know more about render_to_string method, I read the docs but can't understand well. -
Byte Range Request: Flask vs Django - HTML Video not showing on Iphone
The web server I am using is PythonAnywhere. They do not support byte range requests, so my video is not showing up on the Iphone when using Django. Their recommendation is to go through AWS (Amazon S3), by hosting the videos there (they support byte range requests). I am only looking to serve static video files, and they said that if that is the case, there is a workaround with Flask, so that the video could be hosted by PythonAnywhere and not routed to AWS. It has to do with HTTP 206 (Partial Content) request. My question is, why can Flask do this but Django cannot? Am I missing something? -
How to save an image from my DOM to backend in django?
I am building a web app using django, now one part of it is a small image editor which i created using Fabric.js, in which the user can upload an image(completely js code, not connected with the backend), and do some editing, and upload the resulting image, only thus time, it has to be stored in my MEDIA of django app, i just have no idea how to get the last step done, i.e., how do i get an image which is available only in my DOM(document object model) at that instance and save it to my backend -
how to write svg code to a file and save It in media folder in Django?
I have a function that generates a barcode as svg code. I need to display this svg in an HTML PDF template. but unfortunately inline svg doesn't work. so as a workaround I need to write this code into a file and save it in the media folder so I can access it by tag in the HTML PDF template. Below is the function that generates the barcode: def barcode_number(self): number = self.get_real_instance().number svg_code = generate('code39', str(number).zfill(20), pil=True) code = svg_code.decode("utf-8") ## here I want to write code into barcode.svg file safe_html = mark_safe(svg_code) return safe_html How can I write this code to a svg file and save it in '/media/uploads' ? Thank you