Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django filter if object appears in another table
I have a model Device and a model BrokenSensor. In the BrokenSensor table, all the devices with broken sensor get a row. The BrokenSensor model looks like this: 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 can I do the most efficient way this query: Give me all the devices, except the devices the BrokenSensor table -
how can I get some latest objects from DB without reading all of the objects in Django?
There's some functions in Django to help you get first or last record, such as first(), earliest(), last() and latest(). What I'm looking for is a function to get some latest objects without reading all of data. For example something like this to get latest 3 object: latest_three_objects = my_model.objects.get_latest(count=3) PS: I know that I can get it in this way: latest_three_objects = my_model.objects.all()[:3] But I think it will read all of my_model data from DB and it's not efficient! Any thoughts? -
What backend framework to use for a full stack developer, Node.js (express) or Django?
I learned django for full MPA websites using HTML, CSS and JavaScript initially. Then I wanted to learn React for creating SPAs and so I learned JS again in depth and learned React with Django. Django, even though is batteries included, I started finding it very confusing. Also the there isn’t much content on the internet to learn how django actually works. So I am thinking of learning express JS for backend because I have heard that it is intuitive and well explanatory. Also it has good courses (including MERN stack courses). Just wanted to take advice from someone experienced if this could be a wrong call? Should I stick to Django and learn more about it in depth or should I switch to Express JS. I just want to learn one to be a successfull Full Stack Web Developer. PS: I am equally good at JS and Python. -
In django how to submit form using JS and XMLHttpRequest and then how to retreive those datas in views.py
I am facing error which is: Forbidden (CSRF token missing or incorrect.): /formsubmit [02/Jun/2020 17:38:04] "POST /formsubmit HTTP/1.1" 403 2513 [02/Jun/2020 17:38:05] "GET /?csrfmiddlewaretoken=GiH9HRWEdUnVdvYEGj2vVSvM1A7cStTUGNZ5WjLUcQdqzOl6kyJ8H84qy2sY5D7p&name=arnab HTTP/1.1" 200 647 Its telling csrf token is missing but again csrf token is showing.Please Help Me. My entire code is as follows: my html: <form enctype="multipart/form-data"> {% csrf_token %} <input type="text" name="name"> <button onclick="btnclick()"> CLICK </button> my script: <script> function btnclick() { alert("alert printing") var name=document.getElementsByName('name'); var formdata=new FormData(); formdata.append("name",name); alert("form data appended"); xhr=new XMLHttpRequest(); xhr.open("POST","formsubmit",true); xhr.send(formdata); alert("formdata sent"); } my urls.py: urlpatterns = [ path('',views.uploadpage,name="uploadpage"), path('upload',views.upload,name="upload"), path('formsubmit',views.formsubmit,name="formsubmit"), ] my views.py: def formsubmit(request): name=request.POST.get('name') print(">>>>>>>>>>>>>>>>>>>>>>",name) return HttpResponse("I AM OUT !!!!!!!!!!!!") -
How to to implement user profile picture with python social auth using Django on Google App Engine via Google Cloud Storage
I have successfully been using social auth for using Google And Facebook signin. How can I get the user image for each user, both new ones and that have already registered in the past ? MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.open_id.OpenIdAuth', 'social_core.backends.google.GoogleOpenId', 'social_core.backends.google.GoogleOAuth2', 'social_core.backends.facebook.FacebookOAuth2', 'mysite.signup.views.EmailBackend', ) SOCIAL_AUTH_URL_NAMESPACE = 'social' SOCIAL_AUTH_STRATEGY = 'social_django.strategy.DjangoStrategy' SOCIAL_AUTH_STORAGE = 'social_django.models.DjangoStorage' SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', 'posts.views.update_user_social_data' ) -
'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