Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Simple Jwt Authenticate multiple models
I'm working on a project that includes users communicating with devices( rpi's) via websockets. They only way I can think to make it more secure so other's can't access a websocket 'room' they aren't allowed to be in, is to have a separate way for the rpi's to login like users do. Then somehow check if they are authenticated when connecting to a socket room. Any tips for how to do this? -
Django - DateTime Model field saving time as midnight
I'm experiencing an unusual and frustrating challenge: I have formatted the date/time input inside of the form so it knows what format I'm sending it in, the form validates, and there are no challenges with the data, however when it's saving it saves the time as midnight no matter what way I plug it in. The failing value is sample_date, in the below model. Database Pic: https://imgur.com/yUObctR Model class WaterTest(models.Model): name = models.CharField(max_length=200) sample_date = models.DateTimeField() sample_address = models.TextField() mailing_address = models.TextField(blank=True, null=True) sample_point = models.CharField(max_length=200) job_site = models.ForeignKey(JobSite, on_delete=models.CASCADE, blank=True, null=True) template = models.ForeignKey(Template, on_delete=models.CASCADE, blank=True, null=True) collected_by = models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE) def __str__(self): return f"{self.name}: {self.sample_address}" class Meta: verbose_name = 'Water Test' verbose_name_plural = 'Water Tests' Form class CreateWaterTestForm(forms.ModelForm): sample_date = forms.DateField(input_formats=['%m/%d/%Y %H:%M']) class Meta: model = WaterTest fields = ['name', 'sample_date', 'sample_address', 'mailing_address', 'sample_point', 'job_site', 'template', 'collected_by'] create_report.html <div class="col-md-6"> <div class="mb-3"> {{ form.sample_date.errors }} <label class="form-label" for="{{ form.sample_date.id_for_label }}">Sample Date/Time <span class="text-danger">*</span></label> {{ form.sample_date|add_class:"form-control" }} </div> </div><!-- Col --> <script> $("#{{ form.sample_date.id_for_label }}").datetimepicker({ {% if THEME == 'demo2' %}theme: 'dark',{% endif %} format: 'm/d/Y H:i' }); </script> DateTime picker: https://xdsoft.net/jqplugins/datetimepicker/ GitHub: https://github.com/varlenthegray/wcadmin/tree/dev -
Fetch relations from ManyToMany Field using Annotation
I have my database here. Where I have 2 users connected to one instance of ChatRoomParticipants with a ManyToManyField. I'm trying to get list of related users from a ManyToMany Relation Field from ChatRoomParticipants where I don't want to show the currently authenticated user in the list with other fields i.e room present in the model. Considering user f4253fbd90d1471fb54180813b51d610 is currently logged in and is related to all ChatRooms via ChatRoomParticipants model. Things I've tried but couldn't get the desired output chatrooms = list(ChatRoomParticipants.objects.filter(user=user).values_list('user__chatroom_users__user__username', 'room').distinct()) ##### chatrooms = ChatRoomParticipants.objects.filter(user=user).annotate(user!=User(user)) #### chatrooms = Chatrooms.objects.filter(user=user) rooms = chatrooms.values('user__chatroom_users__user__username').distinct().exclude(user__chatroom_users__user__username=user) I want an output like [ { 'user': '872952bb6c344e50b6fd7053dfa583de' 'room': 1 }, { 'user': '99ea24b12b8c400689702b4f25ea0f40' 'room': 2 }, { 'user': 'eecd66e748744b96bde07dd37d0b83b3' 'room': 3 }, ] models.py class ChatRoom(models.Model): name = models.CharField(max_length=256) last_message = models.CharField(max_length=1024, null=True) last_sent_user = models.ForeignKey( User, on_delete=models.PROTECT, null=True) def __str__(self): return self.name class Messages(models.Model): room = models.ForeignKey(ChatRoom, on_delete=models.PROTECT) user = models.ForeignKey(User, on_delete=models.PROTECT) content = models.CharField(max_length=1024) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.content class ChatRoomParticipants(models.Model): user = models.ManyToManyField(User, related_name='chatroom_users') room = models.ForeignKey(ChatRoom, on_delete=models.PROTECT) -
Creating a handler for user_activated signal
I want to receive a signal when user is activated (i.e. when auth_user.is_active becomes 1). I only want to receive this signal once, the very first time that the user is activated. I have used the answer given to this question, and it works for me: @receiver(pre_save, sender=User, dispatch_uid='get_active_user_once') def new_user_activation_handler(sender, instance, **kwargs): if instance.is_active and User.objects.filter(pk=instance.pk, is_active=False).exists(): logger.info('user is activated') However this seems to be a customized signal, I believe django has a built-in user_activated signal. I have tried using the built-in signal but it does not fire: from django_registration.signals import user_activated @receiver(user_activated, sender=User, dispatch_uid='django_registration.signals.user_activated') def new_user_activation_handler(sender, instance, **kwargs): logger.info('user is activated') Any idea why this signal is being fired? -
How to properly make a signup view with django
I'm made a sign up view with Django but it's not working, it's stored in the database and all but I can't login with the data stored by that view while I can login with the user I made with manage.py createsuperuser here's my signup view def signup(request): if request.method == 'POST': user = User.objects.create( username=request.POST['username'], password=request.POST['password'], email=request.POST['email'], first_name=request.POST['first_name'], last_name=request.POST['last_name'], ) user.save() return HttpResponseRedirect(reverse('posts')) else: signupform = SignUpForm() return render(request, 'users/signup.html', {'form': signupform}) and here's my signup form class SignUpForm(forms.Form): username = forms.CharField(max_length=30, required=True) password = forms.CharField(widget=forms.PasswordInput(), required=True) email = forms.EmailField(required=True) first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) I just need to know what exactly is wrong and how to fix it exactly or what do I need to learn to perform this task properly. -
Is there a Django extension that does something similar to Ruby on Rails AttrJson
I've tried looking for a Django equivalent to RoR ActiveRecord AttrJson but I can't seem to find one. Is there a similar Django extension? -
How to use Django's DurationField with Postgres, when defined previously using sqlite?
I recently moved all my data from sqlite to postgres. All fields seem to work fine except for the duration field. It is shown as an integer in the admin panel and it does not let me edit or save. It works fine with sqlite. However after moving to Postgres, I get the following errors (upon saving or updating): ProgrammingError at /admin/content/movie/add/ column "duration" is of type bigint but expression is of type interval HINT: You will need to rewrite or cast the expression. class Movie(models.Model): """ Stores movie related information. """ unique_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) name = models.CharField(verbose_name='name', max_length=100, blank=False, unique=True) slug = models.SlugField(verbose_name='slug', null=True, blank=True) description = models.TextField(verbose_name='description', blank=True) poster = models.ImageField(verbose_name='poster',upload_to='posters/movies', default='defaults/video.webp', validators=[validate_image]) # Field of interest duration = models.DurationField(verbose_name='duration') created_at = models.DateTimeField(verbose_name='created_at', auto_now_add=True) I also used the following length method for successfully converting the field to human readable form (when using sqlite), but it does not work after moving to postgres. It says: duration (int) does not have 'days' attribute def length(self): """ Converts timedelta into hours and minutes. """ days, seconds = self.duration.days, self.duration.seconds hours = days * 24 + seconds // 3600 minutes = (seconds % 3600) // 60 seconds = (seconds % … -
Does Django cache clear when the server is restarted?
I am trying to use Django's caching API like this: from django.core.cache import cache cache.set('test',[],None) ... list = cache.get('test')... I have 2 questions about this Do I need to set the caching backend in settings for this type of usage? It seems to work without that. Will the cache get reset when the server is restarted. My use case is that I have a function that grabs all classes in the project that are a subclass of a certain class. I only need that function to run when the server loads, because obviously the code is not changing. So if I cache this list of classes and then add a class to the codebase that also inherits from this class, will the cache get reset and have this new class in it now also? -
Most efficient way of storing and retrieving 3 lists of related data in python
I have a django model name, the model and the record of the model. What is the most efficient way of storing and retrieving them. I was thinking of 3 separate lists or a dictionary with the model name as the key and tuple containing the model and record as the value. Any other options? -
How to Show message when anonymosuser post something in Django
I used this method to show message when user send post request. this method works until the user is authorized ... but if anonymous user send post request , something is wrong here.... cause the request is not valid anymore... belong error occurs for me on this line messages.error(request, "Error. Message not sent.") The view shop.views.add_to_cart didn't return an HttpResponse object. It returned None instead. Then I tried to pass a HttpRequest... not working again How can I show message when anonymosuser post something in Django ? -
Availability Schedule field in Django Models?
I am quite new to Django and I'm trying to build a web application where some users will be able to input their available weekly schedule and also show at what times of a day they are available. The picture below(this is just front-end part) shows something similar to what I'm trying to build. What type of Model field do I use to store this type of information inside of a Model class? -
How i can realize multiple pagination(drf)
If I'll send get request like thisenter image description here, i need to have multiple pagination (LimitOffset and PageNumber). models.py: from django.db import models class Products(models.Model): title = models.CharField(max_length=255) description = models.TextField(blank=True) photo = models.ImageField(upload_to="photos/%Y/%m/%d/", null=True) hashtag = models.CharField(max_length=255) is_hit = models.BooleanField(default=False) category = models.ForeignKey('Category', on_delete=models.PROTECT, null=True) def __str__(self): return self.title class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name views.py: from rest_framework import generics from rest_framework.pagination import PageNumberPagination from .models import * from .serializers import ProductsSerializer class PaginationProducts(PageNumberPagination): page_size = 2 page_size_query_param = 'page_size' max_page_size = 2 class ProductsAPIList(generics.ListCreateAPIView): queryset = Products.objects.all() serializer_class = ProductsSerializer pagination_class = PaginationProducts serializers.py from rest_framework import serializers from .models import * class ProductsSerializer(serializers.ModelSerializer): class Meta: model = Products fields = "__all__" def get_photo_url(self, obj): request = self.context.get('request') photo_url = obj.fingerprint.url return request.build_absolute_uri(photo_url) I need something that can help API client choose number of page and quantity of posts on that page. Think that in this case i need NumberPagePagination and LimitOffsetPagination. -
protect a django rest api against sql injection
I have a REST API using django and i want to secure it against sql injection. For example when i type on the browser : localhost:8080/MyApi/?id=3 or 'a'='a', i want to get an error. I searched on the net and i find that sanitizing is a solution, but this solution can validate the fields of my api and not from the url This is what i tried : class FieldSerializer(serializers.Serializer): Field = serializers.CharField(max_length=100) def validate_field(self, value): return bleach.clean(value) How can i do that? -
Hi there I am fairly new to heroku and would like some information on server capabilities
I want to deploy a social media app on heroku with an expected total of about 5000users and 1000 concurrent users. -All users are allowed to post products with a maximum of 3 pics -Upload Profile pictures. What heroku plan would best serve my needs or what other options are there. Thanks in advance -
HTML Checkbox: automatic checkable prop update based on value with Javascript Jquery
This is my JS file to make the checkboxes, i just want that the checked prop of the checkbox updates itself base on the value of the input because my template engine renders the value of the boolean fields directly to my input value attr. But is not working $(document).ready(function () { $("input:checkbox").each(function (e) { console.log($(this).val()) value = $(this).val() $(this).prop('checked', value); }); }); <tr class="checkbox_widget_button"> <td> <div class="card-header"> {{item.validation}}</div> </td> <td> <form method="POST" name="validationFormName_{{item.id}}" id="validationFormId_{{item.id}}"> {% csrf_token %} <div class="card-body"> <input type="hidden" name="id" value="{{item.id}}"> <input type="hidden" name="user_id" value="{{user.profile.custom_user_id}}"> <label for="validation">{{item.validate|lower}}</label> <input type="checkbox" name="validation" value="{{item.validate|lower}}" id="validation"> </div> </form> </td> </tr> -
How can I loop over S3 Media folders in Django?
For context, my AWS S3 media folder consists of subfolders. Each one contains only images for an advertisement. In local, I can loop over each image within a folder and render it to the advertisement page however I can't get it to work in production. The relevant view rendering the location looks like below: def carmodel(request, carmodel_id): carmodel = get_object_or_404(CarModel, id=carmodel_id) folder_name = carmodel.title.replace(" ", '%20') image_folder = os.listdir('media/'+carmodel.title) return render(request, 'vehicles/vehicle.html', {"carmodel": carmodel, "image_folder":image_folder, "folder_name":folder_name}) Each folder is named using the carmodels title. And in the vehicles.html file, I'm looping over it like so. {% for image in image_folder %} <img src="/media/{{ folder_name }}/{{ image }}" class="slider-thumbnail"> {% endfor %} I know that the os.listdir from the image_folder variable within carmodel view doesn't work in production. But I'm stuck trying to figure out how to fix it. I'm ultimately trying to construct the media url by using MEDIA_URL, then folder name then at the end, at the iteration for each image . Hope this makes sense! -
Unable to access Django server running in EC2 instance
I'm trying to run a Django(or really any server to begin) in an ec2 instance like in this tutorial: https://dev.to/awscommunity-asean/create-and-deploy-python-django-application-in-aws-ec2-instance-4hbm The issue is that I can't access the server from my browser despite setting my security group in a way that enables traffic from outside. In the ec2 instance (I am able to ssh in) I have a django server running with python3 manage.py runserver 0:8000 I also set ALLOWED_HOSTS = ['*'] in settings.py My inbound rules are as follows: I try to access the webpage with :8000 with no luck I would like to know where there are sources for error in this process and if there's anything I can do to test the server. If I missed anything let me know. -
Translations tabs of Django parler not showing in the view
I'm using django parler to translate my models. now i'm creating a custom admin Panel and i have a view for create and update of Contents. I'm using a class based view inherit from "View" for both create and update views so i can't use the TranslatableCreateView and TranslatableUpdateView. I saw in the codes of Django parler that using TranslatableModelFormMixin you can add translation support to the class-based views. I used this mixin but still i don't have access to the language tabs. Here is Views.py: class ContentCreateUpdateView(TranslatableModelFormMixin, TemplateResponseMixin, View): module = None model = None obj = None template_name = 'content-form.html' def get_model(self, model_name): if model_name in ['text', 'video', 'image', 'file']: return apps.get_model(app_label='courses', model_name=model_name) return None def get_form(self, model, *args, **kwargs): Form = modelform_factory(model, exclude=['owner', 'order', 'created', 'updated']) return Form(*args, **kwargs) def dispatch(self, request, module_id, model_name, id=None): self.module = get_object_or_404(Module, id=module_id, course__owner=request.user) self.model = self.get_model(model_name) if id: self.obj = get_object_or_404(self.model, id=id, owner=request.user) return super().dispatch(request, module_id, model_name, id) def get(self, request, module_id, model_name, id=None): form = self.get_form(self.model, instance=self.obj,) return self.render_to_response({'form': form, 'object': self.obj}) def post(self, request, module_id, model_name, id=None): form = self.get_form(self.model, instance=self.obj, data=request.POST, files=request.FILES) if form.is_valid(): obj = form.save(commit=False) obj.owner = request.user obj.save() if not id: # new content … -
Getting "IntegrityError" in Django models when trying to create
I am working on an app with Django backend and I am currently developing the signup page. Here's my code: models.py from django.db import models from django.contrib.auth.models import User from django.core.validators import MaxValueValidator, MinValueValidator from datetime import date from .countries import COUNTRIES from .hobbies import HOBBIES class Hobbies(models.Model): hobby = models.CharField(max_length=255, choices=HOBBIES) class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) def username(self): usern = User.objects.get(id=self.user.id) usern = usern.username return usern setup = models.BooleanField(default=False) gender = models.CharField(max_length=100, blank=True) dob = models.DateField(blank=True) def age(self): today = date.today() age = today.year - self.dob.year - ((today.month, today.day) < (self.dob.month, self.dob.day)) return age orgin = models.CharField(max_length=300, choices=COUNTRIES, blank=True) lives = models.CharField(max_length=300, choices=COUNTRIES, blank=True) bio = models.CharField(max_length=150, blank=True) email = models.CharField(max_length=255, blank=True) image = models.ImageField(upload_to='images', blank=True) hobbie = models.ManyToManyField('Hobbies', blank=True) views.py- from django.shortcuts import render from rest_framework import viewsets, status from .serializers import UserSerializer, ProfileSerializer from .models import Profile from django.db import IntegrityError from rest_framework.response import Response from rest_framework.decorators import action from django.contrib.auth.models import User from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated, AllowAny from rest_framework.permissions import IsAuthenticatedOrReadOnly, BasePermission from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt import json from django.contrib.auth import authenticate # Create your views here. #..... @csrf_exempt def signup(request): if request.method == 'POST': data = … -
How to fix Django / python free(): invalid pointer?
When I run the django manage.py app, I got free(): invalid pointer error. Example: >python manage.py check System check identified no issues (0 silenced). free(): invalid pointer Abortado (imagem do núcleo gravada) The django app is running fine but I'm trying to get rid off this message. How can I fix this error or get more info to debug it? Python 3.8.10 (default, Jun 22 2022, 20:18:18) [GCC 9.4.0] on linux (Ubuntu 20.04) Django==2.2.28 with virtualenv -
How to make a search filter on the django website
I have a database with the name of the attached files models.py class UploadFile(models.Model): user = models.ForeignKey(User,on_delete = models.CASCADE,related_name='file_created' ,verbose_name='Автор') title = models.CharField(max_length=200, verbose_name='Заголовок') # uploadedfile = models.FileField(upload_to='files/',null=True, verbose_name='Файл') description = models.TextField(blank=True, verbose_name='Описание') createdtime = models.DateField(auto_now_add=True, db_index=True, verbose_name='Дата создания') price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name='Цена') number_course = models.IntegerField(null=True, blank=True, verbose_name='Курс') number_semestr = models.IntegerField(null=True, blank=True, verbose_name='Семестр') subjectt = models.CharField(max_length=200, null=True,verbose_name='Предмет') type_materials = models.CharField(max_length=200,null=True, verbose_name='Тип работы') institute = models.CharField(max_length=200, null=True, verbose_name='Институт') def __str__(self): return self.title class Meta: verbose_name = 'Загрузка файла' verbose_name_plural = 'Загрузка файлов' I need to make a filter on the table that is obtained when uploading a file: Page with table: <div style="float: right; margin-bottom: 10%; margin-top: 10%;" class="form-group row" data-aos="fade-up"> <form action="" method="post" style="width:90%"> {% csrf_token %} <!-- {{form|crispy}}--> <p><label class="form-label" for="{{ form.number_course.id_for_label }}">Курс: </label> {{ form.number_course }}</p> <div class="form-error">{{ form.number_course.errors }}</div> <p><label class="form-label" for="{{ form.number_semestr.id_for_label }}">Семестр: </label> {{ form.number_semestr }}</p> <div class="form-error">{{ form.number_semestr.errors }}</div> <p><label class="form-label" for="{{ form.subjectt.id_for_label }}">Дисциплина </label> {{ form.subjectt }}</p> <div class="form-error">{{ form.subjectt.errors }}</div> <p><select name = "type_materials" required class="form-select" aria-label="Тип материала"> <option selected>Тип материала</option> <option value="Практические работы">Практические работы</option> <option value="Лабораторные работы">Лабораторные работы</option> <option value="Курсовые">Курсовые</option> <option value="Дипломная работа">Дипломная работа</option> <option value="Лекции">Лекции</option> <option value="Диск с работами">Диск с работами</option> <option value="Другое">Другое</option> </select></p> <p><select name = … -
Django basic ModelForm get success url not working
I created first app with Django. I added first ModelForm, but it is not working when clicking on Submit. # Create your models here. from django.db import models import datetime from django.utils import timezone from django.urls import reverse class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) def __str__(self): return self.question_text def get_success_url(self): return reverse('polls:detail', args=(self.get_object().id,)) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text And forms from django.forms import ModelForm from .models import Question, Choice class QuestionForm(ModelForm): class Meta: model = Question fields = '__all__' def get_success_url(self): # 4 is is random hardcoded number for testing return reverse('polls:detail', args=(4)) When clicking on Send Message after filling form in valid way, I get this exception Even when added get_success_url to model and to form. Anybody ani tips? -
Django instert key-value into a specific place in JSON
I have 3 endpoints that return the same JSON response but with different values. For one of those endpoints, I need to return only one more key-value pair but in a specific place of the JSON, so I can't just add it at the end. Here is an example of what I need to do: response = { 'oid': oid, 'n': n, 'oidp': oidp, 'np': np, 'o': o, 'contains_source': contains_source, 'treg': end_time - start_time, } response = { 'oid': oid, 'n': n, 'oidp': oidp, 'np': np, **'box': boxid,** 'o': o, 'contains_source': contains_source, 'treg': end_time - start_time, } I need to add box:boxid right after np:np. Is there any way I can do that? Or it's just possible to add a value at the end? Thanks in advance! -
How to create a relationship on the field of a model with three different models in django?
Just a fool question I have a model Exam which contains a field Subject which I want to connect with 3 or 4 or even 5 subjects like foreign key connect one with it. # 1 type class Math(models.Model): id = models.CharField(primary_key=True, max_length=200, blank=True) chapter = models.ForeignKey(Chapters, on_delete=models.CASCADE) name = models.CharField(max_length=250) marks_contain = models.IntegerField(default=10) question = RichTextUploadingField() hint = RichTextUploadingField() created_at = models.DateTimeField(auto_now_add=True, blank=True) # 2 type class Science(models.Model): id = models.CharField(primary_key=True, max_length=200, blank=True) chapter = models.ForeignKey(Chapters, on_delete=models.CASCADE) name = models.CharField(max_length=250) marks_contain = models.IntegerField(default=10) question = RichTextUploadingField() hint = RichTextUploadingField() created_at = models.DateTimeField(auto_now_add=True, blank=True) # 3 type class Computer(models.Model): id = models.CharField(primary_key=True, max_length=200, blank=True) chapter = models.ForeignKey(Chapters, on_delete=models.CASCADE) name = models.CharField(max_length=250) marks_contain = models.IntegerField(default=10) question = RichTextUploadingField() hint = RichTextUploadingField() created_at = models.DateTimeField(auto_now_add=True, blank=True) class Exam(models.Model): id = models.AutoField(primary_key=True) created_at = models.DateTimeField(auto_now_add=True, blank=True) name = models.CharField(max_length=255) subject = models.ForeignKey([Math, Science, Computer]) # I want to do something like this I know this is not possible with foreign-key but what is the way to do things like this? -
Wiki Search Project - Creating a New Page - My home screen link works fine, but my new page will not save to the directory
New Page: Clicking “Create New Page” in the sidebar should take the user to a page where they can create a new encyclopedia entry. 1.Users should be able to enter a title for the page and, in a textarea, should be able to enter the Markdown content for the page. Users should be able to click a button to save their new page. 2.When the page is saved, if an encyclopedia entry already exists with the provided title, the user should be presented with an error message. 3.Otherwise, the encyclopedia entry should be saved to disk, and the user should be taken to the new entry’s page. So I'm working on this Django project and I am realizing that Django is not my favorite. I currently have my Wiki Site functioning the way I want it to but I am stuck on how to "Create a New Page". My link on my home screen works fine >>> Takes me to a New Page that I can create. The problem is that when I try to Save the Page my page gets redirected back to the original page with no content. How do I change my code so that it Saves …