Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Confused when delivering PrimaryKeyRelatedField to the Client
If you extract the value of the field used as PrimaryKeyRelatedField, you will see the value in the form of Object, not PK. In the case of the official document, I am using it as below, but it is confusing when using it with the client. I don't know if the tracks will contain id or Object just by looking at the field name. class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Album fields = ['tracks'] def create(self, validated_data): tracks = validated_data.pop('tracks') # [Track, Track ...] Is there a better way? -
Django form submit with hundreds of Celery tasks
I have created a system that enables a user to select users and notify them. When they submit their form, the code will execute a celery task to notify each user. I am getting browser timeouts when sending to 100s of users. Here is a simplified version of my code. Note that my code works as intended, it's just slow when # of users gets into the 100s. Happy to add more if it helps with the answer, but I really want to focus on the generalizable crux of the issue. Note that there reasons why I need so many editable inputs that I'd rather not get into. Let just assume that they are a constraint for the purpose of this question. HTML <form action="" method="POST"> {%csrf_token%} <input type="submit" value="Send"> <table> <tr> <th>User</th> <th>Input 1</th> <th>Input 2</th> <th>Input 3</th> <th>Input 4</th> <th>Select</th> </tr> {% for u in users %} <tr> <td>u</td> <td><input type="text" name="input-1-{{u}}" value=""></td> <td><input type="text" name="input-2-{{u}}" value=""></td> <td><input type="text" name="input-3-{{u}}" value=""></td> <td><input type="text" name="input-4-{{u}}" value=""></td> <td><input type="text" name="input-4-{{u}}" value=""></td> <td><input type="checkbox" name="select-{{u}}" value="True"></td> </tr> {% endif %} </table> </form> Views if request.method == 'POST': # users is a queryset for u in users: # input-#- is a form … -
Custom authorization in Django Rest
I am just a newbie with Django, python. I try to build 1 simple API Collection include CRUD basic, and authentication, authorization. I have 1 simple Views like: @api_view(['GET']) @permission_classes([IsUser]) def get_test(request : Request): return JsonResponse({"message": "success"}, status = status.HTTP_200_OK) and IsUser is: class IsUser(IsAuthenticated): def has_permission(self, request : Request, view): token = request.query_params.get('token') if token: role = jwt.decode(token.split(" ").__getitem__(1), key="secret_key",algorithms="HS256").get('role') if role == 'User': return True else: return False return False My purpose wants to parse the JWT token and authorization based on that. I wonder don't know if my way is really correct? Can anyone give me some comments as well as documentation to better understand this issue? I don't use any other lib because I want to code by myself at first to understand the flow. Thanks for helping me. -
transferring data between JavaScript frontend and Django backend - noob asks
I am exploring web dev very in-depth for the first time and I'm trying to make a chrome extension that sends, let's say, a string to a Django back end, the Django back end processes said string and returns a result back to the chrome extension. I'm doing this because from what I can tell, I can't make a pure Django chrome extension and I am already familiar with Django (although of this I am unsure). Can anyone point me towards some tools I should research to accomplish this? I keep seeing terms like POST, GET, AJAX but have no idea where to begin. Thanks! -
Gunicorn tmp folder fetch my files which got empty
When i was working on server my changed file got deleted but i didn't have restarted gunicorn yet so my system is working properly but i want to get the code of that file. I have tried to look into many directories but didnt found the file Can anyone guide to know where the file will be because i think it might be saved in a temporary directory -
django How to review blog comment before publish?
I am new in django. I want to review my blog comment before it publish or show in my html template. I am using MPTTModel in my model for child parent relationship in my comment section. I used BooleanField in my models but it's not working. Right now my html template showing all blog comment when any user submitting comment. here is my code: #models.py class BlogComment(MPTTModel): blog = models.ForeignKey(Blog,on_delete=models.CASCADE) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') name = models.CharField(max_length=250) email = models.EmailField(max_length=2000) comment = models.TextField(max_length=50000) created_at = models.DateTimeField(auto_now_add=True,blank=True,null=True) updated_at = models.DateTimeField(auto_now=True,blank=True,null=True) is_approve = models.BooleanField(default=False) #forms.py class CommentFrom(forms.ModelForm): class Meta: model = BlogComment fields = ['name','email','comment'] views.py class BlogDetail(DetailView): model = Blog template_name = 'blog_details.html' def get(self,request,slug): blog = Blog.objects.get(slug=slug) form = CommentFrom() context = {'form':form, 'blog':blog, } return render(request,'blog_details.html',context) def post(self,request,slug): blog = Blog.objects.get(slug=slug) form = CommentFrom(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.blog = blog comment.save() messages.add_message(self.request, messages.INFO, 'Your Comment pending for admin approval') return redirect(reverse('blog-detail', kwargs={'slug':slug})) else: form() context = {'form':form, 'blog':blog, } return render(request,'blog_details.html',context) #html {% load mptt_tags %} {% recursetree blog.blogcomment_set.all %} <p>comment: {{node.comment}}</p> {% if not node.is_leaf_node %} <div class="children pl-2 pl-md-5"> {{ children }} </div> {% endif %} {% endrecursetree %} -
Store data of React in Django Database without using Models
I am trying to build a simple project in React and Django. I am a beginner. I am trying to build a punch in machine. I am working on a feature where the user when clicks the image then it displays the time and date she clicked the image. I want to store that time and date in database.But I do not know how to? Do I need to create Model or can be done without the model. My code so far Index.js function CDate(){ const dt = null; const [cdate,setDate] = useState(dt); const handelDate = () =>{ let dt = new Date().toLocaleString(); setDate(dt); } return( <> <h3>{cdate}</h3> <img src={punchin} alt="PunchinMachine" onClick={handelDate} /> </> ) } ReactDOM.render(<CDate />,document.getElementById("root")); Could you please me store the time she clicked in the db so that I can keep track of time. -
"Any" path in Django?
Is it possible to define a route that will be redirected to if Django could not find a match in the defined URLs? For example, let's say I have: urlpatterns = [ path('ajaxlogin', views.ajax_login, name='ajaxlogin'), path('ajaxprofile', views.ajax_profile, name='ajaxprofile'), ] Can I define a "dynamic" URL of a specific view that will be redirected to if the path doesn't exist? Suppose I enter the URLs /ajaxsignup and /ajaxdelete, which are not defined, but have them redirected to a URL of a certain view? In other words: urlpatterns = [ path('ajaxlogin', views.ajax_login, name='ajaxlogin'), path('ajaxprofile', views.ajax_profile, name='ajaxprofile'), path('every-other-url', views.another_view, name='path-everything-else'), ] I know there's Django's error handlers, but are there any other ways to achieve this? I have my frontend based separately on a React application, so I'd very much appreciate a "dynamic" URL rather than using Django's default 404 responses. I suspect that if path couldn't do it, I could use the old url with regex -- but I still have no clue. Thanks in advance. -
django rest framework set image field to null when updating the field
Here is my code; models.py class Book(models.Model): title = models.CharField(max_length=255) author = models.CharField(max_length=255, blank=True, null=True) cover_image = models.ImageField(blank=True, null=True) def __str__(self): return f"{ self.title } - { self.author }" serializer.py class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = '__all__' views.py class BookListViews(generics.ListAPIView, generics.CreateAPIView, generics.RetrieveUpdateDestroyAPIView): queryset = Book.objects.all() serializer_class = BookSerializer The object is created alright, but when I try to update the title or author field, without updating the image, once I post it, the image value is set to null. This is problem because, I don't want to keep changing the image or update the image anytime I want to change the title or author field. -
Delete user create from allauth social login
In the process of learning allauth social login, I am able to successfully register & log in a user using google provider. For trial and testing purposes I need to delete the logged-in user and re-register with the same google email. I deleted the social account, social account token, email for that user from the admin console, but when I try to login again for the same user with the same email it gives an error - An account already exists with this e-mail address I have also checked rest-auth/user but found nothing. How can I completely delete a social account and log in again with the same Email? Any helpful tips? -
How to call a Class´s method with a button on a web page - Django -python
im starting with django and iot and i've decided to start (for learning purposes) an app that connects to my sensors attached to my raspberry pi. The thing that im struggling is the next one: I've done a class for my DHT11 sensor (temperature and humidity), and i've declared all values and wrote a method, which gets and prints the values of the sensor, and made a page where i show all the properties of the object, like "asigned pin" or the "name" of it; all fine until here. this is the class: class DHT11(models.Model): dht_sensor = Adafruit_DHT.DHT11 pin = IntegerField() status = BooleanField(default=False) name = CharField(max_length=15) humidity = IntegerField(default=0) temperature = IntegerField(default=0) def read_values(self): self.humidity, self.temperature = Adafruit_DHT.read(self.dht_sensor, self.pin) if self.humidity is not 0 and self.temperature is not 0: self.status = True else: self.status = False time.sleep(delay) print(self.temperature) print(self.humidity) The issue is that, in the same page where i show the properties of the object, id like to create a button, and with it call the "read_values" method of the object, and then show the values of temperature and humidity in the webpage that the method returns. ¿how do i do this?, do i need websockets? Here is an … -
How to Connect a Django Model with ManyToMany Relationship?
I am making an app that is pretty much similar to google classroom in django. I have a Course model and an assignment model, and I want to connect an assignment to the specified course. These are my models class Assignment(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) name = models.CharField(max_length=100) date_created = models.DateTimeField(default=timezone.now) class Course(models.Model): title = models.CharField(max_length=100) subject = models.CharField(max_length=100) image = models.ImageField(default='no_course_image.jpg', upload_to='course_images') owner = models.ForeignKey(User, on_delete=models.CASCADE) students_invited = models.ManyToManyField(User, null=True, blank=True) assignments = models.ManyToManyField(Assignment, null=True, blank=True) date_published = models.DateTimeField(default=timezone.now) class Meta: verbose_name_plural = 'Course' ordering = ['-date_published'] def __str__(self): return '{} - {}'.format(self.title, self.owner) But i am getting an error when I specify the course field in the assignment model with the ForeignKey! Could you please help me with how to connect the assignment to the Course model? Thank you -
How to create a nested DRF serializer with a UUID PrimaryKeyRelatedField?
I've simplified/minimised the example here (removed class meta which specifies model and all fields, removed some other explicitfields) but it matches the use case and replicates the behaviour being observed. class MainSerializer(ModelSerializer): a = ASerializer(required=False, many=True) def create(self, validated_data): a_data = validated_data.pop("a", None) main_instance = super().create(validated_data) if a_data is None: return main_instance for a in a_data: a["main_relation"] = main_instance a_serializer = ASerializer(data=a, many=True) a_saved = None if a_serializer.is_valid(): a_serializer.save() a_saved = a_serializer.data else: a_saved = a_serializer.errors return { **self.data, "a": a_saved.data() } class ASerializer(ModelSerializer): main_relation = PrimaryKeyRelatedField(queryset=ModelB.objects.all(), required=False, allow_null=True, default=None) The MainSerializer#create ends up throwing an error in the PrimaryKeyRelatedField#to_representation where it says the string representation of main_instance has no attribute pk, but when running through the debugger, the instance definitely has both the pk and uid attribute, and both are the same value as expected. So what's going wrong? Side question: if instead of returning the dictionary, and returning main_instance in both cases, will the viewset return the full MainSerializer#data representation of the instance (the nested a relationship included as per it's serializer)? And if the nested serializers have errors, will they come through in that data? Or would something like this require an extension of the drf functionality? -
How to make this very complicated query from three connected models with Django ORM?
Good day, everyone. Hope you're doing well. I'm a Django newbie, trying to learn the basics of RESTful development while helping in a small app project. We currently want some of our models to update accordingly based on the data we submit to them, by using the Django ORM and the fields that some of them share wih OneToMany relationsips. Currently, there's a really difficult query that I must do for one of my fields to update automatically given that filter. First, let me explain the models. This are not real, but a doppleganger that should work the same: First we have a Report model that is a teacher's report of a student: class Report(models.Model): status = models.CharField( max_length=32, choices=Statuses.choices, default=Statuses.created,) student = models.ForeignKey( Student, on_delete=models.CASCADE, related_name='reports', ) headroom_teacher = models.ForeignKey( TeacherStaff, on_delete=models.CASCADE,) # Various dates results_date = models.DateTimeField(null=True, blank=True) report_created = models.DateTimeField(null=True, blank=True) . #Other fields that don't matter Here we have two related models, which are student and headroom_teacher. It's not necessary to show their models, but their relationship with the next two models is really important. We also have an Exams model: class Exams(models.Model): student = models.ForeignKey( student, on_delete=models.CASCADE, related_name='appointments',) headroom_teacher = models.ForeignKey( TeacherStaff, on_delete=models.CASCADE,) # Various … -
How I get obj from parent model in Django Admin to put in html template
Here is my code where I generate a PDF file, (like an invoice), but I can't retrieve the fields from the admin.TabularInline. In my model.py I have to class: Sale and SaleItems,and in admin.py I have : class SaleItemsInLine(admin.TabularInline): model = SaleItems extra = 1 readonly_fields = ('total', ) formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size':'100%'})}, } @admin.register(Sale) class SaleAdmin(DjangoObjectActions, admin.ModelAdmin): fields = ( ('order', 'created', 'due_date'), ('profile'), ('pay_method', 'tax_card'), ('therapist' ,'activity',), ('notes'), ('totals'), ('pay', 'payOne','payTwo'), ('subtotal', 'status'), ) readonly_fields = ('created', 'totals', 'order','subtotal', 'status', 'tax_card') search_fields = ['profile__name', 'profile__cpf', 'profile__phone', 'activity', ] autocomplete_fields = ('profile',) list_display = ('profile', 'order', 'created', 'due_date', 'totals', 'status') inlines = [SaleItemsInLine] formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size':'30'})}, models.TextField: {'widget': Textarea(attrs={'rows':4, 'cols':100})}, } def generate_pdf(self, request, obj): html_string = render_to_string('sales/invoice.html', {'obj': obj}) html = HTML(string=html_string, base_url=request.build_absolute_uri()) html.write_pdf(target='/tmp/{}.pdf'.format(obj), presentational_hints=True); fs = FileSystemStorage('/tmp') with fs.open('{}.pdf'.format(obj)) as pdf: response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'filename="{}.pdf"'.format(obj) return response return response I get fields from Sale with {{ obj.name }}, {{ obj.created}}, etc... How I get the fields from SaleItems(TabulaInline) ??? -
How to search any of a set of fields spanning multiple tables and show a join of those fields on the results page in Django
I have a set of fields spanning 7 tables that I want to display as a consolidated search results table. (Not sure if it matters, but the relationships between the tables are mostly reverse relationships (except 1)). For illustrative purposes, here is the table hierarchy (where each subtable record has a link to the parent table): Study (1 field) Animal (4 fields) Sample (1 field) -> Tissue (one field - the only forward relationship) MSRun (0 fields) PeakGroup (3 fields) PeakData (3 fields) Each table (Except MSRun) has at least 1 field displayed (and searchable) in the results output (presented in table format). I want the user to be able to search any of those fields and I want only one view function and one results template (in order to reduce the overhead of maintaining multiple identically-appearing result pages when the format is changed (which I expect to happen)). The joined results should only contain values matching whatever the search field was. E.g. If they search for Animal 1, that column would have only '1' in it, along with all other related fields. Worst case, the results table would have roughly 2.2k rows from the largest Study. (Note, 4 of … -
Django not getting path not matching
I am trying to make a certain url on my localhost show "Alex!" when it is entered in. For some reason I am getting this error: "Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ The current path, sauce, didn’t match any of these." The app name is "main" Here is my code: main.urls from django.urls import path from . import views urlpatterns = [ path('sauce/', views.index, name='index'), ] main.views from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("Alex!") mysite.urls from django.contrib import admin from django.urls import path, include urlpatterns = [ path('sauce/', include('main.urls')), path('admin/', admin.site.urls), ] I also tried doing this but with the homepage and not "sauce/" but that didn't work either. -
how I can use http post flutter with django
I want to make it without Django Reset Framework that is my code ''' from django.http import JsonResponse def index1(request): cursor.execute('select * from users where id = %s',[request.POST]) response = list(cursor.fetchall()) return JsonResponse(response, safe=False) ''' and when i use flutter http post put it gives me this Forbidden (CSRF cookie not set.): /index1 [04/Jun/2021 00:20:25] "POST /index1 HTTP/1.1" 403 2870 -
django ListView template post function using Q queries - too many values to unpack (expected 2)
I am using Django 3.2 I am creating a search form that will allow me to search for terms entered by user. I am using POST to post the search terms to the server. Here is my code: /path/to/views.py class FooSearchListView(ListView): model = Foo context_object_name = 'foos' template_name = 'path/to/foo_search_list.html' def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) return context def post(self, request, *args, **kwargs): query_original = request.POST.get('search_terms', None) lookups = Q() if query_original: search_query = [x.strip() for x in query_original.lower().split(',')] for word in search_query: lookups = (lookups | Q(title__icontains=word) | Q(tags__name__icontains=word) | Q(caption__icontains=word) ) return Foo.objects.filter(lookups, is_public=True).distinct() # <- Barfs on this line /path/to/page.html <form action="{% url 'foo-search' %}" class="form-inline input-group col-md-4" method="post"> {% csrf_token %} <input id="search-terms" name="search_terms" class="form-control py-2 border-right-0 border" type="search" value="search"> <span class="input-group-append"> <button class="btn btn-outline-secondary border-left-0 border" type="submit"> <i class="fa fa-search"></i> </button> </span> </form> /path/to/urls.py # ... path('foos/search/', FooSearchListView.as_view(), name='foo-search'), # ... What is causing this error - and how do I fix it? -
Call python function with Django
I've recently started learning how to use Django and I was wondering whether or not you could create a button in HTML that can directly call a python function without changing the URL. I was told this was possible with JS but I wanted to know if you could do that in Python. Thanks for your time reading this! -
Flash popup from within decorator function on Flask Route
I would like to create a flash popup from within a decorator function applied to a Flask view. When I generate a flash from within my view, everything works perfectly fine. I would like to be able to also generate flash messages from a wrapper function acting on the view; the form I have tried is: from flask import Flask, render_template from functools import wraps def my_wrapper_function(_f): @wraps(_f) def _decorated_function(*args, **kwargs): ... flash(removed_article.get('name', 'expansion')) ... return _f(*args, **kwargs) return _decorated_function @app.route('/my_view/<int:_id>', methods=['GET']) @my_wrapper_function def my_view(_id): ... return render_template('my_template.jinja2') This does not appear to work however, no flash message appears. N.B: As opposed to generating flash messages within my view, which does work. The following template is included below for completeness; I would imagine the solution lies in the python code. # my_template.jinja2 {% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} {% for category, message in messages %} {% if category == 'message' %} <div class="alert alert-success text-center" role="alert"> {% else %} <div class="alert alert-{{ category }} text-center" role="alert"> {% endif %} {{ message }} </div> {% endfor %} {% endif %} {% endwith %} Since I'm fairly new at both decorators and Flask in general, I thought I'd … -
Django-Python: Grabbing Alias Outlook Email in the form of JSON
0 I am trying to grab the alias email addresses created within the main account. How am I able to grab the JSON for all of the alias email addresses and then grab all the calendar events contents? Here is the layout of my code: https://github.com/reportex-development/Lobby-Menu/tree/main/Lobby-menu-v3-here I see that in the tutorial > graph_helper.py there is something that's trying to get_calendar_events but it seems like it is only for that one main account but I want to see all the events in the alias accounts. I tried doing: print(events) print(get_user(token)) print(get_calendar(token)) print(get_calendar_group(token)) But none of those are showing me the alias email addresses it is only showing me the main account information. How do I see the alias account information? -
Getting TypeError: __init__() got an unexpected keyword argument 'upload_to' in Django Project?
I have just started learning Django frame work and got stuck after getting an unexpected error as below:-(I have tried to post all information, which i find necessary to be here) TypeError: __init__() got an unexpected keyword argument 'upload_to' I got this error while running command python manage.py makemigrations My project contains only one Model class Products My Model Class:- from django.db import models # Create your models here. class Products(models.Model): name = models.CharField(max_length=25) price = models.IntegerField() description = models.CharField(max_length=50) pic = models.DateTimeField(upload_to="myimages") I am added my app in INSTALLED_APPS fields in setting.py Thanks in advance. Hope to here from you soon. -
Django: Change default parameter appended in the URL in forms
I have a form like this: <form method="get"> <button name="load" type="submit" value="{{game.game_id}}|{{game.champion}}">Show user's stats</button> </form> When the user submits the form, the parameter will automatically be appended into the URL like this www.example.com/?load=5293733926|99 However, I want to add manually another parameter to the URL making the URL look like this: www.example.com/?load=5293733926|99&page=2 If I manually type this to the URL, it goes to where I want. How should I do this? I tried adding: action="./?load={{game.game_id}}|{{game.champion}}&page={{game.page}}" and multiple other variants. But it doesn't work, it redirects to www.example.com/?load=5293733926|99. Context: I have a huge list of dictionaries and if I show them all at the same time and process them, it takes a lot of time. I divided the list with Django's paginator. The forms act as a load more. By default, I show some data from the dictionary and when the user clicks the form button, some extra information is showed. However, if someone clicks the form button in page 2 www.example.com/?page=2, Django would redirect the user to the first page after processing the data. In order to redirect the user to the submitted button's page, I would need to redirect the user to www.example.com/?load=5293733926|99&page=2 It's my first time asking a question … -
How to use Login View in django?
I decided to customize the login form and make authentication with email. I can login with super user account but can't do it with the simple user. Here's the models.py file. I created custom user manager and redifened the creation logic def create_superuser(self, email, user_name, first_name, last_name, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('Staff must be True') if other_fields.get('is_superuser') is not True: raise ValueError('Superuser must be True') if other_fields.get('is_active') is not True: raise ValueError('Is active must be True') return self.create_user(email, user_name, first_name, last_name, password, **other_fields) def create_user(self, email, user_name, first_name, last_name, password, **other_fields): if not email: raise ValueError('You must provide an email') email = self.normalize_email(email) user = self.model(email = email, user_name = user_name, first_name=first_name, last_name = last_name, **other_fields) user.set_password(password) user.save() return user class UserProfile(AbstractBaseUser, PermissionsMixin): email = models.EmailField(('email address'), unique=True) user_name = models.CharField(max_length=150, unique=True) first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) start_date = models.DateTimeField(default=timezone.now) department = models.CharField(max_length=150) company = models.CharField(max_length=150) head = models.CharField(max_length=150, blank=True) is_staff = models.BooleanField(default=False, blank=True) is_active = models.BooleanField(default=False, blank=True) is_admin = models.BooleanField(default=False, blank=True) dashmodel = models.CharField(max_length=150, blank=True) role = models.CharField(max_length=150, blank=True) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['user_name','first_name','last_name'] def __str__(self): return self.user_name ``` I change the logic of …