Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Uploading Multiple Images to Django Admin gives Foreign Key Error
I am working on a gallery project where I have to upload multiple images for a single place. I want to upload images using single ImageField in models. I tried to use TabularInline but it gives Foreign Key Error ERRORS: <class 'yatranepal.admin.PlaceImageInline'>: (admin.E202) 'yatranepal.Place' has no ForeignKey to 'yatranepal.Place'. Please, Suggest me some solution. #models.py class Place(models.Model): placeName = models.CharField( max_length=255, verbose_name="Name of the Place") placetheme = models.CharField(max_length = 500, verbose_name = "Theme of the Place",default="") placeImage = models.ImageField( upload_to="places/", verbose_name="Image of Place") placeImages = models.ImageField(upload_to="places/") placeDesc = models.TextField(verbose_name="Place Description") placeSlug = models.CharField(max_length=50, verbose_name="Place URL") def __str__(self): return self.placeName #Admin.py class PlaceImageInline(admin.TabularInline): model=Place fields= ('placeImages',) class PlaceAdmin(admin.ModelAdmin): inlines= [PlaceImageInline] fieldsets = [ ("Title/Link", {"fields": ["placeName", "placeSlug","placetheme"]}), ("Place Image", {"fields": ["placeImage","placeImages"]}), ("Place Description", {"fields": ["placeDesc"]}), ] formfield_overrides = { models.TextField: {'widget': TinyMCE(attrs={'cols': 80, 'rows': 30})}, } -
How would you create a framework on the top of django?
Hey everyone. My question might be a bit off-topic, but I'm getting interested in building a food-delivery open-source framework in top of django. I've looked into django-oscar e-commerce framework in the past, they have some cli to generate the skeleton of an e-commerce site and you can further customize it by implementing different Abstract classes. I'm wondering if having a cli to generate this project skeleton is the proper way of going against building such a thing, or having a django-rest framework like API would work better. Any suggestions/examples are welcomed. NOTE: I'm not an experienced django developer. Thanks in advance. -
Django Queryset - Move/Sort specific entries to bottom
I'm using Django.2.2.4. Imagine this. q2:<QuerySet [<KnowHow: one>, <KnowHow: onetwo>, <KnowHow: onethree>, <KnowHow: onetwothree>]> q4:<QuerySet [<KnowHow: one>, <KnowHow: onethree>, <KnowHow: four>]> I want to sort q2 that q4 goes to the bottom. q4 entries might not be included in q2. So, I'm aiming to make a query like this. <QuerySet [<KnowHow: onetwo>, <KnowHow: onetwothree>, <KnowHow: one>, <KnowHow: onethree>]> I tried like views.py, but there was an error like this. psycopg2.errors.SyntaxError: each UNION query must have the same number of columns LINE 1: ...git_taggeditem"."tag_id") >= 1) UNION ALL (SELECT "portal_kn... P.S. portal is my app name. models.py from django.db import models from django.urls import reverse from taggit.managers import TaggableManager class KnowHow(models.Model): BASIC_TAGS =( ('1','one'), ('2','two'), ('3','three'), ('4','four'), ('5','five'), ('6','six'), ) CATEGORY =( ('1','Type2'), ('2','Type1'), ) author = models.ForeignKey('auth.User',on_delete=models.CASCADE) category = models.CharField(max_length=1,choices=CATEGORY,default='1') title = models.CharField(max_length=200) text = models.TextField(blank=True,default=' ') # delault=' ':import system will give a error if text column is null file = models.FileField(blank=True,upload_to='explicit_knowhows') basic_tag = models.CharField(max_length=1,choices=BASIC_TAGS,default='1') free_tags = TaggableManager(blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('portal:index') class Feedback(models.Model): EFFECT =( ('1','great'), ('2','maybe good'), ('3','bad'), ) NOVEL =( ('1','I didn't know that'), ('2','I know, but I forgot'), ('3','I know this.'), ) kh = models.ForeignKey(KnowHow, on_delete=models.PROTECT) user = models.ForeignKey('auth.User',on_delete=models.CASCADE) basic_tag = … -
Views counter doesn't increment in database
I'm trying to add a view counter to my posts using F expressions and show the number of views for each post on django admin. But unfortunately, that doesn't work properly. I would be glad if anyone tells me what's wrong in my code. views.py: class Details(generic.DetailView): model = Post def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['essential_posts'] = Post.objects.filter(essential=True).order_by('-created_on') return context def postviewcount(request, slug): post = Post.objects.get(slug=slug) post.views = F('views') + 1 post.save() template_name = 'post-detail.html' models.py: STATUS = ( (0,"Draft"), (1,"Publish") ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) content = models.TextField() image = models.ImageField(upload_to = 'image/', blank=True) created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) essential = models.BooleanField('Essential News', default = False) views = models.PositiveIntegerField(default=0) class Meta: ordering = ['-created_on'] def __str__(self): return self.title -
How to encode None in dost data
In my django app, X is a nullable decimalField. I am getting this error because the value of X is Null in few scenarios. How can I handle this in situations where it Null? def my_serialization(self): return { 'id': self.app.id, ‘name’: self.app.name, ‘X’: self.app.x } def my_test(self): payload = self.my_serialization response = self.client.post(url, payload) This gives my an error: ‘Cannot encode None as POST data. Did you mean to pass an ' TypeError: Cannot encode None as POST data. Did you mean to pass an empty string or omit the value? -
xlwings || excel visiblity issue
i am opening an excel with the help of xlwings for some computation and i have set the visible False but still user can see the excel is opened and also it takes time to open and do the required. i passed the data to a template via django and when page is refreshed it takes time to show the data which i don't want. Is there any way to resolve this. below is my code for xlwings: wb = xlwings.Book(r'\\10.9.32.2\adm\Ash\FY 2019-20\DAILY REPORT\DAILY REPORT FORMAT.xlsx') xlwings.App().visible=False ws = wb.sheets['advance tracking sheet'] dict1= { 'C191' : 'J191', 'C192' : 'J192', 'C193' : 'J193', 'C195' : 'J195', 'C196' : 'J196', 'C199' : 'J199', 'C204' : 'J204', 'C208' : 'J208', 'C209' : 'J209', 'C210' : 'J210', 'C212' : 'J212', 'C213' : 'J213', 'C215' : 'J215', 'C216' : 'J216', 'C217' : 'J217', 'C218' : 'J218', 'C219' : 'J219', 'C220' : 'J220', 'C221' : 'J221', 'C222' : 'J222', 'C223' : 'J223', 'C224' : 'J224', 'C225' : 'J225', } yester_bal = [] for i,j in dict1.items(): b = ws.range(j). value c = b yester_bal.append(c) -
Manually rendered Django formset redirection problem at submition
I have the following models defined: class Item(models.Model): rfid_tag = models.CharField() asset = models.OneToOneField('Assets', default=None, null=True, on_delete=models.SET_DEFAULT,) date = models.DateTimeField(name='timestamp', auto_now_add=True,) ... class Assets(models.Model): id = models.AutoField(db_column='Id', primary_key=True) assettag = models.CharField(db_column='AssetTag', unique=True, max_length=10) assettype = models.CharField(db_column='AssetType', max_length=150) ... class Meta: managed = False db_table = 'Assets' ordering = ['assettag'] def __str__(self): return f"{self.assettag}" def __unicode__(self): return f"{self.assettag}" For which I have created the following form and formset: class ItemDeleteForm(forms.ModelForm): asset = forms.CharField(required=True, help_text= "Item asset tag", max_length=16, label="AssetTag", disabled=True, ) delete = forms.BooleanField(required=False, label="Delete", help_text='Check this box to delete the corresponding item', ) class Meta: model = Item fields = ['asset'] ItemDeleteMultiple = forms.modelformset_factory(model=Item, form=ItemDeleteForm, extra=0, ) managed by the view: class DeleteMultipleView(generic.FormView): template_name = '*some html file*' form_class = ItemDeleteMultiple success_url = reverse_lazy('*app_name:url_name*') def form_valid(self, form): return super().form_valid(form) And rendered in the template: {% extends "pages/base.html" %} {% block title %} <title>Delete Multiple</title> {% endblock %} {% block content %} <h1>Delete Multiple Items</h1> <br> <form class="ManualForm" action ="." method="POST"> {% csrf_token %} {{ form.management_form }} <table border="2"> <tr><th colspan="3" scope="row">Select Items to Delete</th></tr> {% for item_form in form %} <tr> <td><label for="{{ item_form.asset.id_for_label }}">AssetTag {{forloop.counter}}:</label> {% if item_form.non_field_errors %} {{ item_form.non_field_errors }} {% endif %} {% if item_form.asset.errors %} … -
Why does context variable passed as string converted to tuple string in Django?
Currently I am facing strange problem where variable passed as string to html, automatically converted to string tuple. My code is as below. view.py product_img = '/resources/my_project/resources/project_images/75f9bbb5-3efe-4918-acaf-fd994e8971ab.jpg' return render(request, 'myapp/product.html', {'product_img': str(product_img)}) product.html <img class="img img-responsive product_detail_img" src="{{ product_img }}" alt="DVGW Size 15X1mm" style="height: auto;width:250px;cursor:pointer;"/> # product_img = "('/resources/polaris/resources/product_images/75f9bbb5-3efe-4918-acaf-fd994e8971ab.jpg',)" As you can see above in html file product_img variable converted to tuple string and because of it I am not able to display image on my webpage. Does any one have idea how to figure out above issue. I have tried to convert variable to string but still facing same issue. Thanks. -
Page not found error message when template exists
I keep encountering the error message: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/teachers/app-instructor-billing.html I know this typically means that I have not set the correctly configured my urls.py to return a view for the defined path. However, from my understanding I have done this and i'm still getting this error message Here is my urls.py path('teachers/', include(([ path('', teachers.QuizListView.as_view(), name='app-instructor-dashboard'), path('logout', teachers.logout_request, name="logout"), path('edit_user', teachers.edit_user, name='edit_user'), path('billing', teachers.billing_info, name='app-instructor-billing'), path('mentor_messages/', teachers.mentor_messages, name='mentor_messages'), ], 'classroom'), namespace='teachers')), Here is my views.py(teachers.py): @method_decorator([login_required, teacher_required], name='dispatch') def billing_info(request): return render(request, 'classroom/teachers/app-instructor-billing.html') and my html: <li><a href="{% url 'teachers:billing' %}">Edit Billing</a></li> -
How to make custom field in DRF Serializer?
I have model Transasction class Transaction(models.Model): created_at = models.DateTimeField() and other models that have OneToOneField with Transasction. class RefillTransactionData(models.Model): transaction = models.OneToOneField(Transaction, on_delete=models.CASCADE) class PurchaseTransactionData(models.Model): transaction = models.OneToOneField(Transaction, on_delete=models.CASCADE) How i can to create Serializer with custom field "data" which will contain other serializers. A Json shema should be like this { created_at: "2020-10-01" data: { RefillTransactionData: {}, PurchaseTransactionData: {} } } For GET requeest i can do this with to_representation method. But i need same things for all of request types. -
Django view doesn't return POST request data
I created a simple Django view that once is called, sends a POST request to another simple Python-Flask script working on a different server. When the other Flask app receives the POST request, it sends back to Django a new POST request with some JSON data. To debug my code, right now, i'm trying to just print the received data, but i'm having some troubles. Here is my view: def myView(request): mydict = {} # The request is sent to my external Python script.. req = requests.post('http://127.0.0.1:5000/', json={"one": 1}) # Some dummy data # .. Once the external script sends back a request with data, this should handle it if request.method == 'POST': # The data is inside this variable data = request.POST for key in data.items(): if float(key[1]) > 0: mydict.update({key[0]: key[1]}) print(mydict) #FIRST PRINT STATEMENT print(mydict) #SECOND PRINT STATEMENT response = HttpResponse(get_token(request)) return JsonResponse(mydict) #RETURNS "{}" And here is how my Flask app sends data (once it receives the POST request from the Django view) using Python-Requests: # After the request from the VIEW is received, a request containing some random json data # is sent to Django url = 'http://127.0.0.1:8000/myView/' client = requests.session() # We need to … -
django - How to use "select multiple" instead of "select" in m2m relationship
I have a m2m relationship between my Influencer and Category models. My purpose was to easily edit an influencers category from influencer edit page and category edit page both. By default i got a multiple select widget in category edit page, to have the same thing in influencer edit page i used inlines. Now i'm able to edit influencers category from the influencer edit page but i don't have select multiple widget here, instead i have seperate select widgets. I would like to add a single select multiple input as same as category edit page in order to edit stuff faster. Even if it's a m2m relationship i can't understand how django decides to use a select multiple on one side of the relationship and multiple selectcs on the other side. admin.py: class CategoryInline(admin.TabularInline): model = Category.influencers.through class InfluencerAdmin(admin.ModelAdmin): # Some extra stuff here inlines = [ CategoryInline, ] class CategoryAdmin(admin.ModelAdmin): pass admin.site.register(Influencer, InfluencerAdmin) admin.site.register(Category, CategoryAdmin) admin.site.register(InfluencerList) models.py: class Influencer(models.Model): # Some fields here class Category(models.Model): name = models.CharField('Name:', max_length= 50, blank=False, null=False) influencers = models.ManyToManyField('Influencer', related_name='categories', blank=True) class Meta: verbose_name_plural = "categories" Thank you for your help. -
How to use request.user.is_authenticated in views.py?
I want to limit access to pages is to check request.user.is_authenticated and either redirect to a login page, because it's show ('AnonymousUser' object is not iterable). I tried this, but it's not work. views.py class HomeListView(ListView): model = Home def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["home_name"] = Home.objects.all() return context def account(request): if not request.user.is_authenticated: return redirect("account_login") thanks in advance for your help. -
Insert the selected data from the grid into SQL Server database
I am trying to create a website using Django ,python, sql server,which lists out the items in a tabular form.And upon selection of particular item via check box i want to update my database table with selected items. For eg: in the image below if ID : n1234 is selected i want to update backend table with drugsdispensed Please provide me references as i am trying to learn Django and Python. Please refer the image below to get an understanding of what i am trying to achieve. -
How to accept enable Smartcard Authentication with Django and Apache
Since I can't find any specific tutorial on how to enable Smartcard authentication for django I'm hoping that someone can provide me a checklist of what I need to do. -
Return dictionary from generic list view
I am trying to return a dictionary from list generic view. However, nothing is displayed. from django.views import generic from .models import Application, Device class ApplicationView(generic.ListView): template_name = 'applications/applications.html' context_object_name = 'applications' context = { "applications": Application.objects.all(), "devices": Device.objects.all(), } def get_queryset(self): return self.context In template: {% if applications %} <ul> {% for application in applications %} <li>{{ application.name }}</li> {% endfor %} </ul> {% else %} <p>No applications found.</p> {% endif %} -
Err command Eval on Django channels
I know guys this has been asked before I am getting some really weird stuff.i have installed redid version 4.6 with my Ubuntu terminal.i start the server there .it still shows me this error.before some days I was using the redid 3.0zip and that used to work fine but today that gives me error also.i don't know what is my problem or where is it.so please guys if there's any solution to it write down. -
Django: how to specify verbose_name with _meta without importing model?
Here is a simple model definition, using an import for a foreign key: from companies.models.owner_company import OwnerCompany class Restaurant(models.Model): owner_company = models.ForeignKey(OwnerCompany, on_delete=models.PROTECT, verbose_name=OwnerCompany._meta.verbose_name) Let's say that now, I need to define it without importing the OwnerCompany object. In this case, how would you define the verbose_name? class Restaurant(models.Model): owner_company = models.ForeignKey('companies.OwnerCompany', on_delete=models.PROTECT, verbose_name='???') -
How to use Get List from POST Data - Django
i hope the title is enough to know what is my problem This is my code in html when I tried to save this to my database only the "6" is save just like in the picture I use jquery to generate the date and textbox to input the grade this is my html <table id="blacklistgrid" border="2px"> <tr> <th id="th">Students Name</th> <th data-id='headers' id='header'>Average</th> </tr> {% for student in teacherStudents %} <tr class="tr2"> <td class="td" ><input type="text" name="students" value="{{student.id}}" id="student" >{{student.Students_Enrollment_Records.Student_Users}}</td> <td data-id='row' id="ans"><input type='number' class='averages' readonly/></td> </tr> {% endfor %} </table> <script> var counter = 0; function doTheInsert(){ let header=$("tr#tr"); // same as $.find("tr[id='tr2']") $('#th').after("<th data-id='headers' id='header'><input type='date' name='date'></th>"); var rows=$(".tr2"); $("<td data-id='row' ><input type='number' name='gradeko' class='average' /></td>").insertAfter(".td"); counter++; } </script> this is my views.py for gradeko in request.POST.get('gradeko'): pass for students in request.POST.getlist('students'): studentss = StudentsEnrolledSubject(id=students) date = request.POST.getlist('date') V_insert_data = studentsEnrolledSubjectsGrade( Teacher=teacher, Students_Enrollment_Records=studentss, Date=date, Grade=gradeko ) V_insert_data.save() this is my model.py class studentsEnrolledSubjectsGrade(models.Model): Teacher = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Students_Enrollment_Records = models.ForeignKey(StudentsEnrolledSubject, related_name='+',on_delete=models.CASCADE, null=True) Grading_Categories = models.ForeignKey(gradingCategories, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Date = models.DateField(null=True, blank=True) Grade = models.FloatField(null=True, blank=True) what i tried for gradeko in request.POST.getlist('gradeko'): pass for students in request.POST.getlist('students'): studentss … -
Why django rest api root does not list classic endpoints
I have registerd some of my endpoints through routers and written others in classic style, by classic style I mean that they are not registerd through router but directly written in path. Now problem is that api root lists only the endpoints that are registered through router and i want both to be listed. app/views.py from uuid import UUID from rest_framework import viewsets from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from event.models import Event from event.serializers import EventSerializer from food_album.models import FoodAlbums from food_album.serializers import FoodAlbumsSerializer from restaurant.models import RestaurantProfile from restaurant.serializers import RestaurantProfileSerializer from .serializers import * customer_favourites = { 0: [RestaurantProfile, RestaurantProfileSerializer], 1: [Event, EventSerializer], 2: [FoodAlbums, FoodAlbumsSerializer] } class CustomerProfileViewSet(viewsets.ModelViewSet): """ A viewset that provides the standard actions """ queryset = CustomerProfile.objects.all() serializer_class = CustomerProfileSerializer lookup_field = 'public_id' def get_serializer_class(self): if self.action in ['create', 'update']: return CustomerProfileCreateSerializer return self.serializer_class class RewardTypesViewSet(viewsets.ModelViewSet): """ A viewset that provides the standard actions """ queryset = RewardTypes.objects.all() serializer_class = RewardTypesSerializer lookup_field = 'public_id' class RewardActionsViewSet(viewsets.ModelViewSet): """ A viewset that provides the standard actions """ queryset = RewardActions.objects.all() serializer_class = RewardActionsSerializer lookup_field = 'public_id' class ReportItemViewSet(viewsets.ModelViewSet): """ A viewset that provides the standard actions """ queryset = ReportItem.objects.all() serializer_class = ReportItemSerializer … -
How to sort by a propery of ManyToMany Object in Django?
I'm trying to filter an object by the "order" property of a ManyToMany object. the tricky part here is that i'm trying to exclude a specific unit from the query but cannot seem to find how to do it. So, what basicaly the query should do is: get all Question objects assigned to a specific unit(one of the Unit's in M2M Field) sort them by the "order" property of all the other Unit's that are assigned to the Question Example ID Question Question.unit 1 question1 unit1, unit2 2 question2 unit1, unit3 3 question3 unit1, unit4 ID Unit Unit.order 1 unit1 1 2 unit2 2 3 unit3 3 4 unit4 4 Code: #views - my code so far, seems to filter by all units def get_questions_beside_unit(): questions = Question.objects.filter(unit=quiz.unit).order_by('unit__order') #models class Question(models.Model): ... unit = models.ManyToManyField(Unit) class Unit(models.Model): order = models.IntegerField() -
Use JsonResponse variable from Django in Html via ajax
I am returning JsonResponse with the required hash from Django view on a ajax call. How to use the Json object inside html via {{}} (jinja templating). Below is my ajax call: $(function () { $('#getData').submit(function (e) { e.preventDefault(); $.ajax({ url: "/Report", type: 'get', data: { 'date1': $('#d1').val(), 'date2': $('#d2').val(), }, success: function (data) { alert("Success"); // How to pass the data here to use it in html } }); }); }); My sample html : <div id="maindiv" class="col col-5 col-sm-10" style="display: none;"> <div> <h3> Showing Results for {{info.fromDate}} to {{info.toDate}}</h3> </div> <br><br> <div id="summary"> <div class="card-deck"> <div class="card mx-auto"> <div class="card-body text-center"> <p style="text-align: center;vertical-align: middle;padding: 20px;" class="card-text"> <h1><b><span style="font-size:80px;">{{info.total}}</span></b></h1> <h6> Total </h6> </p> </div> </div> <div class="card" id='chart1' style="width: 100%; height: 500px;"> <div class="card-body text-center"> <script> Info = {{ info.marks| safe }} createpiechart("marks", 'chart1', Info); <!-- This creates an amchart --> </script> </div> </div> </div> </div> This is just a sample. I have many more charts and processing for which I used the jsonresponse variable via {{}} inside html. What is the correct way to get the data from ajax to html? Initially I used render to return response to html. But I see that the data I … -
Django admin try catch on signals
Hi I'm currently having trouble to skip not show error(admin side) when doing a query in Django signal function I have these two model: class TopUp(models.Model): class Meta: db_table = "topups" verbose_name = 'Topup' verbose_name_plural = 'Topups' user = models.ForeignKey("backend.User", null=True, blank=True, related_name='user_optup', on_delete=models.CASCADE) currency = models.ForeignKey("backend.Currency", null=True, blank=True, related_name='user_topup_currency', on_delete=models.SET_NULL) TOPUP_METHOD_CHOICES = [ (0, 'fiat'), (1, 'chain') ] method = models.PositiveSmallIntegerField("Method", choices=TOPUP_METHOD_CHOICES, default=0) amount = models.DecimalField("Amount", max_digits=65, decimal_places=0, default=0) TOPUP_STATUS_CHOICES = [ (0, 'Pending'), (1, 'Approved'), (100, 'Rejected'), ] status = models.PositiveSmallIntegerField("Status", choices=TOPUP_STATUS_CHOICES, default=0) class UserBalance(models.Model): class Meta: db_table = "user_balances" verbose_name = 'User Balance' verbose_name_plural = 'User Balance' user = models.ForeignKey("backend.User", null=True, blank=True, related_name='user_balance', on_delete=models.CASCADE) currency = models.ForeignKey("backend.Currency", null=True, blank=True, related_name='user_balance_currency', on_delete=models.SET_NULL) balance = models.DecimalField("Balance", max_digits=65, decimal_places=0, default=0) The logic is on Django admin if status changed on TopUps(aka add money to account record) it will handle the balance on user balance If status changed to 1(Approved) then user balance with that currency got increased, if Reject then reverts and so on... My admin.py: class TopUpsAdmin(admin.ModelAdmin): list_display = ('get_phone_number',) def get_phone_number(self, obj): return obj.user.phone_number get_phone_number.short_description = 'User' get_phone_number.admin_order_field = 'user_phone_number' def get_readonly_fields(self, request, obj=None): return ('id', ) def save_model(self, request, obj, form, change): update_fields = [] # True … -
Get all related set objects on Django object including those not yet persisted to database
Let's say I have the following simple Django models: class Club(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Student(models.Model): name = models.CharField(max_length=50, unique=True) club = models.ForeignKey(Club, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.name And I create the following objects: club1 = Club.objects.create(name="Club1") student1 = Student.objects.create(name="Student1", club=club1) print(club1.student_set.all()) # <QuerySet [<Student: Student1>]> Now I'm going to instantiate a second student object on the club object but NOT YET persist it to the database. Is there anyway to get all students associated to club1 BEFORE it has been written to the db? Looks like using the standard approach just returns the objects stored in the db: student2 = Student(name="Student2", club=club1) print(club1.student_set.all()) # <QuerySet [<Student: Student1>]> # Goal is to get this: # <QuerySet [<Student: Student1>, <Student: Student2>]> The reason I need this is to perform some validation of the staged data state. -
django unique_for atributes in models
In the past, I think there was a model atrtibute named unique_for to define a foreignKey but I can't find it anymore. Suppose a model named Recommendation. A User can recommend many websites but only one by domain. So, I wanted to set a unique_for('user', 'recommendation.domain') or something like like this. What's the current way to do it ? Thanks