Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to access list items in django jinja template dynamically using variable indexing
Django jinja template error - TemplateSyntaxError I was trying to create sample show users page where I am want to show username, password and role of the users. I will be storing role as numbers and later I am trying to get the role name from a list. I have hard coded this role names to a list roles = ['admin', 'teacher', 'student'] this roles has been passed to html page as context value. Also, I am passing a num variable for accessing the list items(atm its value is also hard coded, I will be changing this in future) views.py def index(request): roles = ['admin', 'teacher', 'student'] num=1 return render(request=request, template_name='show_all.html', context={'roles': roles, 'num': num}) and inside my html page I am trying to access this list using num variable as given below show_all.html {{roles[num]}} but it is throwing an error TemplateSyntaxError at /show_all Could not parse the remainder: '[num]' from 'roles[num]' there are few solutions that saying roles.0 will get you the first result and roles.1 will give next, But I don't want to hard-code the index there. requirements.txt asgiref==3.5.2 Django==4.1.3 sqlparse==0.4.3 tzdata==2022.6 I have tried {{roles.num}} {{roles.get(num)}} {{roles[num]}} nothing is giving me desired result. -
Django - 'object is not iterable' error but there are no iterations on my object
I have a Model called Request with a Many-To-One model relationship where a User can have multiple Request objects. A Request is a custom made painting Model with many fields. I am just trying to isolate the specific Request object the User clicked on and show it on a separate template called 'requestcarousel'. I am not running any for loops on the object so I am not sure why I am getting an 'object is not iterable' error. I've tried to use filter instead of get which doesn't give an error but none of the objects are being shown Here is my view: def requestcarousel(request, pk=None): if request.method == 'GET': allRequests = Request.objects.filter(requested_user=request.user.pk) requestedPaintings = allRequests.get(pk=pk) context = { 'requestedPaintings': requestedPaintings, } return render(request, "requestcarousel.html", context) Here is requestcarousel.html: {% extends "index.html" %} {% load i18n %} {% load static %} {% static "images" as baseUrl %} {% block request_carousel_content %} {% get_current_language as LANGUAGE_CODE %} <!-- START CAROUSEL --> <div class="card"> <!-- Title --> <div class="container p-2"> {% if requestedPaintings %} {% if LANGUAGE_CODE == 'ja' %} <div class="card-title p-3"> <h4>{{requestedPaintings.name}} </h4> </div> {% else %} <div class="card-title p-3"> <h4>{{requestedPaintings.english_name}} </h4> </div> {% endif %} {% endif %} </div> … -
Django - How to prevent form reload if entered incorrectly
I have the following login form: <input type="text" placeholder="Username" name = "username" /> <input type="password" placeholder="Password" name = "password" /> <button type = "submit" name = "submit" value = "sign_in" >Log In</button> {% for message in messages %} <p id = "messages" style = "color:red; font-weight: bold;" class = "errormessage">{{message}}</p> {% endfor %} In the event that the user incorrectly enters their username/password, I display an error, working with the following view: if (request.POST.get('submit') == 'sign_in'): #-----------SIGN IN FUNCTION---------- context = {} if request.user.is_authenticated: return HttpResponseRedirect("/levels/1") # redirect 2 dashboard else: if request.method == 'POST': # if user isnt already logged in username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) #authenticate user if user is not None: # if user exists login(request, user) return HttpResponseRedirect("/levels/1") # redirect to dashboard else: # if user entered username/password wrong context = {'ALERT':"Username OR password is incorrect"} messages.error(request, 'Username OR password is incorrect') However, the form doesn't work as expected. When the user incorrectly enters the form, the page refreshes and the user has to click back on the Log In button to view the error (the login form is a small modal that comes up) I want to make it so … -
django how to create custom id
I'm trying to create an custom id for my project the id should contain the course,schoolyear,semester then incrementing number that start with 00 When I post something like this in ex. Postman { "sem": "1", "sy": "2022-2023", "studentid": "2019-0478" "course": "ENGG" } it will create something like this ENGG2022-20231-00 but the error is saying django.db.utils.DataError: value too long for type character varying(20) for now this is what I got def get_default_id(): last_CI_id = CourseItem.objects.all().order_by('CI_id').last() if not last_CI_id: return str(CourseItem.office) + str(CourseItem.sy) + str(CourseItem.sem) + '00' Even if I remove the others like return str(CourseItem.sy) + '00' it still will return the same error class CourseItem(models.Model): CI_id = models.CharField(primary_key=True, max_length=20, default=get_default_id) studentid = models.CharField(max_length=9, blank=True, null=True) course = models.ForeignKey('Course', models.DO_NOTHING, blank=True, null=True) sem = models.CharField(max_length=1, blank=True, null=True) sy = models.CharField(max_length=9, blank=True, null=True) Hope someone can help and if this is not gonna work atleast can I have some alternative solution to this problem -
how to add a text box to django forms.MultipleChoiceField?
when use "widget=forms.Select" there is text box automatically added, but when use "widget=forms.CheckboxSelectMultiple" there are no text box around the choices. How to add the text box please? in the forms.py SEGMENTATION = ( (HIGH, 'High'), (MEDIUM, 'Medium'), (LOW,'Low') ) segmentation = forms.MultipleChoiceField( # widget=forms.Select, widget=forms.CheckboxSelectMultiple, choices=SEGMENTATION ) in html <div class="col-xs-5"> {% bootstrap_field offer_form.segmentation %} </div> [![now it looks like this][1]][1] [1]: https://i.stack.imgur.com/sbc6y.png -
Am trying to create a user request from an existing model object but If statement on 2 instances of object is not working for me
Here's my model class Users_Balanc(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) Amount = models.FloatField(max_length=4, default=0.0) Profit = models.FloatField(max_length=30, default=0.0) Bonus = models.FloatField(max_length=30, default=10.0) Referral_Bonus = models.FloatField(max_length=30, default=0.00) Deposit = models.FloatField(max_length=30, default=0.00) Withdrawals = models.FloatField(max_length=30, default=0.00) def __str__(self): return f'{self.user.username} Users_Balanc' And my view def withdrawal_request(request): if request.method == 'POST': Amount = request.POST['Amount'] username = request.GET.get['username'] total = Users_Balanc.objects.all() if (total.Amount <= Amount): New_Request = Request.objects.create(value=Amount, user=username) New_Request.save messages.info(request, 'Successful') return HttpResponse('Request sent sucessful') else: return HttpResponse('Insufficient funds') For more clarification, am using ajax post request method on the html page to return the response For more clarification, am using ajax post request method on the html page to return the response -
Why is My Ordered List with Template Variable is Showing the Numeral One for Each Entry?
I'd appreciate your help figuring out why my ordered list with template variables shows the numeral one for each entry. I'd also like to know how to correct this and present an ascending list. Here's what's happening: I am trying to show the top three selling items. One of the top items has a three-way tie, so I should show five items. I see five items, but each is labeled as number one. Here's what it looks like: Here's my code: views.py class ReportView(LoginRequiredMixin, TemplateView): template_name = "inventory/reports.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["purchases"] = Purchase.objects.all() revenue = Purchase.objects.aggregate( revenue=Sum("menu_item__price"))["revenue"] total_cost = 0 for purchase in Purchase.objects.all(): for recipe_requirement in purchase.menu_item.reciperequirement_set.all(): total_cost += recipe_requirement.ingredient.unit_price * \ recipe_requirement.quantity purchases = Purchase.objects.values( 'timestamp', item_name=F('menu_item__name'), item_price=F('menu_item__price'), item_desc=F('menu_item__description')) df = read_frame(purchases) grouped_purchases = df.groupby('item_name')[ 'timestamp'].count().reset_index() sort_purchases = grouped_purchases.sort_values("timestamp", axis=0, ascending=False, ignore_index=True) top_3 = sort_purchases.nlargest(3, 'timestamp', keep='all') list_of_top_3_purchases = top_3['item_name'].to_list() context["revenue"] = revenue context["total_cost"] = total_cost context["profit"] = revenue - total_cost context["gross_profit"] = (revenue - total_cost) / total_cost * 100 context["gross_margin_ratio"] = (revenue - total_cost) / revenue * 100 context["list_of_purchases"] = list_of_top_3_purchases return context reports.html ... <section style="color: black;"><h2>Top 3 Purchases</h2> {% for item in list_of_purchases %} <ol> <li>{{ item }}</li> </ol> {% endfor … -
how can I store more objects from another class in other classes Field
I've been looking for my problem in Django documentation and couldn't find solution. My problem is that in Api Pannel I cannot insert more objects from "ActorsAndDirectors" class into "cast" Field in "Movie" class. I can only insert one. How to transfrom cast field so I could insert multiple objects from "ActorsAndDirectors" class into "Movie" class this is the code ` class ActorsAndDirectors(models.Model): name = models.CharField(max_length=32, blank=False, null=False) surname = models.CharField(max_length=32, blank=False, null=False) role = models.CharField(max_length=11, blank=False, null=False) def __str__(self): return f"{self.name} {self.surname}" class Movie(models.Model): title = models.CharField(max_length=50, blank=False, null=False, unique=True) description = models.TextField(max_length=400) cast = models.ForeignKey(ActorsAndDirectors, on_delete=models.CASCADE) premiere = models.DateField() updated = models.DateTimeField() slug = models.SlugField() def number_of_ratings(self): return Rating.objects.filter(movie=self).count() def avg_rating(self): score = 0 ratings = Rating.objects.filter(movie=self) for rating in ratings: score +=rating.stars if len(ratings) > 0: return score/len(ratings) else: return 0 def __str__(self): return f"{self.title}, ({self.premiere})" ` I looked through Django documentation for some kind of list Field but with no good results. Im looking for help how to transform the field or maybe some other explanation of my problem -
How to catch scrapy response from spider to pipeline?
I need all the scrapy response with settings, pipelines, urls and everything in pipeline where i create model objects? Is there any way of catching it? pipeline.py class ScraperPipeline(object): def process_item(self, item, spider): logger = get_task_logger("logs") logger.info("Pipeline activated.") id = item['id'][0] user= item['user'][0] text = item['text'][0] Mail.objects.create(user=User.objects.get_or_create( id=id, user=user), text=text, date=today) logger.info(f"Pipeline disacvtivated") spider.py class Spider(CrawlSpider): name = 'spider' allowed_domains = ['xxx.com'] def start_requests(self): urls = [ 'xxx.com', ] for url in urls: yield scrapy.Request(url=url, callback=self.parse, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, ' 'like Gecko) Chrome/107.0.0.0 Safari/537.36'}) def parse(self, response): item = MailItem() for row in response.xpath('xpath thins'): ip['id'] = row.xpath('td[1]//text()').extract_first(), ip['user'] = row.xpath('td[2]//text()').extract_first(), ip['text'] = row.xpath('td[3]//text()').extract_first(), yield item I've tried to call response from pipeline, but i have only item. Also the things from created object are not enough from me. Any ideas? -
What is a proper way to write Django model mixin?
I am writing Django project that has a bunch of similar models, so i decided to write some mixins to structure them. What is a best implementation? -
Add custom command to existing django app
I have installed a thirdpartyapp. After installing my ./manage.py --help has an entry like this, $ ./manage.py --help ... [thirdpartyapp] thirdparty_cmd1 thirdparty_cmd2 ... Now I have created thirdparty_cmd1_extra by extending thirdparty_cmd1. I have put it in my application directory. So it looks like $ ./manage.py --help ... [myapp] thirdparty_cmd1_extra [thirdpartyapp] thirdparty_cmd1 thirdparty_cmd2 ... What I want is this, $ ./manage.py --help ... [thirdpartyapp] thirdparty_cmd1 thirdparty_cmd1_extra thirdparty_cmd2 ... -
Query Django ORM three tables with totals
I have three tables CATEGORIES, TIPODESPESA and EXPENSE. I would like to perform a simpler and faster query to return the total expenses grouped by TYPODESPESA and by CATEGORY. The expected result is the one below: enter image description here What I would like is a result in which the totals are grouped first by CATEGORY, then by TYPE EXPENSE and then show the EXPENSES. However, for me to be able to do this, I perform the following queries below and I'm trying to simplify and make it faster, but I'm still learning a few things. If you can help with the query. registros = CategoriaDespesa.objects.filter( tipodespesas__tipodespesa_movimentodespesa__data__lte=data_final, tipodespesas__tipodespesa_movimentodespesa__data__gte=data_inicio, ) \ .order_by('description') categorias_valores = CategoriaDespesa.objects.filter( tipodespesas__tipodespesa_movimentodespesa__data__lte=data_final, tipodespesas__tipodespesa_movimentodespesa__data__gte=data_inicio, tipodespesas__tipodespesa_movimentodespesa__company=company.company) \ .values('id').annotate(total=Coalesce(Sum( F("tipodespesas__tipodespesa_movimentodespesa__valor"), output_field=FloatField()), 0.00)) tipos_valores = TipoDespesa.objects.filter( tipodespesa_movimentodespesa__data__lte=data_final, tipodespesa_movimentodespesa__data__gte=data_inicio, tipodespesa_movimentodespesa__company=company.company).values('id') \ .annotate(total=Coalesce(Sum(F("tipodespesa_movimentodespesa__valor"), output_field=FloatField()), 0.00)) The classes I'm using are: class CategoriaDespesa(models.Model): description = models.CharField(max_length=200, help_text='Insira a descrição') active = models.BooleanField(default=True, help_text='Esta ativo?', choices=CHOICES) user_created = models.ForeignKey(User, on_delete=models.PROTECT) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class TipoDespesa(models.Model): category = models.ForeignKey( CategoriaDespesa, on_delete=models.CASCADE, related_name="tipodespesas") description = models.CharField(max_length=200, help_text='Insira a descrição') active = models.BooleanField(default=True, help_text='Esta ativo?', choices=CHOICES) user_created = models.ForeignKey(User, on_delete=models.PROTECT) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Despesa(models.Model): company = models.ForeignKey( Company, on_delete=models.CASCADE, related_name="companies_movimentodespesa") tipodespesa … -
Django project - where to put the script?
I am new to python. I am learning django. I made a script that finds certain words on different sites. I give a list of words and a list of sites. As a result, after crawling sites through selenium, I get the result using pandas in the form of a csv file. I want to visualize my project, make a simple web page that will have two windows. In the first window, the user enters a list of words. In the second window - enters a list of sites. Task: check if these words are on these sites. Display the result during the calculation in the form of a table, each time updating it. In the format - link -- found words What should be the structure of my django project? If I understand correctly, then you first need to write the forms in forms.py. What to do next? Where should I put my original script? Thanks this is an example of what I want to see on my page Sorry for the primitive drawing:) -
database viewer for server?
We have a few proprietary tools that store data in rather standard database, using those tools is a pain in the ass. (A common example is a part number database - with some details, and for example a link to a PDF manufactuer data sheet) Getting access to that tool is an issue. For me - 99% of the time - If I could open a giant txt dump of the database and search it using EMACS or VI - I can find what I need. What I'm looking for is a simple (Apache or IIS server) application that I can do that with HTML against the database. Needs to be able to: (A django thing would be great, we already have a django instance) a) Key point - Display and SEARCH only - no data entry. b) Existing well known database with a standard connector. c) Few canned SQL statements would generate the tables to display d) Dimensions are not small full database is 10K (rows) 200+ columns(attributes) e) A KEYWORD search is required - per line: Example Goal find a 0602 resistor that is 220 ohms. I would type "resistor" "film" "0602" and "220" - and click search. … -
Django save child from parent
I have this code: class Model1(models.Model): name = models.CharField(max_length=50) type = models.CharField(max_length=50) class Meta: verbose_name_plural = "Model1s" ordering = ('sioticket',) def def save(self, *args, **kwargs): super(Model1, self).save(*args, **kwargs) class Model2(models.Model): name = models.ForeignKey(Model1, on_delete=models.CASCADE, null=True, blank=True) cpm = models.CharField(max_length=50) class Meta: verbose_name_plural = "Model2s" ordering = ('sioticket',) def save(self, *args, **kwargs): vartype = self.name.type cpm = vartype return super(Model2, self).save(*args, **kwargs) I need to ejecute save() of Model2 from save() of Model 1. Or, from save() of Model1, do: tipo = self.name.type cpm = tipo But the problem is that, in parents I don't know if is it possible to access to save() of its childs classes or how to change values of its childs classes from save's parents. Also I have to say, that, if I create a new Model1 and Model2 works fine, but if I update type from Model1, it don't replicate to "cmp" of Model2. I've tried this: class Model1(models.Model): name = models.CharField(max_length=50) type = models.CharField(max_length=50) class Meta: verbose_name_plural = "Model1s" ordering = ('sioticket',) def def save(self, *args, **kwargs): super(Model1, self).save(*args, **kwargs) children = self.objects.all() for child in children: if child._meta.verbose_name_plural=="Model2s": child.save() class Model2(models.Model): name = models.ForeignKey(Model1, on_delete=models.CASCADE, null=True, blank=True) cpm = models.CharField(max_length=50) class Meta: verbose_name_plural … -
Django - Pagination test
When moving a test from a separate class to a class with other tests, it starts showing 4 posts on the second page instead of 3. If range is changed to 12 it shows 2 posts. Please suggest what is the problem. def test_correct_page_context_guest_client(self): posts = [Post(text=f'Тестовый текст {i}', group=self.group0, author=self.user0) for i in range( 13)] Post.objects.bulk_create(posts) pages = (reverse('posts:posts_list'), reverse('posts:group_list', kwargs={'slug': f'{self.group0.slug}'}), reverse('posts:profile', kwargs={'username': f'{self.user0.username}'})) for page in pages: for page_number in range(2): with self.subTest(page=page): response = self.guest_client0.get( page, {'page': page_number+1}) self.assertEqual(len(response.context['page_obj']), POSTS_COUNT[page_number]) If the test is left in a separate class PaginatorViewsTest(TestCase): then everything works as it should, but this is the task of the reviewer -
can only concatenate str (not "NoneType") to str BeautifulSoup
hi every body i make in my project a search on google with beautifulsoup and i recive this message can only concatenate str (not "NoneType") to str when i try to seach this is search.py from django.shortcuts import render, redirect import requests from bs4 import BeautifulSoup # done def google(s): USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36' headers = {"user-agent": USER_AGENT} r=None links = [] text = [] r = requests.get("https://www.google.com/search?q=" + s, headers=headers) soup = BeautifulSoup(r.content, "html.parser") for g in soup.find_all('div', class_='yuRUbf'): a = g.find('a') t = g.find('h3') links.append(a.get('href')) text.append(t.text) return links, text and this is views.py from django.shortcuts import render, redirect from netsurfers.search import google from bs4 import BeautifulSoup def home(request): return render(request,'home.html') def results(request): if request.method == "POST": result = request.POST.get('search') google_link,google_text = google(result) google_data = zip(google_link,google_text) if result == '': return redirect('home') else: return render(request,'results.html',{'google': google_data}) and this is urls.py from django.contrib import admin from django.urls import path,include from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home,name='home'), path('results/',views.results,name='Result') ] and this is template home <form method='post' action="{% url 'Result' %}" class="d-flex" role="search"> {% csrf_token %} <input class="form-control me-2 " type="search" placeholder="ابحث وشارك بحثك مع الاخرين" aria-label="Search" style="width:22rem;"> … -
How can I put data from api to django
I have stored some data in python and now I want to display it in django how can I do that? animeUrl = "https://api.jikan.moe/v4/top/anime" animeResponse = requests.get(animeUrl).json() def topAnime(): for idx, video in enumerate(animeResponse['data']): # z [data] wyciaga mi nastepujace rzeczy ktorze sa pod spodem animeUrl = video['url'] title = video['title'] status = video['status'] type = video['type'] images = video['images']['jpg']['image_url'] #if status == "Currently Airing": print (idx+1,":",animeUrl, ":", status, ":", title, ":", type, ":", images) topAnime() this is my stored data and now I want to display it on website, how can I do that? I'm newbie in django I'm looking for some suggestions I have tried using templates but it didn't worked -
extends and block not working in Django Templates
I'm learning how to use Django templates but I cant get extends and block to work. Here is my code. template.html <!DOCTYPE html> <html> <body> {% block theTitle %} {% endblock %} </body> </html> textComponent.html {% extends 'templates/template.html' %} {% block theTitle %} <div>what is going on?</div> {% endblock %} Here is how the files are organised: _templates __template.html __textComponent.html -
Understanding session with fastApi dependency
I am new to Python and was studying FastApi and SQL model. Reference link: https://sqlmodel.tiangolo.com/tutorial/fastapi/session-with-dependency/#the-with-block Here, they have something like this def create_hero(*, session: Session = Depends(get_session), hero: HeroCreate): db_hero = Hero.from_orm(hero) session.add(db_hero) session.commit() session.refresh(db_hero) return db_hero Here I am unable to understand this part session.add(db_hero) session.commit() session.refresh(db_hero) What is it doing and how is it working? Couldn't understand this In fact, you could think that all that block of code inside of the create_hero() function is still inside a with block for the session, because this is more or less what's happening behind the scenes. But now, the with block is not explicitly in the function, but in the dependency above: -
Django per-model authorization permissions
Im facing a problem in Django with authorization permissions (a bit new to Django). I have a teacher, student and manager models. When a teacher sends a request to my API they should get different permissions than a student (ie, a student will see all of his own test grades, while a teacher can see all of its own class's students, and a manager can see everything). My questions are as follows: How do I make all of my models valid system users? I've tried adding models.OneToOneField(User, on_delete=models.CASCADE) But this requires creating a user, and then assigning it to the teacher. What I want is for the actual teacher "instance" to be the used user. How do I check which "type" is my user ? if they are a teacher, student or manager? do I need to go over all 3 tables every time a user sends a request, and figure out which they belong to ? doesnt sound right. I thought about creating a global 'user' table with a "type" column, but then I wont be able to add specific columns to my models (ie a student should have an avg grade while a teacher shouldn't) . Would appreciate … -
Showing admin page of previous project in django
While running server of new project getting the admin page of the previous project how to get the admin page of current project? I tried to add"^" in the urls.py file but it is not working at all -
DJANGO: QueryDict obj has no attribute 'status_code'
I am will be shy a bit. That's my first question here and my English isn't greate to speak or write fluently. So I made CreateAdvert CBV(CreateView) and override the 'post' method for it. I need to update QueryDict and append field 'user' to it. But when I am trying to return the context, it says the problem on the title. Views: class CreateAdvert(CreateView): form_class = CreateAdvert template_name = 'marketapp/createadvert.html' context_object_name = 'advert' def post(self, request): #Because I don't want to give QueryDict 'user' field right from the form, I override the #post method here. user = User.objects.filter(email=self.request.user)[0].id context = self.request.POST.copy() context['user'] = user return context Forms: class CreateAdvert(forms.ModelForm): class Meta: model = Advertisment fields = ['category', 'title', 'description', 'image', ] I have tried to cover context with HttpRequest(). It didn't give me a lot of result. but I tried. -
Save FK on post in django
Hi I am having trouble with saving a fk in Infringer table on post. I am trying to save the customer ID when I add a record. For troubleshoot purposes I added a few print lines and this the out put. As you can see below the correct customer ID is present but the customer is None so its not being saved into the record. The other fields save fine. PLEASE HELP! I am a beginner. customer in forms.py is 2 forms.py instance was saved with the customer None customer in views.py is 2 Successfully saved the infringer in views.py with its customer None views.py @login_required(login_url='login') def createInfringer(request): customer=request.user.customer form = InfringerForm(customer=customer) if request.method == 'POST': customer=request.user.customer.id form = InfringerForm(customer, request.POST) if form.is_valid(): saved_instance = form.save(customer) print (f'customer in views.py is {customer}') print (f'Successfully saved the infringer in views.py with its customer {saved_instance.customer}') return redirect('infringer-list') context ={'form': form} return render (request, 'base/infringement_form.html', context) forms.py class InfringerForm(ModelForm): class Meta: model = Infringer fields = ['name', 'brand_name','status'] def __init__(self, customer, *args, **kwargs): super(InfringerForm,self).__init__(*args, **kwargs) self.fields['status'].queryset = Status.objects.filter(customer=customer) def save(self, customer, *args, **kwargs): instance = super(InfringerForm, self).save( *args, **kwargs) if customer: print (f'customer in forms.py is {customer}') self.customer = customer instance.save() print (f' … -
Can we set only a specific type of user as a foreign key in a model's field
I have a model called CustomUser which holds two types of user, teachers and students. The model has a regd_as field which stores the type of user. The model looks as follows: class CustomUser(AbstractBaseUser, PermissionsMixin): REGD_AS_CHOICES = ( ('TCH', 'TEACHER'), ('STU', 'STUDENT'), ) id = models.UUIDField(primary_key = True, editable = False, default = uuid.uuid4) email = models.EmailField(unique=True) date_joined = models.DateTimeField(auto_now_add = True) regd_as = models.CharField(max_length= 10, choices= REGD_AS_CHOICES, null=True) is_staff = models.BooleanField(default=False) is_active = models.Boolea Now I want to have a model that would store a referal code generated only for users who are teachers. The model looks as follows: class ReferalCode(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) teacher_user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, related_name='teacher_user_referal', null=True) referal_code = models.CharField(max_length=100, unique=True,null=True, blank=True) Question Is there a way to set only teachers from the **CustomUser** model as the foreignkey to teacher_user directly? Currently I am using signals to store only teachers as the user in ReferalCode model.