Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
serializer adds unnnecesary fields in Javascript
I need to generate a very clean structure of an JS Array from Django Queryset. For this I'm using a serializer. However, they final array has extra field that may be causing problems with Google Analytics requested format. Google Analytics resquested format: Notice the structure of the products Array <script> // Send transaction data with a pageview if available // when the page loads. Otherwise, use an event when the transaction // data becomes available. dataLayer.push({ 'ecommerce': { 'purchase': { 'actionField': { 'id': 'T12345', // Transaction ID. Required for purchases and refunds. 'affiliation': 'Online Store', 'revenue': '35.43', // Total transaction value (incl. tax and shipping) 'tax':'4.90', 'shipping': '5.99', 'coupon': 'SUMMER_SALE' }, 'products': [{ // List of productFieldObjects. 'name': 'Triblend Android T-Shirt', // Name or ID is required. 'id': '12345', 'price': '15.25', 'brand': 'Google', 'category': 'Apparel', 'variant': 'Gray', 'quantity': 1, 'coupon': '' // Optional fields may be omitted or set to empty string. }, { 'name': 'Donut Friday Scented T-Shirt', 'id': '67890', 'price': '33.75', 'brand': 'Google', 'category': 'Apparel', 'variant': 'Black', 'quantity': 1 }] } } }); </script> My dataLyer produced by serializer: View that contains the serializer: def thanks_deposit_payment(request): order_number = Order.objects.latest('id').id total = Order.objects.latest('id').total costo_despacho = Order.objects.latest('id').shipping_cost order_items = OrderItem.objects.filter(order=Order.objects.latest('id')) … -
How to trans-compile React inside Django project in Pycharm?
I'm using Pycharm to write a Django App with React as the frontend. Because the React source code is inside the Django source code, there is no clear way to trans-compile the React source code. I know Pycharm can compile the code if it is a React project, but there are no instructions for compiling if it is embedded in a Django project. I don't have a list of things I've tried because I have no idea where to start other than doing searches on Google, which I've already done. I did look at the file-watcher in Pycharm, but it is not clear if this is a solution because there is nothing React related in it. -
Creating permission records for existing database model in django auth
I have implemented a wrapper API app on several complicated databases with Django. A default local database is made to keep user, tokens and permission data. API endpoints are ready to use and I am trying to add authorization for. So I decided to use the admin panel to create users and set permission to them. As I cannot run migrate (because I don't want to change resource DBs) I was trying to add permission records to auth_permission table upon on models I registered in the admin panel. I try to : python migrate <mainapp> But it just makes default permission rows. for example, I've used this: admin.site.register(Employee) And I was hoping to have corresponding records in default database like: auth_permission: --------------------------------------------------------- |id|name |content/-type_id |codename | --------------------------------------------------------- |1 |Can add Employee |2 |add_employee | --------------------------------------------------------- So I would be glad to know is there any way to generate these records? -
How can I store XML files on a website to convert them online on Django?
I am working on a website as a hobby in order to gain more experience in Django. I am trying to find a way to upload an XML file on my website and convert it to another form (for instance PDF). My question is, how could I achieve something like this? Do I have to use some kind of online data base and read the file from there for the conversion? I have no clue how to go about it and I havent been able to find an answer to this online. I apologize if the question is off topic. I appreciate any help you can provide -
How to add required profile data for reservation system
I am building a reservation system in django 2 and python 3 where you can rent Tools. The user register with First and Last Name as well as email. I extended the django user model and created a model called 'profile' which has the following fields: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birthday = models.DateField(blank=True, null=True) matrnr = models.CharField(max_length=6, validators=[MinLengthValidator(6), MaxLengthValidator(6)], default='', blank=True, null=True) address = models.CharField(max_length=100, default='', blank=True, null=True) city = models.CharField(max_length=50, default='', blank=True, null=True) zip = models.CharField(max_length=6, validators=[MinLengthValidator(5), MaxLengthValidator(5)], default='', blank=True, null=True) homephone = models.CharField(max_length=15, blank=True, default='', null=True) mobilephone = models.CharField(max_length=15, blank=True, default='', null=True) id_number = models.CharField(max_length=20, blank=True, default='', null=True) driverlicense_number = models.CharField(max_length=20, blank=True, default='', null=True) There is a page with the borrowable tools, with a "Reserve" button next to each item. If the user now clicks on this button, it should first be checked whether the user has already filled in his profile data or not. If not, the user has to fill them in before he can borrow something. How can I achieve that? I am clueless as I am a beginner. This is the table where I list all the tools: {% block title %}Tool List{% endblock %} {% block content %} <p> Here you … -
CreateView weird behaviour. Goes to the wrong view?
In my urls.py I have a ListView and a CreateView. When I have both the views in the urls patterns, the CreateView shows the html linked to the ListView. But when I remove the ListView from the url patterns, then the CreateView shows the correct html. urls.py If I have it like this, CreateView shows ListView html urlpatterns = [ path("", views.TopicListView.as_view(), name="topic"), path("<topic>/", views.PostListView.as_view(), name="post"), path("create/", views.CreatePostView.as_view(), name="create_post") ] This way, the CreateView behaves like I want it to. Shows the correct HTML urlpatterns = [ path("", views.TopicListView.as_view(), name="topic"), path("create/", views.CreatePostView.as_view(), name="create_post") ] views.py class PostListView(ListView): model = models.ForumPost template_name = "forum/post_list.html" def get_context_data(self): context = super().get_context_data() return context def get_queryset(self): query_set = super().get_queryset() return query_set class CreatePostView(CreateView): model = models.ForumPost fields = ("title", "description") template_name = "forum/create_post.html" def get_context_data(self): context = super().get_context_data() print("hello idiot") return context -
Adding response for post in ModelViewset
I have to provide a DB status response (which tells if the serializer gets stored or not) after a POST request in ModelViewSet. Please help me perform that in the view. from django.shortcuts import render from .models import Booking from rest_framework import viewsets from .serializers import BookingSerializer class BookingViewSet(viewsets.ModelViewSet): queryset = Booking.objects.all() serializer_class = BookingSerializer -
Django: "readable" 500 page for http clients?
On server error (500), the default debugging behavior of django is to return an HTML page containing the stack trace. However, I'm using django (with rest framework) to create REST api, so I'm accessing it through command line tools, and the returned html is unreadable. Is there any way to customize django to return a more readable, text only response? -
Extract ManyToManyField values
I'm having trouble extracting values from a ManyToManyField in django. I don't get an error, just an empty queryset. Here is my code, can you please take a look and let me know if I'm doing something wrong? I can see the selected values correctly in Admin, which leads me to believe that I have probably stored the values correctly, but I cannot retrieve the values in my views.py. models.py class Colors(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ColorId = models.CharField(primary_key=True, max_length=100) ColorName = models.CharField(default='Na', max_length=100) class Meta: ordering = ('ColorName',) def __str__(self): return self.ColorName class Bike(models.Model): colors= models.ManyToManyField(Colors) def save(self, *args, **kwargs): super().save(*args, **kwargs) forms.py class SettingsUpdateForm(forms.ModelForm): colors = forms.ModelMultipleChoiceField(queryset=Colors.objects.all()) class Meta: model = Bike fields = [ 'colors', ] a snippet from my html template <div class="form-group col-sm-8 col-md-6"> {{ p_form.colors.label_tag }} {% render_field p_form.colors class="form-control" %} </div> I'm able to get other parameters that I have saved by doing something like: bikes= Bike.objects.all() colors= bikes.colors I suspect that this is where I'm doing something wrong, but I can't figure out what. As I mentioned, I'm getting an empty queryset, no errors and I'm able to see the selected values correctly in my Admin panel. Thanks in advance for your … -
Running postgres 9.5 and django in one container for CI (Bamboo)
I am trying to configure a CI job on Bamboo for a Django app, the tests to be run rely on a database (postgres 9.5). It seems that a prudent way to go about is it run the whole test in a docker container, as I do not control the agent environment so I cannot install Postgres there. Most guides I found recommend running postgres and django in two separate containers and using docker-compose to easily manage them. In this scenario each docker image runs just one service, started with CMD. In Bamboo I cannot use docker-compose however, I need to use just one image, so I am trying to get Postgres and Django to run nicely together in one container but with little success so far. My problem is that I see no easy way to start Postgres as a service inside docker but NOT as a docker CMD command, official postgre image uses an entrypoint.sh approach, also described in the official docker docs But it is not clear to me how to implement that. I would appreciate your help! -
Unable to fetch data from Mysql DB until I manually restart the server
I am putting some data on db in one tab of my application then unable to fetch the same data in another tab of the appilcation. I then restarted my server then it showed up. Error in atexit._run_exitfuncs: Traceback (most recent call last): File "C:\Users\pranj\AppData\Local\Programs\Python\Python37-32\Lib\tkinter__init__.py", line 775, in after_cancel data = self.tk.call('after', 'info', id) RuntimeError: main thread is not in main loop on cntrl+c this error gets displayed -
Unable to triger the browser to auto download files from Filereponse
What I am doing is upload files and process them, after that, a zipped file will be generated and automatically be downloaded in the browser. However, I was not able to triger the download using the FileResponse after following the official tutorial. The browser always gives an error saying Something went wrong!:parsererror SyntaxError: Unexpected token P in JSON at position 0. Template: $(document).on('submit', '#productForm', function(e){ e.preventDefault(); var inputFilePath = document.getElementById('sourceFileInput').files.item(0).name; $.ajax({ method: 'POST', dataType: 'json', url: 'validate/', data: { source_file: inputFilePath, region: $("#Region-choice").val(), product_type: $("#Product-type").val()} }) .done(function(){ document.getElementById('lblStatus').innerHTML = "Result: <br/>" document.getElementById('lblStatusContent').innerHTML = "Success!" }) .fail(function(req, textStatus, errorThrown) { document.getElementById('lblStatus').innerHTML = "Result: <br/>" alert("Something went wrong!:" + textStatus + ' ' + errorThrown ) }); document.getElementById('lblStatus').innerHTML = "Working hard...Please take a coffee \u2615 and wait, it might take a while.<br/>"; alert("Submitted!"); }); Relevant views.py def validate(request): """The .delay() call here is to convert the function to be called asynchronously""" if request.method == 'POST': filename = request.POST.get('source_file') file_path = os.path.join(settings.MEDIA_ROOT, 'SourceFiles', filename) region = request.POST.get('region') product_type = request.POST.get('product_type') result = validateSource.delay(file_path, region, product_type) output_filepath, log_filepath = result.get() if os.path.exists(output_filepath) and os.path.exists(log_filepath): zip_filename = zipFiles([output_filepath, log_filepath], filename) response = FileResponse(fs_media.open(zip_filename), 'rb', as_attachment=True) return response raise Http404 def zipFiles(files_list, source_filename): zip_filename = re.sub(r"(.xlsx|.xls)", … -
How to assign group after the ldap parameter?
I would like to assign to group after specific ldap parameter. In Django I have other groups then in ldap. I do something in signals.py, but i want do do the same effect in settings.py, because when I create a new groups i want change something in settings.py I do this in signals.py ant it works global group_name if (gidNumber =='201'): goup_name = 'a ' elif (gidNumber == '202'): user.is_staff = True group_name = 'b' else: group_name = 'c' if(user.groups.filter(name=group_name).exists()!= True ): group = Group.objects.get(name=group_name) user.groups.add(gruop) but i would ilke do this like smoething like this what i try do this in my settings.py AUTH_LDAP_USER_FLAGS_BY_GROUP = { "groups.filter(name='a')": "gidNumber=201,uid=%(user)s,ou=People,dc=yy,dc=xx ", } -
How to allow postgres to connect to Django using torify
I'm trying to run a Django server using torify, but when I run torify python3 manage.py runserver I get below error: Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? I've already added this code to the torrc: HiddenServiceDir /var/lib/tor/hidden_service/ HiddenServicePort 5432 127.0.0.1:5432 HiddenServicePort 5432 localhost:5432 or even just this: HiddenServiceDir /var/lib/tor/hidden_service/ HiddenServicePort 5432 127.0.0.1:5432 But both of them didn't work. -
can not override `route` method inside one of my models
I want to override the route method from the Page wagtail model inside one of my models but it seems that it doesn't work, i am aware of the RoutablePageMixin that isn't what i want,Basically i tried to do what is in the wagtail's doc like this: class Echoer(Page): def route(self, request, path_components): print('inside route method') . . . but i never see that print statement get executed when a request arrive for that page, can anyone please explain what is going on?Thank you -
Getting Characetr encoding error in django Incorrect string value: '\\xF0\\x9F\\x
I getting this error django.db.utils.OperationalError: (1366, "Incorrect string value: '\xF0\x9F\x99\x8F \xF0...' for column 'html_code' at row 1") I created database using this command CREATE DATABASE sample CHARACTER SET utf8; I have these settings in mysql vim /etc/mysql/conf.d/mysql.cnf [mysql] default-character-set=utf8mb4 vim /etc/mysql/mysql.conf.d/mysqld.cnf [mysqld] character-set-server=utf8mb4 collation-server=utf8mb4_unicode_ci I even used this command as well ALTER TABLE sample_randy CONVERT TO CHARACTER SET utf8 The problem is it worked first time i use those command and after sometime it again stop working with same error. I am not sure which thing is resetting the options If i delete the database, create again and run script again then it work again. if i rerun again then it get same error -
how to resolve the problem with starting cmdb
my softwares's version: Django (1.11.13) python 3.4.3 maraidb 10.5 when i use python3 manage.py makemigrations it occured an error with File "/home/python34/lib/python3.4/site-packages/django/db/backends/mysql/base.py", line 101, in execute return self.cursor.execute(query, args) File "/home/python34/lib/python3.4/site-packages/MySQLdb/cursors.py", line 203, in execute raise ProgrammingError(str(m)) django.db.utils.ProgrammingError: unsupported operand type(s) for %: 'bytes' and 'tuple' how can i resolve the problem? -
Can't upload and see image from django models
I am trying to upload images at my model and later on show it at template. Forms.py: class ClanakForma(forms.ModelForm): class Meta: model = Clanak fields = '__all__' Models.py: class Clanak(models.Model): naslov = models.CharField(null=False, blank=True, max_length=120) datumObjave = models.DateField(null=False, blank=False) autor = models.ForeignKey(Autor, on_delete=models.CASCADE, null=True) videofile= models.FileField(upload_to='images/', null=True, verbose_name="") def __str__(self): return str(self.naslov) + ', ' + str(self.datumObjave) + ', ' + str(self.autor) + ', ' + str(self.videofile) views.py def dodajClanak(request): if request.method == 'GET': forma = ClanakForma() elif request.method == 'POST': forma = ClanakForma(request.POST) if forma.is_valid(): data = Clanak() data.naslov = forma.cleaned_data['naslov'] data.datumObjave = forma.cleaned_data['datumObjave'] data.autor = forma.cleaned_data['autor'] data.videofile = forma.cleaned_data['videofile'] #data.email = forma.cleaned_data['email'] data.save() return redirect('readAllNew') return render(request, 'justadded.html', {'forma':forma}) def readAllNew(request): data = list(Clanak.objects.all()) return render(request, 'readAllNew.html', {'data':data}) urls.py: urlpatterns = [ path('dodajClanak/',views.dodajClanak, name='dodajClanak'), path('readAllNew/',views.readAllNew, name='readAllNew'), ] + static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT) justadded.html: <!DOCTYPE html> <html> <head> <title></title> </head> <body> <form action="{% url 'dodajClanak' %}" method="post"> {% csrf_token %} <table border="1"> {{forma.as_table}} </table> <input type="submit" name=""> </form> </body> </html> readAllNew.html <!DOCTYPE html> <html> <head> <title></title> </head> <body> <table border="1"> <tr> <th>Naslov</th> <th>Datum</th> <th>Autor</th> <th>Slika</th> </tr> {% for x in data %} <tr> <td>{{x.naslov}}</td> <td>{{x.datumObjave}}</td> <td>{{x.autor}}</td> <td><img src='{{ MEDIA_URL }}{{ imagefile }}'></td> <td><a href="{% url 'delete' x.id %}">delete</a></td> <td><a href="{% … -
how to implement django remember me option properly
Here i am trying to login with the remember me option,but this code is not working properly.If the remember_me checkbox is not checked then it doesn't logs in and if also the remember me option checked then it logs in but after logout there is also not the username and password already in the login form.How can i implement remember_me option ,Is there any better idea ? forms.py from django import forms class LoginForm(forms.Form): username = forms.CharField(max_length=100) password = forms.CharField(widget=forms.PasswordInput) remember_me = forms.BooleanField() template <form action="" method="post" class="form-signin"> {% csrf_token %} <input type="text" class="form-control mb-2" name='username' placeholder="Username" required autofocus> <input type="password" class="form-control mb-2" name='password' placeholder="Password" required> <button class="btn btn-lg btn-primary btn-block mb-20" type="submit">Sign in</button> <div class="checkbox float-left"> <input type="checkbox" name="remember_me" id="basic_checkbox_1" > <label for="basic_checkbox_1">Remember me</label> </div> <a href="#" class="float-right">Need help?</a> </form> views.py if request.method == 'POST': form = LoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] remember_me = form.cleaned_data['remember_me'] user = authenticate(request,username=username,password=password) if user: login(request,user) if not remember_me: request.session.set_expiry(0) redirect_url = request.GET.get('next', 'home') messages.success(request, 'logged in.') return redirect(redirect_url) else: messages.error(request,'Invalid username or password') else: form = LoginForm() return render(request,'login.html',{'form':form}) -
Django: many-to-many ordering
I have many-to-many server to network through ip relationship: class Server(models.Model): hostname = models.CharField(max_length=50) networks = models.ManyToManyField(Network, through='Ip') class Network(models.Model): name = models.CharField(max_length=50) class Ip(models.Model): ip = models.CharField(max_length=20) I render it to table: Hostname | Network 1 | Network 2 ============================== server 1 | 1.1.1.10 | 5.5.5.100 server 2 | 1.1.1.15 | 5.5.5.20 I need this table to be ordered by column. Ordering by column is easy: Server.objecs.all().order_by('hostname') How can I do the same with two other columns? E.g. if table is ordered by "Network 2" column, order will be "server 2, server 1". -
Graphene Django filter by generic relation
I am using graphene-django with django-filter. Got problem with filtering object with django's GenericForeignKey. I tried custom FilterSet but no luck. So here are my models and schema. class Feature(models.Model): start_time = models.DateTimeField(db_index=True, validators=[validate_start_time]) content_type = models.ForeignKey( ContentType, on_delete=models.CASCADE, limit_choices_to={"model__in": ["album", "collection", "mix"]} ) object_id = models.UUIDField(db_index=True, unique_for_date="start_time") item = GenericForeignKey("content_type", "object_id") objects = FeatureQuerySet.as_manager() class Album(models.Model): cover = ImageField(upload_to="album", blank=True, help_text="600x600") single = models.BooleanField(default=False) featured = GenericRelation("Feature") and here is my schema using DjangoObjectType: class FeatureNode(DjangoObjectType): class Meta: model = Feature interfaces = (relay.Node,) filter_fields = ("content_type",) class AlbumNode(DjangoObjectType): class Meta: model = Album filter_fields = ("is_new_release", "single", "featured") interfaces = (relay.Node,) class FeatureFilter(django_filters.FilterSet): featured__start_time = django_filters.DateFilter() class Meta: model = Album fields = ("featured",) class Query(ObjectType): album = relay.Node.Field(AlbumNode) albums = DjangoFilterConnectionField(AlbumNode, filterset_class=FeatureFilter) What i wanted to do is i want to get Albums query with featured:True flag. Like following: query FeaturedAlbums { albums(featured:True) { edges { node { id } } } } -
How do I freeze time and assert on a timestamp in a template?
p1/urls.py: from django.urls import path from . import views urlpatterns = [ path('t1/', views.t1), ] p1/views.py: from django.shortcuts import render def t1(request): return render(request, 'p1/t1.html') p1/templates/p1/t1.html: <?xml version="1.0" encoding="UTF-8"?> <root timestamp="{% now 'Y-m-d H:i:s' %}">...</root> p1/settings.py: TIME_ZONE = 'Asia/Tokyo' USE_TZ = True INSTALLED_APPS = [ ... 'p1', ] p1/tests.py: from django.test import TestCase from freezegun import freeze_time class MyTestCase(TestCase): @freeze_time('2019-01-02 03:04:05') def test_freezegun(self): expected_response = ''' <?xml version="1.0" encoding="UTF-8"?> <root timestamp="2019-01-02 03:04:05">...</root> ''' response = self.client.get('/t1/') self.assertXMLEqual(expected_response, response.content.decode('utf-8')) Then, $ ./manage.py test Creating test database for alias 'default'... F ====================================================================== FAIL: test_freezegun (p1.tests.MyTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/yuri/_/1/env/lib/python3.7/site-packages/freezegun/api.py", line 658, in wrapper result = func(*args, **kwargs) File "/home/yuri/_/1/p1/p1/tests.py", line 12, in test_freezegun self.assertXMLEqual(expected_response, response.content.decode('utf-8')) File "/home/yuri/_/1/env/lib/python3.7/site-packages/django/test/testcases.py", line 854, in assertXMLEqual self.fail(self._formatMessage(msg, standardMsg)) AssertionError: '\n <?xml version="1.0" encoding="UTF-8"?>\n <root timesta [truncated]... != '<?xml version="1.0" encoding="UTF-8"?>\n<root timestamp="2019-01-02 12:04:05">. [truncated]... - - <?xml version="1.0" encoding="UTF-8"?> ? ------------ + <?xml version="1.0" encoding="UTF-8"?> - <root timestamp="2019-01-02 03:04:05">...</root> ? ------------ ^^ + <root timestamp="2019-01-02 12:04:05">...</root> ? ^^ - ---------------------------------------------------------------------- Ran 1 test in 0.031s FAILED (failures=1) Destroying test database for alias 'default'... System check identified no issues (0 silenced). What am I doing wrong? Adding tz_offset to freeze_time doesn't help. -
How to use mongodb in Django with taking the database flexible structure and queries into consideration?
I'm developing a Django application that uses mongodb in a part of it. My database schema is changing (some fields are deleted/added continuously), so how to integrate it with Django in a way that accepts the changes without changing the old data, and without affecting the search queries? I have searched about the available libraries, and I found the below: mongoengine and django-mongodb-engine: mongoengine is not supported for a while now and not updated, also django-mongodb-engine required a forked old django-nonrel package. This matches with the question: Use pymongo in django directly djongo: Initially it is working fine with the most updated versions of python and Django, and it accepts the changes in my database models without migrations and Django admin panel is working fine. Later on, after applying some changes, I have faced an issue when it comes to querying the database or listing the data in the admin panel. The old data fails to fit with the new model if the change includes deleted fields. pymongo: The disadvantage is that I cannot use django models or panel and I have to build my own database abstract layer, but the advantage is about the higher control that I will … -
Which tables, triggers, views are affected by a drop column cascade in PostgreSQL
Django created a migration for dropping a field from a table: ALTER TABLE "my_table" DROP COLUMN "my_deprecated_field" CASCADE; COMMIT; I would like to know which consquences the CASCADE has, i.e. which other columns, tables, triggers, etc. are going to be affected by it. Since there is no EXPLAIN ALTER, which other means do I have to find out? -
How to Render a table in template
Models timetable_choices =( ('Monday','Monday'), ('Tuesday','Tuesday'), ('Wednesday','Wednesday'), ('Thursday','Thursday'), ('Friday','Friday'), ('Saturday','Saturday'), ) class Timetable(models.Model): day = models.ForeignKey('Day',on_delete=models.CASCADE,blank=True,null=True) start = models.IntegerField() end = models.IntegerField() subject = models.CharField(max_length=12) class Day(models.Model): day = models.CharField(max_length=9, choices=timetable_choices) I have already populated the Day table and Timetable table. Views class Timetabletemplate(TemplateView): template_name = 'timetable.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['timetable'] = Timetable.objects.all() context['monday'] = Timetable.objects.filter(day="Monday") return context Template <table style="width:100%"> <tr> <th></th> <th>1</th> </tr> <tr> <td>Monday</td> {% for item in monday %} <td>{{item.subject}}</td> {% endfor %} </tr> </table> What I am trying to do is render subject in a cell.I have n subjects, number of subjects depend on how many subjects the user has added . I want the subjects when day = Monday in the first row and similarly when day = Tuesday,wednesday in the respective rows below monday . I am getting an error invalid literal for int() with base 10: 'Monday' when I tried this code .