Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python convert text of SVG to PNG without Cairo
I have been working for about 20+ hours and I'm stuck. I have a Django app deployed on azure web apps. In one of my django views, I was able to successfully convert an svg to png on my local device with Cairo, however, Cairo requires homebrew to execute brew install pango. As such, Cairo is completely out of the picture to convert SVG to PNG. I also looked into using svglib and running from svglib.svglib import svg2rlg, however svg2rlg(input) requires input to be the name of a file. Because I'm using Django and I'm running a webapp, I certainly want to avoid creating files. How would one go about converting svg to png without cairo. Can I somehow input text, something like string="""<?xml version="1.0" standalone="no"?> <svg width="200" height="250" version="1.1" xmlns="http://www.w3.org/2000/svg"> <line x1="10" x2="50" y1="110" y2="150" stroke="orange" stroke-width="5"/> <polyline points="60 110 65 120 70 115 75 130 80 125 85 140 90 135 95 150 100 145" stroke="orange" fill="transparent" stroke-width="5"/> </svg>""" into svg2rlg? Can I simply download the Cairo library to the Django project folder? -
request.POST always empty
I'm trying to send data from my form to a view with ajax, but my form fields in request.POST are empty.My fields during the submission do contain the data. But when I check the contents of request.POST the form data is still empty. So the form.is_valid value is always False. How can i solve this problem? here is my form <form id="formId" method="post"> {% csrf_token %} {{form.errors}} {% for field in form %} <div class="input-group mb-3"> <span class="input-group-addon bg-white"> <i class="{% if field.html_name == 'email' %} fa fa-envelope {% else %} fa fa-user w-4 {% endif %}"> </i></span> {{field}} </div> {% endfor %} <div class="row"> <div class="col-12"> <button type="submit" id="btnRegister" class="btn btn-primary btn-block px-4">Créer le compte</button> </div> </div> </form> ajax <script> $(document).ready(function(){ $("#btnRegister").on("click",function(e){ var form = document.getElementById("formId"); function handleForm(event) { event.preventDefault(); } form.addEventListener('submit', handleForm); }); }); var serializeData = $("#formId").serialize(); var nom_agent = $("#id_nom_agent").val(); var prenom_agent = $("#id_prenom_agent").val(); var email = $("#id_email").val(); $.ajax({ dataType: 'json', url: "{% url 'add_agent' %}", type: 'post', data: { "csrfmiddlewaretoken" : "{{ csrf_token }}", 'nom_agent': nom_agent, 'nom_agent': prenom_agent, 'email': email, }, success: function(data){ console.log("ok"); }, error: function(){} }); </script> My view is the following def add_agent(request): if request.is_ajax(): if request.method=="POST": print(request.POST) form = RegisterForm(request.POST) if … -
How to receive AJAX POST data in a view Django?
So I have a button called Print Label, which on click should send some data to a view, and then my view should display that data in an html page. So far, it seems like I have been able to save the data as I can see it using the alert method using JS. However, when I POST this data using AJAX, it seems like the data is not going through as my view is not recognizing the POST call(I am getting a 404 page). url for view: path('label/', plabel, name="label.html"), Saving data on click function: $("#table").on('click','.btn-outline-primary',function(){ // get the current row var currentRow=$(this).closest("tr"); var col1=currentRow.find("td:eq(0)").html(); // get current row 1st table cell TD value var col2=currentRow.find("td:eq(1)").html(); // get current row 2nd table cell TD value var col3=currentRow.find("td:eq(2)").html(); // get current row 3rd table cell TD value var col4=currentRow.find("td:eq(3)").html(); var col5=currentRow.find("td:eq(4)").html(); var col6=currentRow.find("td:eq(5)").html(); var col7=currentRow.find("td:eq(6)").html(); var col8=currentRow.find("td:eq(7)").html(); var col9=currentRow.find("td:eq(8)").html(); var col10=currentRow.find("td:eq(9)").html(); var col11=currentRow.find("td:eq(10)").html(); var col12=currentRow.find("td:eq(11)").html(); var col13=currentRow.find("td:eq(12)").html(); var col14=currentRow.find("td:eq(13)").html(); var mydata= [col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, col13, col14]; AJAX call: $.ajax({ url: "/label/", type: "POST", data:{ csrfmiddlewaretoken: '{{ csrf_token }}', mydata: mydata}, }); alert(mydata); //this is showing my data has been saved Picture … -
Get_next_by_FOO method incorrectly returns link
My problem is that I specify the get_next_by_FOO method, but the link does not work correctly. #models.py class Project(models.Model): user = ForeignKey(settings.AUTH_USER_MODEL, on_delete=CASCADE, db_index=True) name = CharField(max_length=150, db_index=True) cover = models.ImageField( upload_to="project_photos/", null=True, blank=True ) site = URLField( max_length=200) description = TextField() note = CharField( max_length=150) created_at = DateTimeField(auto_now_add=True) def next(self): return self.get_next_by_created_at() def pre(self): return self.get_previous_by_created_at() #html <a href="{{ project.next }}">Next project</a> <a href="{{ project.pre }}">Previous project</a> And it gives out the following link: http://localhost:8000/projects/8/%D0%9D%D0%BE%D0%B2%D0%B0%D1%8F%20%D1%80%D1%83%D0%B1%D1%80%D0%B8%D0%BA%D0%B0 The id of the model does not change, and the name of the next or previous model instance is appended to the end of the link -
How can I access this email attribute as self if it's a class attribute?
How am I able to print the email as self.email if it's a class attribute? Wouldn't we have to pass it to the parent class via the super function to do that? class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=100, unique=True) # Required fields date_joined = models.DateTimeField(verbose_name="date_joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last_login", auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email -
Is there an easy way to ignore duplicates with django models unique=TRUE?
class Reddit_Submission(models.Model): submission_id = models.CharField(max_length=32, unique=True) submission_time_stamp = models.CharField(max_length=32) submission_title = models.CharField(max_length=32) submission_score = models.CharField(max_length=32) submission_author = models.CharField(max_length=32) submission_url = models.CharField(max_length=32) I have the above code sample from my Model within my django application. My question is, Is there a easy way to ignore a "Example = model.save()" if something is duplicated within the database already? Thanks -
Django: Is there a Context passed automatically to the templates?
Is there some hidden context that is passed automatically by Django to the templates (without I write it in the views.py or settings.py)? -
How to attach and upload profile image through model in angular
I am using a model to POST data to api , model also has image field.How can i attach image data to coverImage field. Whenever i send post request it return a error that coverImage is not a file. export class NewCourseModel { instructorId:number; title:string; subtitle:string; description:string; language:string; category:string; subcategory:string; price:number; creationDate:Date; coverImage:File; promoVideo:File; } export class CreateCourseComponent implements OnInit { newCourseForm: FormGroup; newCourseModel: NewCourseModel; newSectionModel = new courseSectionModel(); newLectureModel = new courseLectureModel(); newSectionFormArray=[]; formSteps:any = 1; userID; selectedCourseImage: File = null; selectedCourseVideo: File = null; imageUrl = "/assets/images/courses/add_img.jpg"; videoUrl = "/assets/images/courses/add_video.jpg"; imageFileName = "No Image file selected"; videoFileName = "No Video file selected"; courseCategories: courseCategories[]; courseSubCategories: courseSubCategories[]; constructor(private _authService: AuthService, private _courseService: CoursesService) { this.newCourseModel = new NewCourseModel(); // this.courseCategories = new courseCategories(); // this.courseSubCategories = new courseSubCategories(); } ngOnInit(): void { this.InitializeForm(); this.getCourseCategories(); this.newSectionModel = new courseSectionModel(); this.newSectionFormArray.push(this.newSectionModel); } addSection(){ this.newSectionModel = new courseSectionModel(); this.newSectionFormArray.push(this.newSectionModel) } removeSection(index){ this.newSectionFormArray.splice(index); } InitializeForm(): any { this.newCourseForm = new FormGroup({ title: new FormControl('', [Validators.required]), subtitle: new FormControl('',[Validators.required]), description: new FormControl('',[Validators.required]), language: new FormControl('',[Validators.required]), category: new FormControl('',[Validators.required]), subcategory: new FormControl('', [Validators.required]), price: new FormControl('', [Validators.required]), // creationDate: new FormControl('', [Validators.required]), // updatedDate: new FormControl('', [Validators.required]), coverImage: new FormControl('', [Validators.required]), promoVideo: new FormControl('', [Validators.required]), … -
When I log out, I find this error "detail": "Authentication credentials were not provided."
I am using django-rest-knox, when I logout using knox_views.LogoutAllView.as_view(), it gives me this error "detail": "Authentication credentials were not provided." note: I am using a custom user model(AbstarctUser and BaseUserManager) here is serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email','birth_date','first_name','last_name') # there is a registerserializer too class LoginSerializer(serializers.Serializer): email = serializers.EmailField() password = serializers.CharField() def validate(self, data): user = authenticate(**data) if user and user.is_active: return user raise serializers.ValidationError("Incorrect Credentials") and here's views.py class LoginView(generics.GenericAPIView): serializer_class = LoginSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user= serializer.validated_data return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) -
DRF Project Static Files Problem On Server
I'm trying to host the project I prepared on PythonAnywhere. Even though I run the collectstatic command, I can't get any results. When I visit the url, the design does not appear, the same is true for the Admin. When I looked, the requested address is static file instead of static_base. But static_url and static_root should have different names anyway. Do I need to add something related to this field in the urls.py file? Because I haven't seen anything like it when I read it. Settings.py import os from pathlib import Path from datetime import timedelta # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'key' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.SessionAuthentication' ], } SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME" : timedelta(minutes = 15) } ALLOWED_HOSTS = ["talhakoylu.pythonanywhere.com"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "rest_framework", "book", "country", "account", "school", "nested_inline", "quiz" ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', … -
How to add more fields in django-allauth User model?
I want to add more fields in Django allauth user model. I created a User-Profile model in a one-to-one relation with auth-user and tried to create user-profile object in form.py. But this method is not working. Here is my code: models.py class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) forms.py class CustomSignupForm(SignupForm): profile_picture = forms.ImageField() def signup(self, request, user): profile_picture = self.cleaned_data['profile_picture'] user.save() UserProfile.objects.create(user=user, profile_picture=profile_picture) return user -
DetailView + input button
I would like to add a button to "validate" a user towards the next step of his registration. The staff member have to "validate" the user in the user detail page. So I created a DetailView view with template with all the details of this user. But I would like to know if it is possible to write code in DetailView function to allow the user to increment his step_registration variable when I click on "validate" ? Here is my DetailView function : views.py class StudentDetailView(DetailView, LoginRequiredMixin): model = Student login_url = login student_detail.html {% block content %} <h1>Etudiant: {{ student.user.firstname }} {{ student.user.firstname }}</h1> <ul> {% if student.photo %} <li> Photo :<img src="{{ student.photo.url }}", width = 250, height = 300>"> </li> {% endif %} <li> Etat de l'inscription : {{ student.step_registration }}</li> <li> Date de naissance : {{ student.birthdate }} </li> </ul> <button class="btn btn-secondary"> Validate ! </button> {% endblock %} The step registration variable is called "step_registration", so I want to do student.step_registration += 1 when a staff member click on "validate" -
CS50 Project 1 Search bar Question: How do I make the search bar filter through the entries to find the possible ones and display them in a list?
I am working on CS50 Project 1 to make a search bar that searches through the possible wikipedia-like entries using Django. If you type in the exact name of the title, you will be redirected to that entry page. How do I display a list of possible entries using the query? views.search def search(request): entry_list = util.list_entries() query = request.GET.get("q", "") if query in entry_list: return redirect(get_entry, query) else: results = [] for entry in entry_list: if query in entry: results.append(entry) return render(request, "encyclopedia/index.html", { "entry": results }) index.html {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia {% endblock %} {% block body %} <h1>All Pages</h1> <ul> {% for entry in entries %} <a href = "wiki/{{ entry }}"><li>{{ entry }}</li></a> {% endfor %} </ul> {% endblock %} If anything but the exact title is searched for, the user receives a blank page. How do I fix this? -
how to modify the field value of a model when another field value of another model changes?
I have 4 models: reputation, goldbadge, sylverbadge and bronzebadge would like to add 1 in the bronzebadge model when the reputation model score reaches 100 score and this must be done automatically here are my models class reputation(models.Model): score=models.BigIntegerField(default=0) user=models.ForeignKey(User,on_delete=models.CASCADE,related_name="reputation_user") def __str__(self): return self.score class goldBadge(models.Model): score=models.BigIntegerField(default=0) user=models.ForeignKey(User,on_delete=models.CASCADE,related_name="goldbadge_user") def __str__(self): return self.score the other models are almost identical My concern is that when saving the reputation model we will first check if the score is greater than or equal to 100 if yes then we increase the value of sylverbadge by 1 I am only a beginner in python and django so your help will do me a lot of good thank you for your answers already -
Django -Python Copyfile using win32api permission denied
I was looking to implement a copy on the server where I click a button on the client side html of my web server and the server implements a copy of a particular file inside the server from a fixed destination to another destination inside the server itself. The server is windows based so I was using the win32api CopyFile method but it shows access denied error . How can I resolve this issue? I have tried setting permissions of the drive. It seems as if Django needs administrative privileges for this but not sure. Other solutions are welcome. -
django models containing list of another model
I have to implement adding different pages/urls to the favorities from a list of pages. I am using django and have a user class inbuilt and provided by django, a page class like this class Page(models.Model): ... category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=TITLE_MAX_LENGTH) url = models.URLField() Below is category class class Category(models.Model): ... name = models.CharField(max_length=NAME_MAX_LENGTH, unique=True) ... I have to store this list of pages per user as their favorites. I can think of it like many users will store many pages and therefore, add a field to the User model like this : pageToSave = models.ManyToMany(Page) or I can think of it like one user saves many pages and implement it like this class Page(models.Model): ... category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=TITLE_MAX_LENGTH) url = models.URLField() **fk = models.ForeignKey(User, on _delete=models.CASCADE)** Which if any approach is correct or otherwise, what can you suggest? -
I tryed to create a db usign python and django and have a method "DELETE" that don't execute and return error 500 in postman
Just new to python programming, Django SQL, and try to create a DB, verify it with Postman and SQLLiteStudio! Using Django to create a DB and python (3.9.6).When I run the DELETE method, in postman return error 500 without executing DELETE. {In my cmd I don't see any error msg} [error msg in Postman trying to execute DELETE ] : https://i.stack.imgur.com/tspKr.png Views : from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from django.http.response import JsonResponse from EmployeeApp.models import Departments,Employees from EmployeeApp.serializers import DepartmentSerializer,EmployeeSerializer # Create your views here. @csrf_exempt def departmentApi(request,id=0): if request.method=='GET': departments = Departments.objects.all() departments_serializer = DepartmentSerializer(departments, many=True) return JsonResponse(departments_serializer.data, safe=False) elif request.method=='POST': department_data=JSONParser().parse(request) department_serializer = DepartmentSerializer(data=department_data) if department_serializer.is_valid(): department_serializer.save() return JsonResponse("Added Successfully!!" , safe=False) return JsonResponse("Failed to Add.",safe=False) elif request.method=='PUT': department_data = JSONParser().parse(request) department=Departments.objects.get(DepartmentId=department_data['DepartmentId']) department_serializer=DepartmentSerializer(department,data=department_data) if department_serializer.is_valid(): department_serializer.save() return JsonResponse("Updated Successfully!!", safe=False) return JsonResponse("Failed to Update.", safe=False) elif request.method=='DELETE': department=Departments.objects.get(DepartmentId=id) department.delete() return JsonResponse("Deleted Succeffully!!", safe=False) Models: from Django.DB import models class Departments(models.Model): DepartmentId = models.AutoField(primary_key=True) DepartmentName = models.CharField(max_length=100) class Employees(models.Model): EmployeeId = models.AutoField(primary_key=True) EmployeeName = models.CharField(max_length=100) Department = models.CharField(max_length=100) DateOfJoining = models.DateField() PhotoFileName = models.CharField(max_length=100) Serializers: from EmployeeApp.models import Departments, Employees class DepartmentSerializer(serializers.ModelSerializer): class Meta: model=Departments fields=('DepartmentId','DepartmentName') class EmployeeSerializer(serializers.ModelSerializer): class Meta: model=Employees fields=('EmployeeId', 'EmployeeName', 'Department', 'DateOfJoining', 'PhotofileName') … -
Django admin 'view on site' returns NoReverseMatch, but urls all work from elsewhere
I posted an earlier version of this question here, but most of that has been cleared up and now I just have this one more narrow issue I can't solve: I consistently get NoReverseMatch errors when using ‘view on site’ from within the admin. This is an example of the error: NoReverseMatch at /admin/r/10/5/ Reverse for 'WorklogDetail_url' with keyword arguments '{'app_label': 'ktab', 'slug': 'hattie-and-deadline'}' not found. 1 pattern(s) tried: ['ktab/work/(?P[-a-zA-Z0-9_]+)/$'] However, if I type the url into the address bar myself, or click on it from ListView, it comes up just fine. I've learned that 'view on site' does not use my view, but one called 'shortcut'. I also understand that this view searches by content type and object id, rather than my kwargs or slug. I verified that both are correct in the admin's url format, like /admin/r/10/5/, but I don't know what the '/r/' stands for. Anyway, that's where I'm stuck. Your help appreciated. Thanks. -
Cannot use a slash in a variable for filtering a Django query?
While querying data for a template this is working: prev_season_gws = PlayerGW.objects.filter(player=player, season="2020/21") This is not working: previous_season = functions.previous_season # The function is returning a string of "2020/21" prev_season_gws = PlayerGW.objects.filter(player=player, season=previous_season) Why isn't it working with a variable? I also tried to wrap the previous_season variable with the str() function without success. -
Duplicate app naming issue in Django without renaming the app
I know there are a few other posts about this out there and renaming my messages app might solve the issue, but I don't want to change the name of my messages app, and the label solution from this post just returns this error instead: django.core.exceptions.ImproperlyConfigured: The app label 'email.messages' is not a valid Python identifier. And the above error is after adding the label and default_app_config fields to MessagesConfig like the other post suggests: class MessagesConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'messages' label = 'email.messages' default_app_config = 'messages.apps.MessagesConfig' My INSTALLED_APPS in settings.py is as follows: INSTALLED_APPS = [ # my apps # 'accounts', 'subscribers', 'django_filters', 'accounts.apps.AccountsConfig', 'core', 'messages', # 'messages.apps.MessagesConfig', # 'email.messages', # django apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] And I'm getting this error: django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: messages What's the actual workaround for this (other than renaming messages to a different app name)? Thanks... -
How can i control model fields in for loop in django?
I am new to django. I am trying to build an Quiz web application that puts one question at a time and as soon as student select one answer on radio button , it immediately shows response whether his ans is correct or incorrect. If incorrect, it shows them the right ans.Then after clicking on submit button next ques appears. After last question, result is shown to them. I have 2 problems- 1.My first problem is i am not able to put one ques at a time from all set of questions. However i am able to put all questions at a time. How can i do that? 2.My second problem is i don't know , how i will go to next ques after clicking on submit button. Below are my files. Please help me with this. I will be highly grateful to you. -
how to fetch product size too with product and its quantity in django
I want to fetch user selected size with the quantity and product but I don't understand how to do that any how idea to achieve that i try to look documentation but didn't find one any idea how to do that my views.py for add to cart class Product_detail(View): def get(self, request, item_id,): item = Item.objects.filter(id=item_id) category_list = Categories.objects.all() items = Item.objects.all() print(item) return render (request, 'product_detail.html',{"items" : item, 'category_list': category_list, 'item': items }) def post(self, request, item_id): item = request.POST.get('item') size = request.POST.get('size') cart = request.session.get('cart') if cart: quantity = cart.get(item) if quantity: cart[item] = quantity+1 else: cart[item] = 1 else: cart = {} cart[item] = 1 request.session['cart'] = cart print(request.session['cart']) return redirect('products:detail', item_id=item_id) my html code <form method="POST" action="#{{ item.id }}"> {% csrf_token %} <input type="text" hidden value="{{item.id}}" name="item"> <label class="size" for="size">Size:</label> <p class="input"><input type="radio" name="size" value="S"> <span>S</span> <input type="radio" name="size" value="M"> <span>M</span> <input type="radio" name="size" value="L"> <span>L</span> <input type="radio" name="size" value="XL"> <span>XL</span> <input type="radio" name="size" value="2XL"> <span>2XL</span></p> <button type="submit" class="cart btn btn-outline-primary">Add to cart</button> </form> right now I am only able to fetch its item id and quantity any suggestion will be appreciated thank you -
ModuleNotFoundError: No module named 'ckeditor', how do i solve this?
I have ckeditor installed inside venv. in my setting, i also added ckeditor and ckeditor_uploader in my setting, i also added to requirements.txt. but nothing seems to work still get ModuleNotFoundError: No module named 'ckeditor' here is my setting.py THIRD_PARTY_APPS = [ 'ckeditor', 'ckeditor_uploader', ] CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js' CKEDITOR_UPLOAD_PATH = 'images/' CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_CONFIGS = { 'default': { 'toolbar': None, }, } urls.py urlpatterns = [ path('_ckeditor/', include('ckeditor_uploader.urls')), ] models.py from ckeditor_uploader.fields import RichTextUploadingField class About(models.Model): name = models.CharField(max_length=50) about_text = RichTextUploadingField() def __str__(self): return str(self.name) -
How to filter a child object's parent field for Django
I want to have a form with fields that are filtered based on Django group model name field. For example, I have a model that is connected to Django User model which is connected to Django group model like so: class customUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.first_name I have added a row of data in Django group using Django admin panel called 'Teacher'. What I'm trying to do is to have my form list only customUser that is listed as "Teacher" in Django group model. My form: class myForm(ModelForm): class Meta: model = customUser fields = ['user '] def __init__(self,*args,**kwargs): super (myForm,self ).__init__(*args,**kwargs) **# What I want to achieve but doesnt work.** self.fields['user'].queryset = customUser.objects.filter(user.group.name = "Teacher") Any help is greatly appreciated. -
Django dirtyfields - can we access the before and after state?
I'm interested in using django-dirtyfields to track if a field is changed. I also want to access what the field was before and after the change and I'm not sure how to do this. class GradeBookSetup(DirtyFieldsMixin, models.Model): user = models.OneToOneField(CustomUser, on_delete=CASCADE) scale_mode = models.CharField(max_length=7, blank=True, default='MOE') def save_model(self, request, obj, form, change, *args, **kwargs): # need to save user to each object obj.user = request.user if self.is_dirty(): dirty_fields = self.get_dirty_fields() if 'scale_mode' in dirty_fields: if scale_mode_before == 'MOE' and scale_mode_after == 'MOEPLUS': super().save_model(request, obj, form, change, *args, **kwargs) I looked at the source code for dirtyfields but I'm not at the level yet which I can understand everything that it's doing and how I can access values from it.