Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pre-commit hooks for checking the param docstrings in python/django
I am looking for a way of adding a pre-commit hook to check if the params in the function are added, secondly to check if the PEP257 guidelines are followed interms of Classes and Functions docstring, below is my pre-commit-config.yaml : repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v3.4.0 # Use the ref you want to point at hooks: - id: trailing-whitespace - id: check-docstring-first - id: double-quote-string-fixer # - id: docformatter - repo: https://github.com/myint/docformatter.git rev: v1.3.1 hooks: - id: docformatter args: [--in-place] -
How to Create 2 different objects at the same time in 1 view in django rest_framework? DRF
What I want to do is, create user object and staffprofile object at the same time. And username will be based on first_name field and last_name field on the staffprofile object that is created along with it. And password will be auto generated using random module. I have a custom User model which inherits AbstractUser and has these parameters: class User(AbstractUser): is_student = models.BooleanField(default = False, verbose_name = 'Student') is_staff = models.BooleanField(default = False, verbose_name= 'Staff') is_teacher = models.BooleanField(default = False, verbose_name='Teacher') is_superuser = models.BooleanField(default = False, verbose_name= 'Administrator') is_registrar = models.BooleanField (default = False, verbose_name= 'Registrar') email = models.EmailField( max_length=254, unique=True, verbose_name='Email Address', blank=True, null=True, ) def __str__(self): return self.username and I have a StaffProfile model which is related to User model through user attribute: class StaffProfile(models.Model): GENDER_CHOICES = [ ('Male', 'Male'), ('Female', 'Female'), ] user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key= True, limit_choices_to= Q(is_staff= True), related_name= 'staffprofile', ) first_name = models.CharField(max_length= 70,) middle_name = models.CharField(max_length=70,) last_name = models.CharField(max_length=70,) gender = models.CharField( max_length= 6, choices=GENDER_CHOICES, default='Male', ) employee_number= models.CharField(max_length= 15) date_of_birth = models.DateField() mobile_number = models.CharField(max_length= 15) address= models.TextField() def get_full_name(self): """ Return the first_name plus the last_name, with a space in between. """ full_name = '%s %s' % (self.first_name, … -
My login form isn't working, it says variable was referenced before assignment
when I go to '/login', this error comes up: UnboundLocalError at /login/ local variable 'form' referenced before assignment This is my view: from django import forms from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.http import HttpResponseRedirect class LoginForm (forms.Form): username = forms.CharField() password = forms.CharField() def login (request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): # username = request.POST['username'] # password = request.POST['password'] username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) if user is not None and user.is_active: login(user) return redirect ("/login/success") form = LoginForm(request.POST) return render (request, 'login.html', {'form':form}) This is the template: {% include 'base.html' %} {% load crispy_forms_tags %} <div class="videos"> <form method="post" class="bootstrap4"> {% csrf_token %} {{ form | crispy }} <button type="submit" class="btn btn-success">Submit</button> </form> Do't have an acount? Click <a href="/register">here</a> to create an account. </div> I don't see where it is referenced before assignment, and I get this error with python occasionlly, and I'm never able to figure out where it is referenced before assignment. -
Changed import structure in Django 3.2?
I just opened a new Djangoproject with v3.2 and tried to import my apps as usual, when I got an ImproperlyConfigured Exception on one of my apps. Steps: create and activate env, pip install django (without version number defaults to v3.2 as of now) django-admin startproject project mkdir project\apps, mkdir project\apps\core django-admin startapp core project\apps\core migrate, if necessary Go to settings and add 'apps.core' to INSTALLED_APPS Result, when trying to runserver \lib\site-packages\django\apps\config.py", line 246, in create raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Cannot import 'core'. Check that 'apps.core.apps.CoreConfig.name' is correct. Structure -- project -- apps -- core -- apps.py -- project -- manage.py core\apps.py class CoreConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'core' The auto_field seems to be new as it was not integrated in earlier versions, however this should not affect the importation if I understand this correctly. I returned to v3.1.3 to check if something else went wrong, but it is working fine with this approach. Does anyone have the same issues or have a solution? Thanks -
Testing contrib.messages in a Django FormView (Class Based View)
The view is a FormView. If there is any validation problem, the same template is returned with a message from contrib.messages. I just want to build a test that checks if this message is rendering properly . I have already read about RequestFactory, Client, Mock, Middleware and I was not able to implement this test in CBV FormView. I also tried get_messages and other stuff. View: class MyView(FormView): form_class = MyForm template_name = 'app/welcome_template.html' def form_valid(self, form): form_data = form.cleaned_data auth = LDAPBackend() user = auth.authenticate(self.request, username=form_data['login_field'], password=form_data['password_field']) if user: return super(MyView, self).form_valid(form) else: messages.add_message(self.request, messages.WARNING, 'some warning' + str(form_data['other_field'])) return self.form_invalid(form) Test attempt: This test is printing always empty lists. from django.test import TestCase, RequestFactory, Client from django.urls import reverse from .views import MyView from caf.settings import V_USER, V_PWD from django.contrib.messages import get_messages class MyViewTestCase(TestCase): def setUp(self): self.factory = RequestFactory() self.client = Client() def test_message(self): input_data = {'login_field': V_USER, 'password_field': V_PWD, 'other_field': 'other...'} request = self.factory.post(reverse('app:welcome_template'), data=input_data, follow=True) response = MyView.as_view()(request) print(len(get_messages(response.wsgi_request))) print(len(response.context['messages'])) I'll appreciate any help. Thanks in advance. -
How to filter the customized query in Django ORM
I want to show the remaining students which are enrolled in the given course but not added in the respective subjects by the teacher. For example 'students_enrolled = Student.objects.filter(course_enrolled=sub_name.course_id.id)' gets all the students which are enrolled in the given course i.e. (sub_name.course_id.id) and 'students_in_class = StudentsInClass.objects.filter(subject=subject_id, teacher=request.user.id)' have all the students added in the class by the 'request.user.id' teacher and given subject. Is there any way to show the students which are present in the 'students_enrolled' but not in the 'students_in_class' ?? models.py class Courses(models.Model): id = models.AutoField(primary_key=True) course_name = models.CharField(max_length=255) def __str__(self): return self.course_name def get_absolute_url(self): return reverse('addCourse') class Student(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True) phone_number = models.CharField(max_length=20, blank = True) semester = models.CharField(max_length=20, blank = True) session_year = models.ForeignKey(Session, on_delete = models.CASCADE, null=True, related_name = 'session_year') course_enrolled = models.ForeignKey(Courses, on_delete = models.CASCADE, null=True, related_name = 'course_enrolled') def __str__(self): return str(self.user) + " " + str(self.course_enrolled) class Subjects(models.Model): id = models.AutoField(primary_key=True) subject_name = models.CharField(max_length=255) course_id = models.ForeignKey(Courses, on_delete=models.CASCADE, default=1) #need to give defauult course teacher_id = models.ForeignKey(Teacher, on_delete=models.CASCADE) def __str__(self): return self.subject_name def get_absolute_url(self): return reverse('addSubject') class StudentsInClass(models.Model): teacher = models.ForeignKey(Teacher,related_name="class_teacher",on_delete=models.CASCADE) student = models.ForeignKey(Student,related_name="user_student_name",on_delete=models.CASCADE) subject = models.ForeignKey(Subjects,related_name="user_subject_name",on_delete=models.CASCADE, null=True) def __str__(self): return self.subject.subject_name + " and … -
How can I create permission to 'is_staff' in Django?
I have two, regular types of access to admin - one is 'is_staff', other one is 'is_staff' with 'is_superuser'. Superuser is fine, I am okay with admin having access to anything, but I would like users with 'is_staff' flag to automatically have some permissions, without having to add them. How can I achieve that? Should I create separate group that is added automatically once the person have 'is_staff' flag? Or can I attach some permissions automatically to 'is_staff' group? -
How to start and maintain a background thread in django?
I have a Django project that provides an API. The api provides an information that must be measured over time. So fo example measure every 2 sec for 2 sec. I would like to write a background thread that measures the information and writes it to a place where it can be accessed immediately. I host django over cherrypy. I have the following requirements: I need to access the Django ORM in the thread. So Django must be setup already. Soft requirement: I would not like to write the information to DB after every measurement. I would prefer to write it to a variable that can be accessed from views.py If I stop cherrypy with CTRL C, it must be stopped and not blocked because my thread is running. My thread must not prevent migrate and makemigrations from terminating. Here is my current attempt which mets only the first two requirements (CPU measurement only an example): # CPU Monitoring cpu_usage = 100 def thread_function(name): global cpu_usage while True: cpu_usage = psutil.cpu_percent(interval=2) time.sleep(2) x = threading.Thread(target=thread_function, args=(1,)) x.start() print("CPU Monitoring thread started") @api_view(["GET"]) def cpu(request): disk_object = psutil.disk_usage("/") memory_object = psutil.virtual_memory() to_gb = 1024 * 1024 * 1024 result = {"cpu_load_percent": … -
Input contains NaN, infinity or a value too large for dtype('float32'). Recommendation system django
Request Method: GET Request URL: http://127.0.0.1:8000/carreviews/recommendation/ Django Version: 2.0.2 Exception Type: ValueError Exception Value: Input contains NaN, infinity or a value too large for dtype('float32'). Here my views.py from django.shortcuts import get_object_or_404, render from .models import Review, Car from .form import ReviewForm from django.http import HttpResponseRedirect from django.urls import reverse, reverse_lazy from django.contrib.auth.models import User import datetime from django.contrib.auth import logout from django.shortcuts import redirect from django.views import generic from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User import pandas as pd import numpy as np import scipy as sp from sklearn.neighbors import NearestNeighbors def review_list(request): latest_review_list = Review.objects.order_by('')[:9] context = {'latest review_list': latest_review_list} return render(request,'review_list.html', context) def review_detail(request,pk): review = get_object_or_404(Review, id=pk) return render(request,'review_detail.html',{'review': review}) def car_list(request): car_list = Car.objects.order_by('-title')[:20] context = {'car_list': car_list} return render(request,'car_list.html', context) def car_detail(request,pk): car = get_object_or_404(Car, id=pk) form = ReviewForm() return render(request,'car_detail.html', {'car': car}) def add_review(request, pk): car = get_object_or_404(Car, id=pk) form = ReviewForm(request.POST) if form.is_valid(): rating = form.cleaned_data['rating'] comment = form.cleaned_data['comment'] user_name = form.cleaned_data['user_name'] review = Review() review.car = car review.user_name = user_name review.rating = rating review.comment = comment review.save() return HttpResponseRedirect(reverse('car_detail', args=(car.id,))) return render(request, 'car_detail.html', {'car': car, 'form': form}) def logout_view(request): logout(request) return redirect('/') class SignUp(generic.CreateView): form_class = UserCreationForm template_name ='registration/signup.html' success_url … -
add a validation error with form that contain html form and model form in Django
I am using a form in Django that contain a part html and the 2nd part tag form like this html file <div class="container"> <form action="{% url 'create_appointement_register_patient' %}" method="POST"> <p> <label for="patients">select a patient</label> <select name="patients" id="patients"> <option value="">-- select a patient --</option> {% for patient in patients %} <option value="{{patient}}">{{patient}}</option> {%empty%} <option value="nothing">nothing</option> {% endfor %} </select> </p> {{ form.media }} {{ form.as_p }} {% csrf_token %} <button type="submit" value="create_appointement_register_patient"> ok </button> </form> </div> How can I add a validation error that verifies if the patient is in the database or its not, if the value of patient is not in the database than raise an error? this is my viwes.py @login_required def create_appointement_register_patient(request): if request.user.is_doctor() or request.user.is_reception(): form_app = AppointmentForm_2(request.POST or None) user2 = get_user_model() patients = user2.objects.filter(type_of_user=TypeOfUser.PATIENT) if request.method=='POST': form_app = AppointmentForm_2(request.POST or None) if form_app.is_valid(): form_apps = form_app.save(commit=False) form_apps.user_ho_add = request.user #################### form_apps.patient = request.POST['patients'] ##################### start_time = form_apps.start_time future_time = dt.datetime(1970, 1, 1, start_time.hour, start_time.minute, start_time.second, start_time.microsecond) + timedelta(minutes=30) form_apps.end_time = dt.time(future_time.hour, future_time.minute, future_time.second, future_time.microsecond) form_apps.save() messages.success(request, 'appointment added') else: messages.error(request, 'Error') return render(request,'appointement/add_appointement2.html',{'form':form_app, 'patients':patients}) else: return render(request,'appointement/add_appointement2.html',{'form':form_app, 'patients':patients}) else: return HttpResponseRedirect(reverse("create_appointement")) and this is my forms.py class AppointmentForm_2(forms.ModelForm): doctor = forms.ModelChoiceField(queryset=User.objects.filter(type_of_user=TypeOfUser.DOCTOR)) date = … -
How to parse or round decimal point in Django template
I have a ML model that can produce a number of array which have lot of numbers after decimal point. I used joblib to extract model and used it on django to show my data. But the problem is I am not able to round up decimal point where I already used round(i,2)[its not work]. Is their any other solution which I can apply ? Here is the views.py Here is the template- home.html Output: My intension is to showing 4.38% instead of 4.387352524728998 % Please help me out, I am lost in the dark. -
Can't save data from HTML form to database Django
I'm trying to save data entered in this form (below) into a database: home.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>TODO</title> </head> <body> {% if user.is_authenticated %} <form id='add-task' method='post'>{% csrf_token %} <div class="mb-3"> <input type="text" class="form-control" name="task-name" placeholder="task name"> </div> <div class="mb-3"> <input type="text" class="form-control" name="task-desc" placeholder="description"> </div> <div class="mb-3"> <input type="text" class="form-control" name="deadline" placeholder="YYYY-MM-DD"> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </br></br> {% endif %} </body> </html> I'm not sure if I poorly formatted the code or if I'm using the wrong HTML. Is it possible to do this using HTML or should I just use a ModelForm? views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth import logout from django.contrib.auth.models import Group from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from .models import Task def home(request): # checks if user is logged in so that it can display task creation page if request.user.is_authenticated: return render(request, 'home.html', {'user': request.user}) # add new task ---> ALL THE CODE BELOW if request.method == 'POST': name = str(request.POST['task-name']) desc = str(request.POST['task-desc']) deadline = request.POST['deadline'] task = Task(task_name=name, task_desc=desc, task_deadline=deadline) task.save() #messages.success(request, "You've added a task.") return render(request, 'home.html', {}) -
Log something at beginning & end of Django management commands
Right now I have multiple management commands in my Django project. I would like to log something like [command_name] command started and [command_name] command finished at the beginning and end of the commands in a way that I would'nt repeat myself in each command. Already tried decorators on top of the handle() method but didn't think it was a good solution since I would have to decorate the handle() method in all commands. PS: I'm using python logger. -
How do I use django GenericForeignKeys?
I have the following two models: class URLResource(models.Model): class ResourceType(models.TextChoices): VID = 'VID', _('Video') DOC = 'DOC', _('Document') resource_type = models.CharField( choices=ResourceType.choices, default=ResourceType.UNK, max_length=3) title = models.CharField(max_length=280, null=True) url = models.URLField() created = models.DateTimeField(auto_now_add=True) def __repr__(self): return f'URLResource {self.resource_type}: {self.title} URL: {self.url}' class Record(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, ...) date = models.DateTimeField(default=now, blank=True) # <resource>: I want to point to a resource somehow def __repr__(self): return f'Record {{ User: {self.user}, Resource: }}' My use case is such that a lot of users can create Records and list them, but since the underlying URLResource is going to be same, I thought I could use many-to-one relationship from Records-to-URLResource so the underlying resources would remain the same. However, even though I have only one type of resource now i.e. URLResource, I also want to roll out other resources like VideoResource, PhysicalResource etc. Clearly, I can't simply use the many-to-one relationship. So, I figured I could use Django's contenttype framework, but I still can't get things to work. I want to be able to do atleast these two things: When creating a Record, I can easily assign it a URLResource (or any other Resource). I can easily access the URLResource fields. For example … -
Inlineformset_factory more than one model
I have an inlineformset factory. everything is ok, but in inline formset I would like to display additional fields from one linked table. I have exactly one element that can appear at several suppliers under different markings, and the suppliers define price thresholds with discounts for each element. I would like (simplifying) to add no more than two price thresholds to the element marking. There may usually be one. I paste the definitions of my models showing what I mean. class Component(models.Model): name = models.CharField(max_length=500) category = models.ForeignKey(D_ComponentType, on_delete=models.PROTECT) comment = models.CharField(max_length=2500, null=True, blank=True) insert_user = models.ForeignKey(User, on_delete=models.PROTECT, editable=False, related_name='insert_user') responsible = models.ForeignKey(User, null=True, on_delete=models.PROTECT, editable=False, related_name='responsible') creation_date = models.DateTimeField(default=datetime.datetime.now, editable=False) def save(self, *args, **kwargs): user = get_current_user() if user and not user.pk: user = None if not self.pk: self.insert_user = user self.modified_by = user super(Component, self).save(*args, **kwargs) def __str__(self): return self.name class Meta: verbose_name = 'Part' verbose_name_plural = 'Parts' ordering = ['name'] class ComponentItem(models.Model): component = models.ForeignKey(Component, on_delete = models.SET_NULL, null=True, related_name='item') symbol = models.CharField(max_length=100, null=True) vendor = models.ForeignKey(D_Vendor, on_delete=models.PROTECT) priority = models.IntegerField(default=0) insert_user = models.ForeignKey(User, on_delete=models.PROTECT, editable=False, ) creation_date = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): user = get_current_user() if user and not user.pk: user = None if not … -
look like css wont reload but not all the times
when I visit the page most of the times it is ok . but some times when I keep pressing refresh or for example if I am in a another page and then came back to that page via a link , page wont be shown right ,look likes it could not load the CSS file . I delete the CSS and then I reload the page and I saw page is just like those times that I mention above , so I am pretty sure it is about page's CSS . Next when page is disorder I click on refresh and page gets right another thing I should add is ,always I have this problem with large screens browsers like in laptop or pc but never experience this problem with tablet or phone and small devices I design that web site with Nice page so every page has 2 CSS (nicepage.css and page.css)files ,and 2 JS files you can visit the page here : https://www.drhosseinchi.ir/docs/first/ so what can I do ? -
celery.service: Failed with result 'signal'
I am setting up my django production project to work with celery on an ubuntu server. It works fine when i run task manually with celery -A project worker -l INFO but systemd stops every time i set it up and run. Configuration settings below. /etc/default/celeryd # most people will only start one node: CELERYD_NODES="worker1" # but you can also start multiple and configure settings # for each in CELERYD_OPTS #CELERYD_NODES="worker1 worker2 worker3" # alternatively, you can specify the number of nodes to start: #CELERYD_NODES=10 # Absolute or relative path to the 'celery' command: CELERY_BIN="/home/steph/icecream/venv/bin/celery" #CELERY_BIN="/virtualenvs/def/bin/celery" # App instance to use # comment out this line if you don't use an app CELERY_APP="homestud" # or fully qualified: #CELERY_APP="proj.tasks:app" # Where to chdir at start. CELERYD_CHDIR="/home/steph/icecream/hometutors/homestud/" # Extra command-line arguments to the worker CELERYD_OPTS="--time-limit=300 --concurrency=8" # Configure node-specific settings by appending node name to arguments: #CELERYD_OPTS="--time-limit=300 -c 8 -c:worker2 4 -c:worker3 2 -Ofair:worker1" # Set logging level to DEBUG #CELERYD_LOG_LEVEL="DEBUG" # %n will be replaced with the first part of the node name. CELERYD_LOG_FILE="/var/log/celery/%n%I.log" CELERYD_PID_FILE="/var/run/celery/%n.pid" # Workers should run as an unprivileged user. # You need to create this user manually (or you can choose # a user/group combination that already … -
How do you send django objects to javascript code?
I want to send a django object over to my javascript code when a button is clicked. The following code is present in my views.py file: def index(request): venues = Venue.objects.all() return render(request, 'index.html', {'venues':venues}) The following code is present in my index.html file: {% block content %} <script> var count = 0; function changePlayers(test_venue) { count++; document.getElementById("player").innerHTML = "Players: "+(count+{{venue.players}})+"/{{venue.total_players}}"; } </script> <h1>Venues</h1> {% for venue in venues %} <div class="card"> <div class="col-md-8"> <p class="card-text" id="player" style="margin-left: 20px">Players: {{venue.players}}/{{venue.total_players}}</p> <button type="button" class="btn btn-outline-secondary" style="margin-left: 20px; margin-bottom:20px" onclick="changePlayers({{venue}})">Book Now</button> </div> </div> {% endfor %} {% endblock %} There is an error in the 4th line of the javascript code that says Property assignment expected.javascript. My main question is how do I pass the 'venue' object to the javascript code and use it when I click the submit button. Is the way in which I went about it even possible? What would be the correct way of going about it? I'm sorry if this question is silly, I have just started learning django. -
Problem Django: Needs rebuild when i make HTML changes
The problem is as follows: If I make changes to HTML / CSS, I have to re-build the project (django) so that I can refresh at DOM. If I make changes to the .py files, it is rebuilt automatically. What can I do to rebuild them automatically when I make changes to HTML / CSS? -
Django JSONField update on Postgres fails with: "value too long for type character varying(60)"
It's my first time asking a question, so I hope I don't break any major rules. Everything works fine locally on SQLite, but not on production with PostgreSQL. Django says their JSONField uses jsonb by default, which translates to roughly 250MB. My field: my_jsonfield = models.JSONField(default=dict, blank=True) Existing data on that field looks like this (possibly already exceeding 60 chars): [ ["item_1", 1617706749], ["item_2", 1617706749], ["item_3", 1617706749] ] The error happens while I try save the serializer, something like: new_item = ["item_4", 1617708548] old_item = list(instance.my_jsonfield) combine_items = old_item + new item serializer = serializer_class(instance, data=combine_items, partial=True) if serializer.is_valid(): serializer.save() # <--- ERROR HERE I have already tried deleting all migrations and manage.py migrate <app_name> zero + played around with field options. What else am I missing here? Python 3.8.5; Django 3.1.2; djangorestframework 3.12.1; PostgreSQL 12 -
How to list objects that have same ForeignKey ettribute?
I want to list all approval steps that have the same approval_id on one page. I can list every ApprovalSteps in my views but that is not what I want. For example, I have an approval object with ApprovalProcess id is 1. I want to list all approval steps with approval_id = 1 in my template. How can I do that? models.py class ApprovalProcess(models.Model): id = models.AutoField(primary_key=True) user_id = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True, related_name='starter') doc_id = models.ForeignKey(Pdf, on_delete=models.CASCADE, null=True) ... class ApprovalSteps(models.Model): approval_id = models.ForeignKey(ApprovalProcess, on_delete=models.CASCADE, null=True) starter = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True, related_name='step_starter') ... views.py def approval_details(request, pk): approval_item = get_object_or_404(ApprovalSteps, id=pk) return render(request, 'approval_details.html', {'approval_item': approval_item}) -
getting No module named 'setuptools_rust' error while installing No module named 'setuptools_rust'
getting this error while installing django-oauth-toolkit -
How to mutual reference django serializers both defined in a same file
I defined two serializers in a same file which are UserSerializer and ProfileSerializer. Both serializers need to reference each other but I cannot reference the serializer which is defined after in file. How can I make them reference each other? class ProfileSerializer(serializers.ModelSerializer): followers = UserSerializer(many = True) class Meta: model = Profile fields = '__all__' class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer() class Meta: model = User fields = '__all__' -
Unable to update password using set_password()
I am migrating User date from another database. I have to set email as user's password. I wrote this code. users = User.objects.exclude(email__icontains='skeshari') for user in users: if user.email: password = user.email user.set_password(password) user.save() else: print('----') But this is not working. is_active flag is True for all users. I also tried individual user user = User.objects.get(email='*********@gmail.com') user.set_password('password') user.save() -
Django: is there a difference in performance between accessing the database from a view or from the template (with Template Language)?
I have been wondering for a while now. Is there a difference if for example i get a list of objects in the view and pass it to the template as context variable or if i do some gymnastics in the template and reach the information directly? For example: view + template query #view context = { 'orders' : Order.objects.filter(user=user), } #template {% for order in orders %} {{ order }} {% endfor %} Vs. {% for order in user.orders.all %} {{ order }} {% endfor %} Would the pure template query be slower because it has to perform more operations? If there is a difference how many orders would the query have to retrieve in order to have a noticeable difference between the two solutions?