Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Scoped Styling in Django
My base.html ... <body> {% include 'parts/navbar.html' %} <div>This is the base content html file</div> {% block content %} {% endblock %} {% include 'parts/footer.html' %} </body> ... my navbar: <div>NAV</div> my footer: <div>Footer</div> <style> div { color: blueviolet; } </style> The footer style applies also to the nav-div which i don't want. Is scoped styling in Django possible or do i have to use line-styles or some engine etc. -
Try to host a website usigh Python and Django
I create a website using Django , Python ,Redux .This website I wanna to host on a domain that I bought for this project.Now , I am kinda new and I do not understand why I ca not upload the files for this website via my host provider. I understand that I am rlly dump , but I wanna to understand why and how to host this website.In localhost:800 all work great. Code for this website:enter link description here (repository on github) -
Django creates an extra unwanted entry in many-2-many intermediate table
I have a many-2-many relationship between Flight and Passenger. When I try to assign a passenger to a flight object, Django seems to add an extra entry to the intermediate table. Here are the models: class Passenger(models.Model): name = models.CharField(max_length=30) age = models.IntegerField() class Flight(models.Model): time = models.DateTimeField('flight time') destination = models.CharField(max_length=20) passengers = models.ManyToManyField( to=Passenger, symmetrical=True, related_name='flights', blank=True, ) Say the intermediate table looks like this, with passenger Say flight_object is a Flight with ID=1, and passenger_object is a Passenger with ID=2, when I run flight_object.passengers.add(passenger_object) Django adds 2 entries to the intermediate table in the database. The table now looks like this: Both entries with ID=1 and 2 should be there, but 3 is incorrect, and the flight_id foreign key is for a completely different flight! -
Why does stunnel keep throwing "Address already in use (48)"?
I am working in implementing Auth0 in a Django project, using stunnel to create the https connection. I followed this instruction This is my dev_https file: pid= cert = stunnel/stunnel.pem foreground = yes output = stunnel.log [https] accept=8080 connect=8000 TIMEOUTclose=1 However, when want to start the server, using this command: stunnel stunnel/dev_https & python3 manage.py runserver& I get the following: [.] Configuration successful [ ] Deallocating deployed section defaults [ ] Binding service [https] [ ] Listening file descriptor created (FD=9) [ ] Setting accept socket options (FD=9) [ ] Option SO_REUSEADDR set on accept socket [.] Binding service [https] to :::8080: Address already in use (48) [ ] Listening file descriptor created (FD=9) [ ] Setting accept socket options (FD=9) [ ] Option SO_REUSEADDR set on accept socket [.] Binding service [https] to 0.0.0.0:8080: Address already in use (48) [!] Binding service [https] failed I tried changing the accept port from 8443 to 8080. Same result I then checked for active processes on the port with lsof -i 8080 This reveals that stunnel is already running on the port. I killed that process and tried again, but I get the same error. Specific questions Can someone briefly explain how … -
How do I set a NOT NULL constraint on Django charfield?
I'm struggling with how I can set a NOT NULL constraint on a charfield. Currently, my model looks like this: class Tutors(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20, blank=False) email = models.EmailField(max_length=254) birth_day = models.DateField(auto_now=False, auto_now_add=False) def __str__(self): return(self.first_name + ' ' + self.last_name) I want to make sure that last_name and first_name can't be saved to the database as NOT NULL. Docs are confusing me a bit lol -
Django Databases - Can you use Postgresql for the Django tables, but have the meat of the data on MSSQL?
I have a scenario where I have full access to CRUD operations on a Database, but cannot create tables, etc., or justify requesting tables to be created. Is it possible to have all the meta tables (auth_*, user_*, django_* tables) hosted local to the app server, and keep the working data in the MSSQL database? I know I could create models to match the MSSQL tables, and copy the data over regularly, but this doesn't seem like a great idea. I'm also aware that there is mixed feelings online about the django-mssql plugin and its abilities. So this adds extra confusion to the problem for me. -
En un modelo DJANGO estoy usando la herramienta FilterView, al momento de visualizar el filtro no me aparece el form clase META
Modelo python donde se define los campos de la tabla from django.db import models # Create your models here. class Integrantes(models.Model): nombre = models.CharField(max_length=50) apellido = models.CharField(max_length=30) codigo = models.CharField(max_length=20) cargo = models.CharField(max_length=20) Filter.py - aqui defino que filtro aplicaré from django.contrib.auth.models import User import django_filters from apps.integrantes.models import Integrantes class integrantesFilter(django_filters.FilterSet): class Meta: model = Integrantes fields = ['nombre'] La vista del Filtro - Uso la herramienta FilterView from django.shortcuts import render, redirect from django.http import HttpResponse, request from django.urls import reverse_lazy from django.views.generic import ListView, CreateView, UpdateView, DeleteView from django_filters.views import FilterView from apps.integrantes.forms import IntegrantesForm from apps.integrantes.models import Integrantes from apps.integrantes.filters import integrantesFilter # Create your views here. class IntegrantesList(ListView): model = Integrantes template_name = 'integrantes/integrantes_list.html' paginate_by = 10 class Integrantes1List(FilterView): model = Integrantes template_name = 'integrantes/integrantes_list.html' filter_class = integrantesFilter paginate_by = 10 Template HTML -> la visualización, sin enmargo, me aparecen todos los campos del modelo INTEGRANTES y solo necesito filtrar por 'nombre' {% extends 'base/base.html' %} {% block title %} ADM RTN {% endblock %} {% block header %} {% endblock %} {% block content %} <form action= "" method="get"> {{ filter.form.as_p }} <input type="submit"/> </form> <table class="table table-bordered"> <thead> <tr> <td>#</td> <td>NOMBRES</td> <td>APELLIDOS</td> <td>CODIGO</td> … -
Is the a way to pass data from an inline formset's clean method to the parent's model admin's clean method in Django?
I have models Product and ProductVariant where on the admin site, the ProductVariant (child) is an inline within the Product (parent). I have overriden the ProductVariant's clean() method to do some validation and creation of stuff like SKU etc. Now I would like to also override the Product's clean() method to do some validations but for one of the validations, I would like to use data (cleaned_data) I have obtained from the ProductVariant's clean() method. So my question is, is there a way that I can pass something I've obtained from the cleaned_data in an inline to the clean() method of the inline's parent. I have added a bit of my code below for reference. It may look a bit more complex than the question I've asked above because I'm using nested inlines and whatnot, but I'm sure the answer will apply in both cases. Thank you in advance. # File: models.py class Product(models.Model): name = models.CharField(max_length=100, unique=True) slug = AutoSlugField(populate_from='name', slugify_function=autoslug_slugify, unique=True) option_types = models.ManyToManyField(OptionType, blank=True) class ProductVariant(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) option_values = models.ManyToManyField(OptionValue, blank=True) # File: admin.py # ==================== # ProductVariant Admin # ==================== class OptionValueInlineFormSet(BaseInlineFormSet): def clean(): # Generate SKU using option_values. Opted for this because … -
Best way to create a Mobile App out of a Django website
What is the best/efficient way of creating a mobile app out of a Django site. I understand that perhaps using React to and connect to a DJANGO API, but assuming I don't know React, can I somehow convert DJANGO site into a Phone Appp? -
How do I get Django form errors from Ajax to appear on the user screen?
Perhaps I'm not thinking clearly...but it would seem to make sense to me that if I am submitting a form via AJAX...the same form that I can submit via the traditional HTML method that I should be able to get the form errors and display them just as I would via a HTML submit? I can certainly get the form.errors in my console if I print them.....but I can't seem to figure out how to get them back to the template so that they render on the user's screen. JSONRESPONSE shows them in a different screen...but how can I just get them back on the form itself? Here is my View... class CreateProcedureView(LoginRequiredMixin,CreateView): model = NewProcedure form_class = CreateProcedureForm template_name = 'create_procedure.html' def form_valid(self, form): instance = form.save() return JsonResponse({'success': True }) def form_invalid(self, form): response = JsonResponse({"error": "there was an error"}) response.status_code = 403 # To announce that the user isn't allowed to publish return response def post(self, request, *args, **kwargs): if "cancel" in request.POST: return HttpResponseRedirect(reverse('Procedures:procedure_main_menu')) else: self.object = None user = request.user form_class = self.get_form_class() form = self.get_form(form_class) file_form = NewProcedureFilesForm(request.POST, request.FILES) files = request.FILES.getlist('file[]') if form.is_valid() and file_form.is_valid(): procedure_instance = form.save(commit=False) procedure_instance.user = user procedure_instance.save() list=[] … -
Context variables on several templates
I have a view, which return context {}. I need to use these context variables not in one template.html, - but in several templates. How can I do this? return render(request, 'cart/cart_detail.html', { 'order':order, 'order_item':order_item, 'total':total} -
Displaying image URL Django
who knows what the problem is and how to fix it, I will try to explain. I have 2 projects, 2 databases: a warehouse and a store, when a new product arrives at the warehouse, the selery performs the task and checks how much product needs to be added to the Store's database, or if it is a new product, then it adds it. problem with pictures. Model Warehouse: class Book(models.Model): author = models.ForeignKey('Author', on_delete=models.CASCADE) genre = models.ForeignKey(Genre, related_name='books', on_delete=models.CASCADE) title = models.CharField(max_length=255) description = models.TextField(blank=True) language = models.CharField("language", max_length=20) pages = models.IntegerField() image = models.ImageField(upload_to='products/%Y/%m/%d') slug = models.SlugField(max_length=255) price = models.DecimalField(max_digits=10, decimal_places=2) isbn = models.CharField('ISBN', max_length=13, unique=True) created = models.DateTimeField(auto_now_add=True) available = models.BooleanField(default=True) quantity = models.IntegerField() here everything is fine, it saves pictures in media / products Model Store: class Book(models.Model): author = models.ForeignKey('Author', on_delete=models.CASCADE) genre = models.ForeignKey(Genre, related_name='books', on_delete=models.CASCADE) title = models.CharField(max_length=255) description = models.TextField(blank=True) language = models.CharField("language", max_length=20) pages = models.IntegerField() image = models.URLField(validators=[URLValidator()]) slug = models.SlugField(max_length=255) price = models.DecimalField(max_digits=10, decimal_places=2) isbn = models.CharField('ISBN', max_length=13, unique=True) created = models.DateTimeField(auto_now_add=True) available = models.BooleanField(default=True) quantity = models.IntegerField() What is the correct name for a field in the store image? link to task celery: https://dpaste.com/G6HJBSJAY screen from API and Image … -
How should I handle timing with push notifications in my Django app?
I'm working with a Django project and I'm implementing push notifications to the back end. I'm using fcm-django for the job. At the moment I'm wondering how should I take care of checking the notification times (how do I tell the app when it should send the notification)? I'll give an example. I have a test Model: class TestNotificationModel(models.Model): timestamp = models.DateTimeField(auto_now_add=False) title = models.CharField(max_length=100) text = models.TextField() user_id = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=("User"), blank=True, null=True) So I can save events to the database and now I need some system to send the notification to the user at some certain time, for example one hour before the time value of the field timestamp. I've been thinking using some library to check for example every hour if the user has an upcoming event and if there is an event which is set to happen at 4pm, the app would send the notification at 3pm. Does this sound like a valid way to implement the feature of sending notifications or is there some other way that would be better? I'm at the starting point with this so any help would be appreciated. -
How to add custom input form to django admin for adding dynamic data?
I'm building an eCommerce website with multiple product variants. So how can I modify the Django admin panel, so that I can add new variants and the corresponding image from the same product adding page? Here is my model: class Products(models.Model): title = models.CharField(max_length=200, blank=False, db_index=True) description = models.TextField(blank=True, null=True) category = models.ManyToManyField(Category, default=None) thumbnail = models.ImageField(blank = True, upload_to = 'products/thumbnails') tags = models.CharField(max_length=100, blank=True, null=True) slug = models.TextField(max_length=500 ,blank=True, help_text="Client side only") created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) class Attribute(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return self.name class Attribute_Value(models.Model): attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE) value = models.CharField(max_length=100, unique=True) def __str__(self): return self.value class Product_Option(models.Model): product = models.ForeignKey(Products, on_delete=models.CASCADE) options = models.ForeignKey(Attribute, on_delete=models.PROTECT) class Product_Combinations(models.Model): product = models.ForeignKey(Products, on_delete=models.CASCADE) combination = models.CharField(max_length=100, blank=True, default="") price = models.DecimalField(max_digits = 10, decimal_places=2, default = 0) class Images(models.Model): product = models.ForeignKey(Product_Combinations, on_delete=models.CASCADE) # title = models.CharField(max_length=200, blank=True) image = models.ImageField(blank=True, upload_to='products/images') Example- Attribute: size, color, material, height Attribute value: 3inch, 5inch, red, blue, wood, metal Product 1: Product_Option- size, material Product_Combinations- combination: 3 inch | wood price: 100 combination: 5 inch | wood price: 200 combination: 3 inch | metal price: 150 combination: 5 inch | metal price: … -
How to Add Image from FILE or URL
I'm trying to add Image from FileField or URL CharField (Url) but i've got some issue. 1st > File from URL is uploaded correctly, Name and Image in Models are successfully created but .. Image is not correct (see code below) 2nd > If File is choosen all is perfect ! I get POST value from Name , slugify it and use it to change name of image with extension in both case ... When I choose an url ... Result for image in Models is : halo/.jpg ... I just want to get back value from file just uploaded from url... In other words : If URL field is filled ... I use this URL instead of File, If not I use FileField to upload. Thanks for help VIEWS.PY def createHalo(request): form = HaloForm() if request.method == 'POST': form = HaloForm(request.POST, request.FILES) if form.is_valid(): document = form.save(commit=False) document.name = request.POST['name'] img_url = request.POST['url'] if img_url != "": print(img_url) photo = Halo() # set any other fields, but don't commit to DB (ie. don't save()) filename = urlparse(img_url).path.split('/')[-1] extension = filename.split(".")[-1].lower() name = "halo/" + slugify(request.POST['name']) + "." + extension # content = urllib.request.urlretrieve(img_url) response = requests.get(img_url) if response.status_code == … -
Editing a Model using templates in django
before updating the update.html form I get null constraint Error how do update my note in my app when i try to update Note model i get this error Request URL: http://127.0.0.1:8000/list Django Version: 2.0.7 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: TakeNotes_note.title In views.py def see(request): if request.user.is_anonymous == False: # lIST OF THE NOTES notes = list(Note.objects.filter(user = str(request.user))) context = {"notes":notes} if request.method == 'POST': # GET THE NOTE REQUESTED note_req = request.POST.get("note_req") if request.POST.get("form_type") == note_req: # CHECK THE DETAILS OF THE NOTED for i in context['notes']: if i.title == note_req: deets = {'note': i} return render(request,'read.html',deets) # Updating the note elif request.POST.get("form_type") == "EDIT": print("Editing", ) for i in context['notes']: if i.title == note_req: deets = {"note":i} if request.method == "POST": # Here is my problem newTitle = request.POST.get("title") newNote = request.POST.get("note") print(newTitle, newNote) i.title = newTitle i.note = newNote i.save() return render(request,"Update.html",deets) #missing Update # Deleting the note elif request.POST.get("form_type") == "DELETE": for i in context['notes']: if i.title == note_req: i.delete() return redirect("/") return render(request,'UserIndex.html',context) else: return redirect("/") in Update.html <!DOCTYPE html> <html lang="en"> <head> {% load static %} <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>Update Note || {{ … -
Upload profile image from React to Django
Im trying to upload a image from my front-end (React) to Django, but i got a error, Bad request, problably becouse the serializer are not accepting the Image data. This is how the data reach the backend <QueryDict: {'id': ['1'], 'image': ['[object Object]']}> This is my view. class ProfilePictureView(APIView): parser_classes = [MultiPartParser, FormParser] def post(self, request): print(request.data) ipdb.set_trace() serializer = ProfilePictureSerializers(data=request.data) if serializer.is_valid(): try: picture = User.objects.get(id=request.data['id']) picture.image = request.data['image'] picture.save() serializer = ProfilePictureSerializers(picture) return Response(serializer.data, status=status.HTTP_200_OK) except: return Response({"Detail": "Not found"}, status=status.HTTP_404_NOT_FOUND) else: return Response(status=status.HTTP_400_BAD_REQUEST) This is my model. def upload_to(instance, filename): return 'media/{filename}'.format(filename=filename) class User(AbstractUser): image = models.ImageField(_("Image"),null=True, blank=True, upload_to=upload_to, default='media/default.png') The Serializer. class ProfilePictureSerializers(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'image') And my requisition on the frontend. const config = {headers: {'content-type': 'multipart/form-data'}}; export const ProfilePictureThank = (UserData, setError) => (dispatch) => { let formData = new FormData(); formData.append("id", UserData.id) formData.append("image", UserData.image) axios .post( `${url_local}/api/profile/picture/`, formData, config) .then((info) => { dispatch(postUserProfilePicture(info.data)); }) .catch((error) => { setError(true); dispatch(postUserProfilePicture(error)); }); }; And here the profile app. const UserData = { id: userId, image: photo } const changeImage = async (e) => { setPhoto({image: e.target.files}) dispatch(await ProfilePictureThank( UserData, setError)); }; <section className="profile-picture-container"> <div className="profile-picture-item"> <img className="profile-photo" src={photo} />; … -
Could not find C:\Users\xerxe\Desktop\bioclin\compose\local\django:
After I run this in the terminal: docker-compose -f local.yml build I get this error: could not find C:\Users\xerxe\Desktop\bioclin\compose\local\django: CreateFile C:\Users\xerxe\Desktop\bioclin\compose\local\django: The specified path could not be found. -
xhtml2pdf problem with converting html file with polish characters
I am trying to make invoices by creating html file and convert it to pdf and than send as http response. The problem is that those invoices contains polish characters which UTF-8 does not display example. I have tried to use ISO-8859-2 to display them, but than I am getting error: ('charmap' codec can't encode characters in position 1159-1163: character maps to ) error. utils.py: from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument( src=BytesIO(html.encode('ISO-8859-2')), dest=result, encoding='UTF-8' ) if pdf.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return HttpResponse(result.getvalue(), content_type='application/pdf') views.py: class GeneratePDF(View): def get(self, request, pk=None): "getting data here" pdf = render_to_pdf("invoice.html", data) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Sales_Invoice_%s.pdf" % ("name") content = "inline; filename=%s" % (filename) download = request.GET.get("download") if download: content = "attachment; filename='%s'" % (filename) response['Content-Disposition'] = content return response return Response(status=rest_status.HTTP_404_NOT_FOUND) Pip freeze: appdirs==1.4.4 arabic-reshaper==2.1.3 asgiref==3.4.1 autopep8==1.5.7 backcall==0.2.0 backports.entry-points-selectable==1.1.0 beautifulsoup4==4.10.0 certifi==2021.5.30 cffi==1.14.6 charset-normalizer==2.0.5 colorama==0.4.4 cryptography==3.4.8 debugpy==1.5.0 decorator==5.1.0 defusedxml==0.7.1 distlib==0.3.2 Django==3.2.7 django-allauth==0.45.0 django-cors-headers==3.8.0 django-rest-auth==0.9.5 djangorestframework==3.12.4 entrypoints==0.3 filelock==3.0.12 future==0.18.2 html5lib==1.1 idna==3.2 ipykernel==6.4.1 ipython==7.28.0 ipython-genutils==0.2.0 jedi==0.18.0 jupyter-client==7.0.6 jupyter-core==4.8.1 matplotlib-inline==0.1.3 mysqlclient==2.0.3 … -
Django : Media URL not showing on the browser
I want to get media django link but I got error 404 on my browser (Chrome) and 200 status code on Terminal models.py from django.db import models from django.utils import timezone from django.utils.translation import gettext as _ from simple_history.models import HistoricalRecords from django.conf import settings from .formatChecker import ContentTypeRestrictedFileField import os class Contrat(models.Model): nom = models.CharField(max_length=15) prenom = models.CharField(max_length=20) telephone = models.CharField(max_length=14, unique=True) telephone2 = models.CharField(max_length=14, unique=True, blank=True, null=True) date_de_naissance = models.DateField(_("date de naissance")) email = models.EmailField(max_length=128) class Record(models.Model): def content_file_name(instance, filename): ext = filename.split('.')[-1] filename = "%s_%s.%s" % (instance.contratSante.nom, instance.contratSante.prenom, ext) return os.path.join('enregistrements', filename) contratSante = models.ForeignKey(ContratSante, default=None, on_delete=models.CASCADE) record = ContentTypeRestrictedFileField(upload_to=content_file_name,content_types=['audio/mpeg', 'audio/mp3', 'audio/ogg'], max_upload_size=20971520, max_length=None) I got this from .formatChecker import ContentTypeRestrictedFileField from formatChecker.py script to check file size and extention from django.db.models import FileField from django.forms import forms from django.template.defaultfilters import filesizeformat from django.utils.translation import ugettext_lazy as _ class ContentTypeRestrictedFileField(FileField): """ Same as FileField, but you can specify: * content_types - list containing allowed content_types. Example: ['application/pdf', 'image/jpeg'] * max_upload_size - a number indicating the maximum file size allowed for upload. 2.5MB - 2621440 5MB - 5242880 10MB - 10485760 20MB - 20971520 50MB - 5242880 100MB - 104857600 250MB - 214958080 500MB - 429916160 """ def … -
Django UpdateView generating 'GET' request instead of 'POST'
I'm following along a book called Django for Beginners and creating a project which displays newspaper articles. Part of the functionality is being able to edit those articles. I've followed along as closely as I could but I'm still getting an error when hitting the 'Update' button: My urls.py from django.urls import path from .views import (ArticleListView, ArticleUpdateView, ArticleDetailView, ArticleDeleteView) urlpatterns = [ path('<int:pk>/edit/', ArticleUpdateView.as_view(), name = 'article_edit'), path('<int:pk>/', ArticleDetailView.as_view(), name = 'article_detail'), path('<int:pk>/delete/', ArticleDeleteView.as_view(), name = 'article_delete'), path('', ArticleListView.as_view(), name = 'article_list'), ] my views.py from django.shortcuts import render from django.views.generic import ListView, DetailView from django.views.generic.edit import UpdateView, DeleteView from django.urls import reverse_lazy from .models import Article # Create your views here. class ArticleListView(ListView): model = Article template_name = 'article_list.html' class ArticleDetailView(DetailView): model = Article template_name = 'article_detail.html' class ArticleUpdateView(UpdateView): model = Article fields = ('title', 'body') template_name = 'article_edit.html' class ArticleDeleteView(DeleteView): model = Article template_name = 'article_delete.html' success_url = reverse_lazy('article_list') My models.py: from django.db import models from django.conf import settings from django.contrib.auth import get_user_model from django.urls import reverse # Create your models here. class Article(models.Model): title = models.CharField(max_length=225) body = models.TextField() date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.title def get_absolute_url(self): reverse('article_detail', args=[str(self.id)]) … -
Upload large file from django to cloud storage
I have a django app on Cloud Run and I'd like to create an endpoint that will be called by another python script. This endpoint should save files to Google storage. The file size is 800Mb max. So when I try to do this I receive: 413 Request Entity Too Large. So from digging the internet I understood that I should use chunk file. But there is something I do not understand.. From this: https://github.com/django/daphne/issues/126 I understand that daphne is now able to receive large body in request. So, I thought that, even receiving a big file Django was managing to chink it and send it piece by piece. I am curious, Is there anyway to do what I want other than doing manual chunk ? For now I added this to my settings: GS_BLOB_CHUNK_SIZE = 524288 DATA_UPLOAD_MAX_MEMORY_SIZE = 26214400 DATA_UPLOAD_MAX_MEMORY_SIZE = 26214400 and I simply use generics.ListCreateAPIView with default value for file upload handler. -
Update Django translations in production
I'm updating the translations file in production (.po file) if an user add some data. When is updated I run the command: from django.core.management import call_command call_command('compilemessages') and it works ok, by SSH I'm checkin that the .po and .mo is updated, but I can't get the new text translations. In my locale works fine, not sure what I have to do in production. My question is, how can I update the in-memory .mo file in prod ? -
Django:different html page if form is submitted
I'd like my html page to not show anymore the form once it is submitted by my user and instead I'd like to show a page with a message that say that the form was already submitted. I thought to use the registration date to determinate whatever the form is submitted or not but this is the error I'm getting when the form is not submitted 'NoneType' object has no attribute 'registration_date' while the code works if there is already a form submitted. I aso don't know if it good to use the presence of the absence of the registration date to determinate if the form is submitted, I've added the profile_submitted BooleanField in my models file but I'm not able to switch it to true and use it. models.py class UserProfile(models.Model): user = models.OneToOneField(User, blank=True, null=True, on_delete=models.CASCADE) gender = models.CharField(max_length=120, choices=gender_choice) birthdate = models.DateField() age = models.CharField(max_length=2) phone = models.CharField(max_length=10) email = models.EmailField() registration_date = models.DateField(default=datetime.today(), blank=True) profile_submitted = models.BooleanField(default=False) view.py def view_profile(request): profile_is_submitted = UserProfile.objects.filter(user=request.user).first().registration_date is not None context = {'profile_is_submitted': profile_is_submitted } return render(request, 'page.html', context) page.html {% extends 'base.html' %} {% block content %} <div class="container"> <h1> Title </h1> {% if profile_is_submitted %} You have already … -
Play video associated with image when clicking the image
I have this code: <div class="video3"> <!-- <video src="{{ video.video.url }}" controls></video> --> {% if video.thumbnail %} <img src="{{ video.thumbnail.url }}" alt="{{ video.title }}" style="width:100px;"> {% else %} <span class="text-muted">Without thumbnail</span> {% endif %} <div class="top-left">{{ video.title }}</div> </div> {% endfor %} </div> I'd like to play the video {{ video.video.url }} in fullscreen when clicking the image (thumbnail) associated with the video.