Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Uploaded images not saved and displayed in Django
I'm working on user profiles, where the user can upload jpg images as their profile pictures. But the uploaded images are neither being stored in my media directory nor is it being displayed in the server. IT keeps displaying 'default photo' instead. I have set up the MEDIA_ROOT and MEDIA_URL in my settings file and have also added to the urls file, it's still not working. I'm new to Django, any help would be appreciated. Here's my models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() image=Image.open(self.image.path) if image.height >300 or image.width > 300: output_size=(300,300) image.thumbnail(output_size) image.save(self.image.path) views.py: def profile(request): if request.method=='POST': update_form=UserUpdateForm(request.POST, instance=request.user) profile_form=ProfileUpdateForm(request.POST, request.FILES ,instance=request.user) if update_form .is_valid() and profile_form.is_valid(): update_form.save() profile_form.save() messages.success(request, f'Your account has been updated!!') return redirect('profile') else: update_form=UserUpdateForm(instance=request.user) profile_form=ProfileUpdateForm(instance=request.user) context={ 'update_form': update_form, 'profile_form':profile_form, } return render(request, 'users/profile.html', context) profile.html: <div class="card" id="profile" style="width: 18rem;"> <img class="card-img-top" src="{{ user.profile.image.url }}" alt="Default photo"> <div class="card-body"> <h2 class="account-heading">{{ user.username }}</h2> <p class="text-secondary">{{ user.email }}</p> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4"><h1>Profile Info</h1></legend> {{ update_form|crispy }} {{ profile_form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-oultline-info" type="submit"> Update </button> </div> </form> </div> -
Read text file and store in a list of list
I have a text file which contains multiple rows of line, I want to store each line in a list I have tried: data = [] with open('numbers.txt') as f: data.append([int(x) for x in f.readline().split()]) print(data) It know the above code stores only 1st row, so how will i store rest of rows ? -
Ajax request returns 200 OK, but an error event is fired instead of success || xlswriter
I have a Download excel button in the UI, when clicked excel should get downloaded. Following are the code snippets for the same. To my surprise, Ajax request returns 200 OK, but an error event is fired instead of success. Not able to trace back the root cause. views.py def excel(request): ans = request.POST.getlist('ans[]') ans_final=[] rows = request.POST.get('rows') for each_ele in ans: each_ele = each_ele.split('.') each_ele[0] = each_ele[0][:-2] each_ele[1] = each_ele[1][:-2] fin = each_ele[0]+' - '+each_ele[1] ans_final.append(fin) output = BytesIO() workbook = xlsxwriter.Workbook(output) # workbook = xlsxwriter.Workbook('/home/sai_avinash/Desktop/hello.xlsx') worksheet = workbook.add_worksheet('Test_Data') bold = workbook.add_format({'bold': True}) for i in range(len(ans_final)): worksheet.write(0, i,ans_final[i],bold) row_index=1 row_count = int(rows) while(row_count): col_index=0 for each_ele in ans: worksheet.write(row_index, col_index, eval(each_ele)) col_index += 1 row_index += 1 row_count -= 1 workbook.close() output.seek(0) # return JsonResponse({'ok':'ok'}) response = HttpResponse( output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ) response['Content-Disposition'] = 'attachment; filename=django_simple.xlsx' return response js file $('body').on('click', '.excel', function () { var ok = ans rows = $('#hmm').val() $.ajax({ type: "POST", url: "/excel", data: {'ans':ok, 'rows':rows}, dataType: "json", success: function (data) { // alert("Success") }, error: function (e) { debugger // console.log(e) alert("Error") } }); }); -
How can I run a function as subprocess and get custom return value from it in Python?
I have a function called generatePDFandEmail. I want to delete the pdf file after email is sent, but when I try to do it in Django view, it says "file used by another process". I read somewhere that one should use a subprocess, so when it finishes, it will release the file and will allow deletion of file. I am trying to find out how should I write the subprocess function which will return the PATH OF PDF file, which I can use to delete the pdf. All I get is returncode, not the custom return value from subprocess. Kindly help! -
How do I solve error: Python has stopped working [closed]
I am running python via Anaconda on windows 10 64bit. I get this error each time i run my local server. I have tried re-installing Anaconda and updating pyqt but the runtime error still persists. Any idea how to fix this, thanks -
How to import complex json do django model object
I got from some network service list of following dict: { '_id': 'bcEsX4Mhridf7Fdz59nYcm', 'stats': { 'acqs': 0, 'alerts': 0, 'blocks': 0, 'false_positive_alerts': 0, 'false_positive_alerts_by_source': {}, 'malware_false_positive_alerts': 0 }, 'hostname': 'SomePC', 'domain': 'local', 'url': '/hx/api/v3/hosts/bcEsX4Mhridf7Fdz59nYcm', 'sysinfo': { 'url': '/hx/api/v3/hosts/bcEsX4Mhridf7Fdz59nYcm/sysinfo' }, 'os': { 'product_name': 'Windows 10 Pro', 'patch_level': None, 'bitness': '64-bit', 'platform': 'win', 'kernel_version': None }, } I want to import it to django model object. My models.py contain following code: class Host(models.Model): _id = models.CharField(max_length=25, primary_key=True) hostname = models.CharField(max_length=25) domain = models.CharField(max_length=253) url = models.CharField(max_length=50) def __str__(self): """String for representing the Model object.""" return '{0}_({1})'.format(self.hostname, self._id) class stats(models.Model): host = models.OneToOneField(Host, on_delete=models.CASCADE, null=True) acqs = models.IntegerField(default=0) alerts = models.IntegerField(default=0) blocks = models.IntegerField(default=0) false_positive_alerts = models.IntegerField(default=0) malware_false_positive_alerts = models.IntegerField(default=0) def __str__(self): """String for representing the Model object.""" return '{0}/{1}/{2}'.format( self.acqs, self.alerts, self.blocks ) class sysinfo(models.Model): host = models.OneToOneField(Host, on_delete=models.CASCADE, null=True) url = models.CharField(max_length=45, blank=True) def __str__(self): """String for representing the Model object.""" return '{0}'.format(self.url) class os(models.Model): host = models.OneToOneField(Host, on_delete=models.CASCADE, null=True) product_name = models.CharField(max_length=253) patch_level = models.CharField(max_length=253, blank=True, null=True) bitness = models.CharField(max_length=10, blank=True, null=True) platform = models.CharField(max_length=10, blank=True, null=True) kernel_version = models.CharField(max_length=10, blank=True, null=True) def __str__(self): """String for representing the Model object.""" return '{0}'.format(self.product_name) If mentioned dict would be a flat one … -
Ho to test a create function in Django?
# my .views def post_create_view(request): form = PostModelForm(request.POST or None) if form.is_valid(): obj = form.save(commit=False) obj.user = request.user obj.save() form = PostModelForm() context = {'form': form} return render(request, 'form.html', context) # my .urls path('create/', post_create_view, name='create') # my .test class TestViews(TestCase): def setUp(self): self.client = Client() self.create_url = reverse('posts:create') self.user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword') self.post1 = Post.objects.create(user=self.user, title='testpost', content='fgh') self.query = Post.objects.all() def test_blog_create_POST(self): # this is where the error surely is response = self.client.post(self.create_url, {'title': 'testpost2', 'content': 'asd'}) self.assertEqual(response.status_code, 302) # this is where the test fail self.assertEqual(self.query.last().title, "testpost2") 'testpost2' doesn't get created but my form works fine. How can I simulate the inputs in my testcase? self.create_url redirect to the correct url, the one with the form in the template, such form works great, but when I write the response in my test the dictionary I pass as second arguments seems not to go through. -
after password updation,if i click on update again it is showing password updated again
after password updation through otp,if i click on update again it is again showing password updated,it is a bug ,how toi fix this class SendMailViewSet(viewsets.ViewSet): def create(self,request): try: email=request.data.get('email') otp=request.data.get('otp') user=Otp() user.email=MyUser.objects.get(email=email) user.otp=random.randint(124455,994678) print(user.otp) user.save() subject = 'Thank you for registering to our site' message = str(user.otp) email_from = settings.EMAIL_HOST_USER recipient_list =[email] send_mail( subject, message, email_from, recipient_list ) return Response(user.otp) except Exception as error: traceback.print_exc() return Response({"message": str(error), "success": False}, status=status.HTTP_200_OK) class PasswordViewSet(viewsets.ViewSet): def create(self, request): try: email = request.data.get('email') password = request.data.get('password') otp = request.data.get('otp') #user_obj = MyUser.objects.filter(email=email) otp_obj_check = Otp.objects.filter(email__email=email) user_obj=MyUser.objects.filter(email=email) if not user_obj: raise Exception("email does not exist") if otp_obj_check: otp_obj = Otp.objects.filter(email__email=email).order_by('-id')[0] else: raise Exception("invalid otp") if not otp: raise Exception("please enter otp") if int(otp_obj.otp) == int(otp): for user_obj in user_obj: user_obj.set_password(password) user_obj.save() # token = get_access_token(user_obj) else: raise Exception('wrong otp') if not password: raise Exception('please enter password') return Response({"password": 'updated', "success": True}, status=status.HTTP_200_OK) except Exception as error: traceback.print_exc() return Response({"message": str(error), "success": False}, status=status.HTTP_200_OK) here is my model of otp class Otp(models.Model): email=models.ForeignKey(MyUser,on_delete=models.CASCADE) otp=models.CharField(max_length=10,null=True,blank=True) def __str__(self): return self.otp -
Why get_children() returns PageQuerySet?
I use the model below and I thought that (IndexPage Instance).get_children() returns BlogPageQuerySet, but PageQuerySet was returned. How can I get queryset with exact class? class BroadcastPage(Page): description = RichTextField('description') catchcopy = models.TextField('catchcopy', blank=True, null=True) categories = ParentalManyToManyField('Category', related_name='broadcasts', blank=True, verbose_name='category') @register_snippet class Category(models.Model): slug = models.CharField('slug', max_length=20) name = models.CharField('name', max_length=20) class IndexPage(Page): def get_context(self, request, category_slug=None, *args, **kwargs): context = super().get_context(request, *args, **kwargs) if category_slug: category = get_object_or_404(Category, slug=category_slug) all_posts = \ self.get_children(categories=category).filter().live().public().order_by('-first_published_at') context['category'] = category else: all_posts = \ self.get_children().descendant_of(self).live().public().order_by('-first_published_at') paginator = Paginator(all_posts, 10) page = request.GET.get('page') try: pages = paginator.page(page) except PageNotAnInteger: pages = paginator.page(1) except EmptyPage: pages = paginator.page(paginator.num_pages) context['pages'] = pages context['categories'] = Category.objects.all() return context BroadcastPages are placed under IndexPage -
Wagtailmenus - choose submenu items
I'm beginner to Wagtail (and web development) and I installed wagtailsmenus package to my project, but I wonder if it's possible to choose custom submenu items ? From what I understand with the documentation is that we can only render Child Page of a top lvl menu item, am I right ? If I want a menu like this (for example) : |--- Blog | |---- ChoosedArticle1 | |---- ChoosedArticle2 | |--- Services | |---- ChoosedService1 | |---- ChoosedService2 | |--- Tutorials | |---- ChoosedTutorial1 | |---- ChoosedTutorial2 Assuming tutorials are BlogPage but with category "tutorial" and articles are regular BlogPage (without category or with a default category) and Services are ServicePage The problem is that tutorials and articles are only under the "BlogListingPage" there is no different pages in my Wagtail project like : TutorialListingPage and BlogListingPage. Here is a scheme : |--- Blog | |--- some cool articles (regular articles) | |--- others articles (categorized as tutorials) | |--- etc. | |--- Services Maybe I don't properly understand the documentation ? https://wagtailmenus.readthedocs.io/ N.B. I'm sorry I'm not english native speaker and it's hard for me to describe the issue Thanks -
Suggestions for tutorials to build an User to User inbox in Django
Could anyone suggest to me a good video tutorial (paid or free) that goes through building a User to User private message system? So far been using Safari by O'Reilly which I've learned a lot through. I'm new to Django, slightly less new to Python. -
Back Page is not loading with Jquery elements
I have a html form page(page 1) from where I go to page 2 html page. In page 1 I have fields such as Resolution, on selecting particular resolution populates fields such as frame-width and height(with value) which is loaded using Jquery and is disabled (just to show) Similarly I have cascaded drop-downs. On submission of this form I get the results on the same page. Also I have given option to display the output on new page. But when I get back to the previous page from new page. Jquery Elements are not loaded. Only static elements in form are loaded. Resolution stays but frame width and frame-height is not loaded. Also output on same page is also gone. How can I get to previous page as per my submission made. I am using Django in Back-end. -
Can I use generic view and class-based views?
i start to learn Django using the django 3 and i have a quick question . Sorry i'm not a native english speaker so i'm not sure if i'm using the right term for it but Can i use sometimes generic view and sometimes class-based views in the same project ? For exemple in the same project can i write class PostList(ListView) : And an other one def post_new(request): Because sometimes is easier to use def and sometimes is easier to ease ListView or other View . It's really just to know the best way to code and have a clean code :) . -
Optimise a nested for loop in django
I have following code which has nested for loop. for app in from_apps: app_pl = app.slotplass_set.all() old_playlists = app.games.all() app.pk = None app.client = labels[1].client app.label = labels[1] app.save(saveToCouch=False) for e in app_pl: e.pk = None e.schedule = app e.save(saveToPouch=False) However, I am unable to optimise it further using a bulk query? -
Connect to LDAP server in django
I'm trying to connect to LDAP server for my django app. In order to connect to my LDAP server I must provide correct login and password. I can't find any information about authorizing to LDAP server, in documentation I see only information about authorizing users to LDAP server with already established connection. How do I solve it? -
Django Rest Framework Serialization Error - "The serializer field might be named incorrectly..."
Not quite understanding what I have done wrong here, and a similar question asked has no real relation to my problem.. I have the notion of a SurfWaiver which is serialized as follows, linked to a ForeignKey model "SurfTicket": from rest_framework import serializers from api.v2.SurfWaivers.models import SurfWaiver from api.v2.SurfTickets.serializers import SurfTicketSerializer class SurfWaiverSerializer(serializers.ModelSerializer): ticket = SurfTicketSerializer() class Meta: model = SurfWaiver fields = ('ticket', 'signed') The SurfTicket is serialized in a similar fashion, as: from rest_framework import serializers from api.v2.SurfTickets.models import SurfTicket from api.v2.SurfAccounts.serializers import SurfAccountSerializer class SurfTicketSerializer(serializers.ModelSerializer): surfer = SurfAccountSerializer(many=False, read_only=True) class Meta: model = SurfTicket fields = ('id', 'surfer', 'when', 'code', 'void_type', 'no_show',) The models.py for both of these match to the serializer, and I have checked for spelling mistakes. The SurfAccountSerializer is also as follows: User = get_user_model() # user model is "SurfAccount" class SurfAccountSerializer(serializers.ModelSerializer): class Meta: model = User read_only_fields = ('locale',) exclude = ('password', 'last_login', 'is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions') Yet, alas, I get the following error: "Got KeyError when attempting to get a value for field `ticket` on serializer `SurfWaiverSerializer`.\nThe serializer field might be named incorrectly and not match any attribute or key on the `dict` instance.\nOriginal exception text was: 'ticket'." Can anyone point … -
Thread pools in Django
I have created a thread pool to add a list of numbers in a text file but I am stuck at a point and I can't find the error. @classmethod def product(self, list1): product = 1 for x in list1: product *= x return product def get(self, request): data = [] with open('numbers.txt') as f: data = [int(x) for x in f.read().split()] b = self.run(a, 10, self.product) print(b) return Response(json.dumps(a)) @classmethod def run(cls, all_items, max_pool_size, func): logger.info('running items of size: {} in a thread pool with max pool size: {}'.format(len(all_items), max_pool_size)) print('running items of size: {} in a thread pool with max pool size: {}'.format(len(all_items), max_pool_size)) items_list = cls.get_items_for_thread_pool(all_items, max_pool_size) return cls.run_in_process_thread_pool(items_list, func) so if I have a text file with row 360 I need 36 size array but I am getting 10 size array only which is size of pool, what changes I need to make in my code ? -
Store client IP on model on requests in Django restframework
I would like to store my client's Ip in my model in django restframework. I don't know where to put my function and how to store it when a log gets created: Models.py class Loglist(models.Model): """This class represents the loglist model.""" message = JSONField(null=True) date_created = models.TimeField(auto_now_add=True) client_ip = models.GenericIPAddressField(null=True) def __str__(self): """Return a human readable representation of the model instance.""" return "{}".format(self.client_ip) Views.py class CreateView(generics.ListCreateAPIView): """This class defined the create behaviour of our rest api.""" queryset = Loglist.objects.all() serializer_class = LoglistSerializer def perform_create(self, serializer): serializer.save() class DetailsView(generics.RetrieveUpdateDestroyAPIView): queryset = Loglist.objects.all() serializer_class = LoglistSerializer Serializer.py class LoglistSerializer(serializers.ModelSerializer): """Serializer to map the model instance into JSON format.""" class Meta: """Meta class to map serializer's fields with the model fields.""" model = Loglist fields = ('id', 'message', 'date_created', 'client_ip') read_only_fields = ('date_created', 'client_ip') -
How to clear AttributeError: batch_norm_trainable in object detection
Hi.. I got the Attribute error: batch_norm_trainable while running the object detection code. please help to sort out this issue. Thanks in advance. C:\Users\Sathiesh Kumar\AppData\Local\Continuum\Anaconda3\envs\Reti\lib\site-packages\tensorflow\python\framework\dtypes.py:523: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) C:\Users\Sathiesh Kumar\AppData\Local\Continuum\Anaconda3\envs\Reti\lib\site-packages\tensorflow\python\framework\dtypes.py:524: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint8 = np.dtype([("quint8", np.uint8, 1)]) C:\Users\Sathiesh Kumar\AppData\Local\Continuum\Anaconda3\envs\Reti\lib\site-packages\tensorflow\python\framework\dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint16 = np.dtype([("qint16", np.int16, 1)]) C:\Users\Sathiesh Kumar\AppData\Local\Continuum\Anaconda3\envs\Reti\lib\site-packages\tensorflow\python\framework\dtypes.py:526: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint16 = np.dtype([("quint16", np.uint16, 1)]) C:\Users\Sathiesh Kumar\AppData\Local\Continuum\Anaconda3\envs\Reti\lib\site-packages\tensorflow\python\framework\dtypes.py:527: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint32 = np.dtype([("qint32", np.int32, 1)]) C:\Users\Sathiesh Kumar\AppData\Local\Continuum\Anaconda3\envs\Reti\lib\site-packages\tensorflow\python\framework\dtypes.py:532: … -
how to generate random User username and insert into the datebase in django
I am trying to generate username randomly and save to the User model. Currently I can able to generate the username, But I can't able to save that into the User Model and I don't know how can I do it. Please help to done it. my forms process without the random username generator function. When i adding these function to generate custom and random username I'm facing lots of error like, attibute error, unbound error and so on views.py # random username generator def userdate(dt_time): return str(10000*dt_time.year+100*dt_time.month+dt_time.day) def usernameGen(names): names = names.split(" ") for i in range(1,1000): first_letter = names[0][0] three_letter = names[-1][:3] number = '{:03d}'.format(random.randrange(1,1000)) dateuser = userdate(date.today()) username =(first_letter+three_letter+dateuser+number) try: User.objects.get(username = username) return usernameGen("PMK GAC") except User.DoesNotExist: return username # registration view def register(request, *args, **kwargs): if request.method == 'POST': username = usernameGen("PMK GAC") #calling usernameGen function form = CustomUserCreationForm(request.POST) #user form profile = ProfileForm(request.POST, request.FILES) #profile form if form.is_valid() and profile.is_valid(): form.save() profile.save() # messages.success(request, 'new user is create. ') return render(request,'info.html') form = CustomUserCreationForm() profile = ProfileForm() context = {'form':form, 'profile':profile} return render(request, 'register.html', context) models.py #this models is not User model. it is additional model with One to one relationship of current user … -
How to Maintain Migration folder for test server and production server in django?
I have been dealing with this issue for a long time now. Our company has two django servers one for testing purpose and the other for deployment purpose, each with their own databases and migrations. My initial solution was to simply maintain two migration folders: -->migrations -->migrations(P) As seen above migrations(P) denotes the production level migrations, this config is used mainly during the testing phase where all the migrations are related to test database and some times it is swapped to the following folder structure when we are in production mode migrations: -->migrations -->migrations(T) In the above case migrations(T) are related to test database and migrations are related to production level server. This worked well but sometimes when there are multiple commits from other developers and also i work on it myself, due to the folder swapping the migration files get merged and messed up causing in a crash. Sorry if my question is a little confusing. Any alternative suggestion or approaches for maintaining production and test level database migrations would be helpful -
Download excel in browser || Django
def excel(request): ans = request.POST.getlist('ans[]') ans_final=[] rows = request.POST.get('rows') for each_ele in ans: each_ele = each_ele.split('.') each_ele[0] = each_ele[0][:-2] each_ele[1] = each_ele[1][:-2] fin = each_ele[0]+' - '+each_ele[1] ans_final.append(fin) workbook = xlsxwriter.Workbook('/home/Desktop/status.xlsx') worksheet = workbook.add_worksheet('Test_Data') bold = workbook.add_format({'bold': True}) for i in range(len(ans_final)): worksheet.write(0, i,ans_final[i],bold) row_index=1 row_count = int(rows) while(row_count): col_index=0 for each_ele in ans: worksheet.write(row_index, col_index, eval(each_ele)) col_index += 1 row_index += 1 row_count -= 1 workbook.close() return JsonResponse({'ok':'ok'}) As seen in the above function in my views.py, when a button(Download Excel) is clicked in the UI, the request is sent to this function and I am generating an excel and saving it in desktop folder for now. How do I make this excel download in the browser itself in UI for the user when "Download excel" button is clicked instead of saving it in a specific path. Note :- I am using xlswriter module for excel generation. -
How to add x-server & x-taggroups for ReDoc through drf-yasg
I using drf-yasg for documentation,i am using redoc and it's working great.But i want to add x-server and x-taggroups.I would like to set custom tags for views, and add them to their own taggroups, but I cannot find anything in the docs about this, how would I go about this? -
modify operator based on parameter
I do have function to get ages by gender and year level: def ages(age=0): ages = [] for level in range(level_from, level_to): gender_male = len( [ s for s in queryset if s.age <= age # want to modify this base on the age ex(s.age >= age, or s.age == age) so I can reuse this code if s.gender == 'male' if s.year_level == level ] ) ages.append(gender_male) return ages s.age is a function, I can't access the age directly because this is a private variable. I am thinking to variable = <= but this generates error. The output should be [0,1,2,3,4,5] if s.age <= 11 class Student: GENDER = Choices( ('male', _(u'Male')), ('female', _(u'Female')), ) YEAR_LEVEL = ( (1, 'one', _(u'First Year')), (2, 'two', _(u'Second_ Year ')), ) _age = models.PositiveIntegerField(_(u'age'), db_column='age') gender = models.CharField( _(u'gender'),GENDER choices=GENDER, ) year_level = models.PositiveIntegerField( _(u'Year), choices=YEAR_LEVEL_CHOICES, default=YEAR_LEVEL.one ) birthday = models.DateField(_(u'Birthday)) @property def age(self): if not self.birthday: return self._age return age_compute(self.birthday) this is my original code def student_ages( self, department=None, age=0, queryset=None, level_from=None, level_to=None, age_from=0, age_to=0, ): below_age, middle_age = [], [] above_age, overall_age = [], [] below_age.append("%s Below" % age) for level in range(level_from, level_to): gender_male = len( [ s for … -
How to correctly display data from two related models in Django ListView
I have two models as below: class Loo(models.Model): loo_type = models.CharField(max_length=3, default="LOO"...) loo_from = models.ForeignKey(Harr, on_delete=models.CASCADE, ...) loo_fac = models.DecimalField(max_digits=7, decimal_places=.....) class Woo(models.Model): woo_item = models.AutoField(primary_key=True, ...) woo_loo = models.ForeignKey(Loo, on_delete=models.CASCADE, ...) woo_dt = models.DateField(null=True, ...) woo_rate = models.DecimalField(max_digits=7, decimal_places=.....) I am trying to display data from the models using the following listview: class WhoLooView(ListView): template_name = "who_loo_list.html" context_object_name = 'wholoos' model = Loo def get_context_data(self, **kwargs): context = super(WhoLooView, self).get_context_data(**kwargs) context.update({ 'woo_item_list': Woo.objects.order_by('-woo_dt'), }) return context def get_queryset(self): return Loo.objects.order_by('loo_from') Note that there can be more than one "woo_item" per instance of Loo (id), so in the listview there will be occasions when for the same Loo id it will have two instances of Woo/s, and thus need to be displayed separately (preferably in two distinct rows). What I have tried so far creates extra (adjacent) columns for each Loo id and whichever Loo/s have a single instance of Woo, are shown in the normal fashion as expected. How does one take care of such a situation. Can we have a nested row for cases where there are more than one instance of Woo?