Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'utf8' codec can't decode byte 0xb5 in position 0: invalid start byte error
I am trying to create a pdf file from an html with the WeasyPrint library, I am following this tutorial: https://www.bedjango.com/blog/how-generate-pdf-django-weasyprint/ But is giving the error of the description. Could someone help me? def termoPDFView(request, id): termo = TermoReferenciaPregao.objects.get(id=id) html_string = render_to_string('painel/report/termo-referencia-pdf.html', {'termo': termo}) pdf = HTML(string=html_string).write_pdf() response = HttpResponse(content_type='application/pdf;') response['Content-Disposition'] = 'inline; filename=termo-referencia.pdf' response['Content-Transfer-Encoding'] = 'utf-8' with tempfile.NamedTemporaryFile(delete=True) as output: output.write(pdf) output.flush() output = open(output.name, 'r') response.write(output.read()) return response -
Django/ModelChoiceFiled: label_from_instance customized doesn't works
I use ModelChoiceField with initial value just for display (readonly field). But value displayed is model id and I want to display customized value that will be a concatenation of 3 fields. I've override ____str____ method but it is not applyed. I try to make customize ModelChoiceFiedl to define label_from_instance that seems to be the way to do what I want but it is not applyed... models.py class Utilisateur(SafeDeleteModel): _safedelete_policy = SOFT_DELETE_CASCADE uti_ide = models.AutoField(primary_key = True) # pro_ide = models.ForeignKey(Projet, on_delete = models.CASCADE) # related project projets = models.ManyToManyField(Projet, through='UtilisateurProjet') uti_nom = models.CharField("Nom", max_length=20) uti_pre = models.CharField("Prénom", max_length=20) uti_mai = models.CharField("Email", max_length=40) uti_sit = models.CharField("Equipe", max_length=20, null=True, blank=True) uti_pro = models.CharField("Fonction/profil", max_length=200, null=True, blank=True) uti_log = models.CharField("Log utilisateur", max_length=20, null=True, blank=True) uti_dat = models.DateTimeField("Date log",auto_now_add=True, null=True, blank=True) log = HistoricalRecords() @classmethod def options_list(cls,pro_ide): # projet = Projet.objects.get(pro_ide=pro_ide) # utilisateurs = Utilisateur.objects.filter(pro_ide=projet.pro_ide) utilisateurs = Utilisateur.objects.filter(projets__pro_ide=pro_ide) the_opts_list = [(utilisateur.uti_ide, utilisateur.uti_nom+', '+utilisateur.uti_pre) for utilisateur in utilisateurs] the_opts_list.insert(0, (None, '')) return the_opts_list class Meta: db_table = 'tbl_uti' verbose_name_plural = 'Utilisateurs' ordering = ['uti_ide'] def __str__(self): return f"{self.uti_nom}, {self.uti_pre} ({self.uti_mai})" forms.py class MyModelChoiceField(ModelChoiceField): def label_from_instance(self, obj): print('label') return obj.uti_nom+', '+obj.uti_pre+' ('+obj.uti_mai+')' class UtilisateurProjetUpdateForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") super(UtilisateurProjetUpdateForm, self).__init__(*args, **kwargs) # … -
Reading a csv file in Django (Python)
I'm trying to figure out how to read from a csv file in a django app. One row of the csv file has data that needs to be parcelled out into different tables/models. But I also need to perform checks on that data to see if it's already in the database. The app is a continuation of the local library tutorial on the Mozilla website. I'm trying to update the library database by uploading data from a csv file, where each line is a record from a book. It kinda works, but not without errors. The main struggle is understanding how to iterate through the file correctly. Do I need to be using an input stream, if so am I doing that correctly, or can I just open the file some other way? I've tried that, but had issues with decoding. The view function I've tried to write (cobbled together from other tutorials, videos and stackexchange posts): import csv, io from django.contrib.auth.decorators import permission_required @permission_required('admin.can_add_log_entry') def book_upload(request): template = "catalog/book_upload.html" prompt = { 'order': 'Order of the CSV should be "authors", "last name", yada yada' } if request.method == "GET": return render(request, template, prompt) csv_file = request.FILES['file'] data_set = csv_file.read().decode('UTF-8') … -
How can i get make a table model work efficiently?
So,i am making an app for making timetables. and i have run into a problem. I have two models . Timetable and Content. class Timetable(models.Model): title=models.CharField(max_length=50) start_time=models.TimeField(default="8:0") end_time=models.TimeField(default="4:0") entries=models.IntegerField(default=3) theme=models.ForeignKey(Theme,on_delete=models.CASCADE,null=True) def __str__(self): return self.title def get_absoulte_url(self): return reverse('timetable-detail',args=[str(self.id)]) class CellEntry(models.Model): parent_table=models.ForeignKey(Timetable,on_delete=models.CASCADE) content=models.CharField(max_length=30) def __str__(self): return self.content How can i make a form such that i can get the two models to behave like a table in excel? How can i set the value of multiple cellentry's parent_table attribute to be the same value in a view? -
Django - How do I create custom permissions in DRF to restrict users from making API calls that they are not authorised to?
I am working on a web app that uses DRF as the backend and ReactJS as the frontend. My web app has users from different sales departments, and I would like to restrict the permission such that only the users from Sales Department A can see the sales projects that are tagged under Sales Department A, and if the users try to access a sales project page that they are not authorised to, it should return an error page. I tried googling for the answer, but I am not sure if the answer I found is the best solution for my problem. I saw solutions using Django Groups, but I was hoping for a solution that would sort of have a check layer within the view or serializer, and from there would deduce which sales department the request.user is from, and hence whether or not the data should be released to them. below is my models.py for more clarity on the structure i am using. class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) department = models.ManyToManyField('SalesDepartment', related_name='users', blank=True) contact_number = PhoneNumberField(blank=True) email = models.EmailField(max_length=255) email_password = models.CharField(max_length=255) profile_picture = models.ImageField(upload_to='profile/', default='profile/blank.png') def __str__(self): return str(self.user.username) class SalesDepartment(models.Model): department_id = models.AutoField(primary_key=True) department_name = … -
how can i reverse farsi or arabic title url in slug automatically with Django
slug it works for me but just reverse the ENGLISH title automatically. but for farsi and arabic language i have to do it manually. so what should i do?! ulits.py: import random import string from django.utils.text import slugify def random_string_generator(size=10, chars=string.ascii_lowercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) def unique_slug_generator(instance, new_slug=None): if new_slug is not None: slug = new_slug else: slug = slugify(instance.title) Klass = instance.__class__ qs_exists = Klass.objects.filter(slug=slug).exists() if qs_exists: new_slug = "{slug}-{randstr}".format( slug=slug, randstr=random_string_generator(size=4) ) return unique_slug_generator(instance, new_slug=new_slug) return slug models.py: slug = models.SlugField(max_length=300, allow_unicode=True, null=True, blank=True, verbose_name=_('پیوند')) def slug_generator(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance) pre_save.connect(slug_generator, sender=Post) -
AttributeError at /accounts/signup/ Manager isn't available; 'auth.User' has been swapped for 'accounts.CustomUser'
I have a custom signup form SignupForm that checks for existing email for the custom user object CustomUser and raises a ValidationError if exists. But when I try to raise the error, I get AttributeError at /accounts/signup/ Manager isn't available; 'auth.User' has been swapped for 'accounts.CustomUser'. Here are my codes. forms.py from django.contrib.auth.forms import UserCreationForm from django import forms from django.core.exceptions import ValidationError from django.contrib.auth import get_user_model class SignupForm(UserCreationForm): def __init__(self, *args, **kwargs): super(UserCreationForm, self).__init__(*args, **kwargs) email = forms.CharField( widget=forms.EmailInput( attrs={ 'class': 'input', 'placeholder': 'bearclaw@example.com' } )) ... # other fields (username and password) ... def clean(self): User = get_user_model() email = self.cleaned_data.get('email') if User.objects.filter(email=email).exists(): raise ValidationError("An account with this email exists.") return self.cleaned_data views.py from django.urls import reverse_lazy from django.views.generic import CreateView from .forms import SignupForm from .models import CustomUser ... # other views and imports ... class CustomSignup(CreateView): form_class = SignupForm success_url = reverse_lazy('login') template_name = 'registration/signup.html' models.py from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): email = models.EmailField(unique=True) def __str__(self): return self.username settings.py AUTH_USER_MODEL = "accounts.CustomUser" What am I missing? -
Update image file in django static files
I'm processing video, then saving each frame as an image in my static folder. Every new image frame overwrites the previous one in the static file directory. The frames come at a pace of 1 per 5 seconds or so. I want to show the frame images on my html file. <img src='../static/frame.jpg' id="image" width="300" height="200"> But it isn't working. It keeps loading the version of the image that was used when it compiled. It only updates when I refresh the page. How can I avoid this? This is the code that I'm using in javascript. Every time I get a websocket message, it should update. I get one every 5 seconds. socket.onmessage = function(e){ var recData=JSON.parse(e.data); image.setAttribute('src', '../static/frame2.jpg'); (...) -
how to upload compress image in imagefield of django forms
I want to compress the image before uploading and then store it in the Imagefield of my Django forms. I am new at it. I don't know how to do it. I can compress Images with normal HTML Input and Javascripts. but I don't know how to pass through Imagefield. or there is another method please help. I am new at it. Please help I am stuck from 4 days froms.py class PostForm(forms.ModelForm): class Meta: model = MainPost fields = ('image','info_post',) widgets = { 'info_post': forms.Textarea(attrs={'rows':4}), } HTML <form enctype="multipart/form-data" class="shadow-lg p-3 mb-5 bg-white rounded" method="POST"> {% csrf_token %} <div> {{ form.image|as_crispy_field }} </div> {{ form.info_post|as_crispy_field }} <input class="btn btn-danger" type="submit" value='Post'> </form> -
Django manager with parameters
I want to create a Manager in DJango that filters on id and sensor. This is my manager: class BrokenDeviceManager(models.Manager): def get_queryset(self): return ( super() .get_query_set() .filter( brokensensor__exact=self.kwargs["pk"], brokensensor__sensor=self.kwargs["sensor"], ) ) When trying this in a test class: Device.broken_objects.filter( device_id=device.id, sensor=Sensor.COUGHS ).count() It gives me: AttributeError: 'super' object has no attribute 'get_query_set' Also tried other approaches, without succes.. This is the brokensensor class: class BrokenSensor(models.Model): sensor = models.PositiveIntegerField(choices=Sensor.choices()) device = models.ForeignKey( Device, on_delete=models.CASCADE, related_name="brokensensor" ) def __str__(self): # pragma: no cover return "pk{} - device: {} - sensor: {}".format( self.pk, self.device_id, self.sensor ) -
How to loop over multiple fields in Django template?
I have models that inherit from an abstract model like this: class ImprovementAbstraction(models.Model): needsImprovement = models.BooleanField() hasFallacies = models.BooleanField() hasEmotionalDeficiency = models.BooleanField() isNecessaryToObtain = models.BooleanField() doesAReallyCauseB = models.BooleanField() areAllStepsPresent = models.BooleanField() isCauseSufficient = models.BooleanField() areAllClausesIdentified = models.BooleanField() isCausalityCertain = models.BooleanField() languageIsEnglish = models.BooleanField() isTautologyPresent = models.BooleanField() class Meta: abstract = True class Assumption(MainAbstractModel, ImprovementAbstraction): need = models.ForeignKey(Need, on_delete=models.SET_NULL, null=True) assumption = models.CharField(max_length=500, default="", null=True) def __str__(self): return self.assumption In the template I would like to display all of the "ToImprovementAbstraction" Model fields associated with the Assumption model. Is there a way to loop over all the fields in the template, something like Assumption.ImprovementAbstractionFields.all() (made up code)? -
Validate POST data in Django Rest Framework
Where is the right place to put validation for received POST data in Django rest framework? I do not want to save this data in db but just need data for my bushiness logic. -
Set timezone relative to user in django
I made a web app using django, I'm not sure about the timezones and stuff. I have the user's preferred timezone, how can I set this timezone relative to that particular user? or will it automatically adjust to the user's timezone? -
Django AttributeError: 'str' object has no attribute 'tzinfo'
I am getting this error at the following code, when I try to get all the objects from my database: data1 = Data.objects.all() for dataset in data1: Here is my model: class Data(models.Model): id = models.AutoField(db_column='ID', primary_key=True) # Field name made lowercase. path = models.TextField(db_column='Path') # Field name made lowercase. username = models.ForeignKey('Users', models.DO_NOTHING, db_column='Username') # Field name made lowercase. datatype = models.CharField(db_column='Datatype', max_length=20, blank=True, null=True) # Field name made lowercase. filesize = models.FloatField(db_column='Filesize', blank=True, null=True) # Field name made lowercase. creationdate = models.DateTimeField(db_column='CreationDate') # Field name made lowercase. modificationdate = models.DateTimeField(db_column='ModificationDate') # Field name made lowercase. diskname = models.CharField(db_column='Diskname', max_length=100, blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'Data' The full error message is: Internal Server Error: /files/ Traceback (most recent call last): File "/home/pi/.local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/pi/.local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/pi/.local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/pi/.local/lib/python3.7/site-packages/django/views/decorators/cache.py", line 31, in _cache_controlled response = viewfunc(request, *args, **kw) File "/home/pi/.local/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/pi/MakMakula/FileManager/app/views.py", line 57, in index for dataset in data1: File "/home/pi/.local/lib/python3.7/site-packages/django/db/models/query.py", line 276, in __iter__ self._fetch_all() File "/home/pi/.local/lib/python3.7/site-packages/django/db/models/query.py", … -
Django message is not working properly using succes message mixin
hi am trying to show message after successful booking but it's not working this is my views.py class booking_confirm(CreateView, SuccessMessageMixin, LoginRequiredMixin): form_class = booking_form1 model = Booking template_name = "confirm_booking1.html" success_message = "booking was created successfully" success_url = reverse_lazy("Driver:Driverview") def form_valid(self, form, *args, **kwargs): booking = get_object_or_404(Loader_post, pk=self.kwargs.get('pk')) print(form.cleaned_data) bk = form.save(commit=False) bk.user = self.request.user bk.post = booking bk.approve = True bk.save() return super().form_valid(form) this is my html code {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} -
Django: Two questions on extending ListView with get_context_data
I tried something similar to this. I have three models: class PartBase(models.Model): name = models.CharField('Name', max_length=120) price = models.DecimalField("Price per part", decimal_places=2, max_digits=6) class Sett(models.Model): name = models.CharField('Name', max_length=120) class PartRelation(models.Model): part = models.ForeignKey(PartBase, on_delete=models.CASCADE) qty = models.PositiveIntegerField("Quantity") sett = models.ForeignKey(Sett, related_name='setts', on_delete=models.SET_NULL, null=True) def get_position_price(self): return self.qty * self.part.price now I want to add the price of all the items in a Sett in a row in my HTML. {% extends 'base.html' %} {% block title %} Add Set {% endblock title %} {% block content %} <table class="table"> <tr> <th>Set Name</th> <th>Total price</th> </tr> {% for set in setts %} <tr> <td>{{ set.name }}</td> <td>{{ set.test }}</td> </tr> {% endfor %} </table> {% endblock %} I wanted to override the get_context_data method somehow like this: class SetListView(ListView): model = Sett context_object_name = "setts" def get_context_data(self,**kwargs): context = super(SetListView, self).get_context_data(**kwargs) context['test'] = "price" return context But I only get an empty field in the template (which I assumed would have the word "price". I can access the price in the shell via for s in Sett.objects.all(): pr = PartRelation.objects.filter(sett=s) price = 0 for p in pr: price += p.get_position_price() But how would I put the code from the shell … -
django.core.exceptions.ImproperlyConfigured Error while hosting django website on apache server on VPS
error log: File "/var/www/host-ecomm/myenv/lib/python3.7/site-packages/django/db/utils.py", line 207, in __getitem__ backend = load_backend(db['ENGINE']) File "/var/www/host-ecomm/myenv/lib/python3.7/site-packages/django/db/utils.py", line 111, in load_backend return import_module('%s.base' % backend_name) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/var/www/host-ecomm/myenv/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 21, in <module> ) from err django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? You can see that at some point during execution, it goes into a python 3.6 based directory, whereas I have given a path to my python3.7 The website has been also built upon 3.7. I have already installed mysqlclient and MySQLdb in my venv . Any suggesstions as to where did could I have entered an incorrect path to python3.6? -
Safely serializing complex values to HTML element attributes
When I have to transfer complex values (e.g. a list of dicts) through a Django template to the front end, I typically use json_script to try and prevent XSS vectors. Recently, I started using lit-element, which has a neat way of pulling attribute values from your custom elements and providing them as properties to your component. You can say: <my-element items="{{ serialized array of items }}"></my-element> Then lit-element will take whatever string value is passed to the items attribute and call JSON.parse() on it, so I need a way of serializing my value to JSON. Since that is relatively trivial in itself, my initial idea was to write a custom template filter and try to match how json_script escapes values. But then I read the source for that function and it explicitly states: Escape all the HTML/XML special characters with their unicode escapes, so value is safe to be output anywhere except for inside a tag attribute. This sounds like attribute values are potentially a more serious XSS vector. So I guess my question is - how to serialize data (in Django/Python) to JSON so it's safe for use in tag attribute values? -
How to add parentheses to make build dynamic django complicated filter and make it run expected?
I want to build complicated filter: queryset.filter( (Q(k__contains=“1”) & Q(k__contains=“2”) & (~Q(k__contains=“3”))) | (Q(k1__contains=“2”) & (~Q(k4__contains=“3”))) ) the structure is fixed, but query case is dynamic(from given input), for example the input could be (k=1&k=2&~k=3) | (k1=1&~k4=3) or (k=1&~k=3) | (k1=1&~k4=3) | (k=4&~k=3) How to add parentheses to build this query to make it run as expected? -
Link not working in anchor tag in django Template
I have a django project with custom user model. When the user registers, he also gives url of his company's website. I access and display it in the template using the USER. But it won't open as a separate link when I write it in an anchor tag as follows: <li><b>Company Website</b><br><a href="{{ detail.company_site }}" target="_blank">{{ detail.company_site }}</a></li> Instead it takes me to this link http://localhost:8000/detail/ahftech.com -
django input serializer date field format
I have a date input format in mm/dd/yyyy. In my input serializer, class ProjectInitSerializer(serializers.Serializer): client_name = serializers.CharField(allow_blank=False, max_length=300) file_name = serializers.CharField(allow_blank=False, max_length=300) run_date = serializers.DateField(required=True, input_formats="%d/%m/%Y") I get this response: "response": { "run_date": [ "Date has wrong format. Use one of these formats instead: %, d, /, %, m, /, %, Y." ] } This serializer is used for input request only. How do I format this? -
ArrayField of DateTimeField causes "django.db.utils.ProgrammingError: cannot cast type timestamp with time zone to timestamp with time zone[]"
I am building an app in Django. I created a new (still empty) model having an ArrayField of DateTimeField, defined as follow: Record_time_values = ArrayField(models.DateTimeField(), blank=False, null=False) As I run the python manage.py makemigrations python manage.py migrate I get django.db.utils.ProgrammingError: cannot cast type timestamp with time zone to timestamp with time zone[] LINE 1: ...estamp with time zone[] USING "Record_time_values"::timestam... I did a little research and this is the thread that get the most close to my same issue, but I don't want to go deep using SQL to fix the problem. Does not it exist a clean way to fix the problem via pure python / Django? In alternative, does exist a good way to store an array of dates and times inside a model, bypassing the arrayfield? -
How to design the autocomplete suggestion box - jQuery - Django
I build an autocomplete function with jQuery and it's working fine but now I want to design the suggestion box which appears if you type in something. I also want to make some changes like how many results should be displayed. $(function() { $("#search_input").autocomplete({ source: "request", select: function (event, ui) { //item selected AutoCompleteSelectHandler(event, ui) }, minLength: 3, }); }); function AutoCompleteSelectHandler(event, ui) { var selectedObj = ui.item; } This is my jQuery function This is how the suggestion box looks like. How can I design it ? I also want to adjust the amount of results which I get displayed. -
How to call external API in django application with username and password
I am trying to receive data from an API endpoint in my django application. I found the solution here: Django rest framework & external api. But when I tried this solution I got error: SSLError at /external-api HTTPSConnectionPool(host='example.com', port=443): Max retries exceeded with url: /example (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')])"))) When I open the external API directly on browser, I need to provide the username and password of the account which has access to that API. But while calling through API I am not providing it anywhere. I am not sure how to set the username and password in the URL or in the settings file to access the external API. -
Wagtail: How to validate m2m inline model?
I have a custom form inheriting from WagtailAdminPageForm and I want to validate an m2m model field (ClusterableModel). Right now I am using the clean() method on my form class. def clean(self): cleaned_data = super().clean() my_field_total_sum = 0 for form in self.formsets['my_field'].forms: if form.is_valid(): cleaned_form_data = form.clean() my_field_total_sum += cleaned_form_data.get('my_value') if total_sum > 100: form.add_error('my_value', 'More then 100 is not allowed') return cleaned_data This works fine until I add and/or remove some inline panels in the admin interface and save my page as a draft and try to validate again. Because self.formsets['my_field'].forms still contains already removed forms and never gets reset to the actual amount of inline panels in the admin. So, is it possible to (re-)set self.formsets['my_field'].forms to the actual amount inline panels visible in the admin interface? Or should I validate elsewhere anyways?