Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django request not recognized
I am currently learning Django with video tutorials and I came across a problem I can't get rid of. I am in the views file of one of my apps and when I try to use "request" it tells me '"request" is not definedPylancereportUndefinedVariable' from django.http import HttpResponse from django.shortcuts import render # Create your views here. def home_view(*args, **kwargs): return render(request, "home.html", {}) def contact_view(*args, **kwargs): return HttpResponse("<h1>contact page</h1>") view code I tried importing HttpRequests and modifying the code to fit but it then tells me that it doesn't have a META attribute when I run the server runserver error I'd like to use "request" and not import a new library for it as it should come with django, the guy in the tutorial I watch just types in request and it works.I couldn't find anything in the Django docs and it seems like using request shouldn't even be an issue. -
How can i round an Sum in Django ojbect
My code: verloningsoverzicht_cumulatief_dagen = Overzicht.objects.filter(periode=periode, jaar=jaar) .values('testcontract', 'contract') .annotate(aantal=Sum('aantal')) Now lets say the .annotatie Sum is 6.3500000, i want it rounded to 6.35 The round method is not working, how can i solve this .annotate(aantal=round(Sum('aantal'),2)) -
How to create a persistent html5 audio player?
I have the following code to open a player on my website for audio playback using Django: {% if track.file.hls_stream %} <a type="button" class="btn btn-outline-primary" href="{% url 'stream' pk=track.file.pk|safe|cypher_link_stream %}" target="_blank"><i class="fad fa-play-circle"></i></a> ... Currently this opens a new tab and uses VideoJS to play the HLS stream. But actually this is not what I want. I would like to hit the play button, and a audio player pop's up at the bottom of the page and stays there while navigating on the site. I already searched for such a solution but didn't had that much luck. Can someone maybe give me a hint where to look at? Thanks in advance. -
Django - Create a Profile model based to built-in User model
Im creating a car rental system in Django, where every logged in users can place their car for Rent. To create Users, im using the Django's built in User model and UserCreationForm. Although this is not what i need because i have to assign a car_for_rent variable to the User model What i would like to do is when i register a user(Based on User Model), to actually create a Person Instance, based on that User model, if this makes sense. Im trying something like this Models.py from django.db import models from django.contrib.auth.models import User class Car(models.Model): model_car= models.CharField(max_length=200) description = models.TextField() car_image = models.ImageField(null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.model_car class Person(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) car_for_rent = models.ForeignKey(Car,on_delete=models.CASCADE) forms.py #authentication from django.contrib.auth.forms import UserCreationForm from django import forms from django.contrib.auth.models import User class CreateUserForm(UserCreationForm): class Meta: model = User fields=[ 'username', 'email', 'password1' ,'password2' ] So right now it just creates a user based only on User Model -
Reverse for 'printReports' with arguments '('',)' not found. 1 pattern(s) tried
My app currently runs through settings that are saved to the database in-order to print financial documents. I am using the pk variable to fetch the correct forms etc. However now when I am trying to redirect to the pk for 'printReports' in my project. It returns the above error. I am trying to figure out where I have mapped this wrongly , but I can't seem to find any errors Please see the below code: Views.py: def printReports(request , reports_pk): pkForm = get_object_or_404(SettingsClass , pk=reports_pk) form= SettingsClass(instance=pkForm) ### Printing Trial Balance PDF response = HttpResponse(content_type= 'application/pdf') response['Content-Disposition']= 'attachment; filename=TrialBalance' + \ str(datetime.now()) + '.pdf' response['Content-Transfer-Encoding'] = 'binary' content = {"arr_trbYTD":arr_trbYTD , 'xCreditTotal':xCreditTotal , 'xDebitTotal':xDebitTotal , 'complexName':complexName , 'openingBalances': openingBalances ,'printZero':printZero} html_string=render_to_string('main/pdf-trialbalance.html' , content) html=HTML(string=html_string) result=html.write_pdf() with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output.seek(0) response.write(output.read()) return response else: printTrialBalance = False return render(request , 'main/printReports.html') URLS.PY: #Reports path('reportsHome' , views.reportsHome, name='reportsHome'), path('accConnect/printReports/<int:reports_pk>' , views.printReports , name='printReports') reportsHome.html: {% extends "main/base.html"%} {% block content%} <h1 style=" text-align: center">Reports</h1> <hr> <br> <div class="list-group"> <a href="#" class='list-group-item active'>Print Single Complex's</a> {% for x in model %} <a href="{% url 'printReports' reports.pk %}" class="list-group-item list-group-item-action" >{{ x.Complex }} Reports</a> {% endfor %} </div> {% endblock … -
Why isn't my .Dockerignore file not ignoring files?
When I build the container and I check the files that should have been ignored, most of them haven't been ignored. This is my folder structure. Root/ data/ project/ __pycache__/ media/ static/ app/ __pycache__/ migrations/ templates/ .dockerignore .gitignore .env docker-compose.yml Dockerfile requirements.txt manage.py Let's say i want to ignore the __pycache__ & data(data will be created with the docker-compose up command, when creating the container) folders and the .gitignore & .env files. I will ignore these with the next .dockerignore file .git .gitignore .docker */__pycache__/ **/__pycache__/ .env/ .venv/ venv/ data/ The final result is that only the git & .env files have been ignored. The data folder hasn't been ignored but it's not accesible from the container. And the __pycache__ folders haven't been ignored either. Here are the docker files. docker-compose.yml version: "3.8" services: app: build: . volumes: - .:/django-app ports: - 8000:8000 command: /bin/bash -c "sleep 7; python manage.py migrate; python manage.py runserver 0.0.0.0:8000" container_name: app-container depends_on: - db db: image: postgres volumes: - ./data:/var/lib/postgresql/data environment: - POSTGRES_DB=${DB_NAME} - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} container_name: postgres_db_container Dockerfile FROM python:3.9-slim-buster ENV PYTHONUNBUFFERED=1 WORKDIR /django-app EXPOSE 8000 COPY requirements.txt requirements.txt RUN apt-get update \ && adduser --disabled-password --no-create-home userapp \ && apt-get -y … -
Serializers.validated_data fields got changed with source value in DRF
I am trying to create an api, where user can create programs and add rules to them. Rules has to be executed in order of priority. I am using Django rest framework to achieve this and I am trying to achieve this using Serializer without using ModelSerializer. Provide your solution using serializers.Serializer class One program can have many rules and one rule can be in many programs. So, I am using many_to_many relationship and also I want the user to change the order of rules in a program, to achieve this I am using a through table called Priority, where I keep track of relationship between a rule and a program using priority field models.py class Program(models.Model): name = models.CharField(max_length=32) description = models.TextField(blank=True) rules = models.ManyToManyField(Rule, through='Priority') class Rule(models.Model): name = models.CharField(max_length=20) description = models.TextField(blank=True) rule = models.CharField(max_length=256) class Priority(models.Model): program = models.ForeignKey(Program, on_delete=models.CASCADE) rule = models.ForeignKey(Rule, on_delete=models.CASCADE) priority = models.PositiveIntegerField() def save(self, *args, **kwargs): super(Priority, self).save(*args, **kwargs) serializers.py class RuleSerializer(serializers.Serializer): name = serializers.CharField(max_length=20) description = serializers.CharField(allow_blank=True) rule = serializers.CharField(max_length=256) def create(self, validated_data): return Rule.objects.create(**validated_data) def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.description = validated_data.get('description', instance.description) instance.rule = validated_data.get('rule', instance.rule) instance.save() return instance class PrioritySerializer(serializers.Serializer): rule_id = serializers.IntegerField(source='rule.id') rule_name … -
Django Model's DateTimeField is taking UTC even when timezone is Asia/Calcutta everywhere. I can't set USE_TZ = False
My Django Server is storing time in UTC format. I want them in IST. But the problem is I can't set USE_TZ = False. Otherwise, it throws more errors and warnings. Pls, help me!!! TIME_ZONE = 'Asia/Calcutta' USE_I18N = True USE_L10N = True USE_TZ = True -
How to remove results with same value with django ORM?
I have a query that returns data that will be displayed in the browser as a line chart. Depending on the period chosen, this can represent a rather huge number of results (~25K max). Most of the time these values do not change, on average on 25 000 results I have about 8000 different values. I think it would be a real optimization if I only return these 8000 values instead of the 25 0000. My Model: class TechnicalData(models.Model): name = models.CharField(_('Name'), max_length=80) value = models.CharField(_('Value'), max_length=80) value_type = models.CharField(_('Value type'), max_length=20) date_time = models.DateTimeField(_("timestamp")) machine = models.ForeignKey("machine.Machine", verbose_name = _("machine"), related_name="technical_data_machine", on_delete=models.CASCADE) class Meta: verbose_name = _("TechnicalData") verbose_name_plural = _("TechnicalDatas") ordering = ["-date_time"] def __str__(self): return self.name If the "value" field does not change during a given period (date_time), I would like to remove the "duplicate/same" values. Today I have this view: class TechnicalDataViewSet(viewsets.ViewSet): """ A simple ViewSet for listing or retrieving technical data. """ permission_classes = [permissions.IsAuthenticated] pagination_class = LargeResultsSetPagination def list(self, request): id_machine = self.request.query_params.get('id_machine') name = self.request.query_params.get('name') only_last = self.request.query_params.get('only_last') names = self.request.query_params.get('name__in') date_start = self.request.query_params.get('date_start') date_end = self.request.query_params.get('date_end') queryset = TechnicalData.objects.all() if id_machine: queryset = queryset.filter(machine__id=id_machine) if name: queryset = queryset.filter(name=name) if names: names = … -
In this how i want to multiply quantity and unit_price to show in total?
class orderdetails(models.Model): product = models.CharField(max_length=100,default='') quantity = models.IntegerField() unit_price = models.IntegerField() total= () -
How to disiable BIGGERkeysses into an authentication application builded in django?
I want only to create users with lowercases into an authentication app login page -
Save Form after successful stripe Payment
I have a model form that the user fills. This form contains a file field as well. After filling in the form once the user presses the submit button, the form is saved to the database using POST after getting verified. What I would like to do is once the user clicks the submit button, they should be taken to another page to make a payment. The payment page will be created using Stripe Payment Intent and not Stripe Checkout. Once they have successfully paid I would like to save the data that the user have filled in the form.I have created the Stripe Payment page and I can see payments being made on the Stripe dashboard but I would like to save the data that the user has filled in the form after successful payment. How do I go about doing this in Python3 , Django? -
Django sales campaign model with list of foreign keys that can only appear in one sales campaign?
I want to create a sales campaign which stores a list of books (Items). But the book should only be applied to one sales campaign — ie. it should not be able to appear in two campaigns. I have the following model: class Campaign(models.Model): campaign_name = models.CharField(max_length=50, null=False, blank=False, default='Special Offer') included_items = models.ManyToManyField(Item, blank=True) active = models.BooleanField(default=True) fixed_price = models.DecimalField(max_digits=6, blank=True, null=True, decimal_places=2) But I think the included_items field might be of the wrong field type. From reading other questions and the Django manual, I think I may be approaching this back to front. Perhaps I should be tackling this from the Item model instead? (Shown below for reference) class Item(models.Model): sku = models.CharField( max_length=10, null=True, blank=True, default=create_new_sku) title = models.CharField(max_length=254) genre = models.ManyToManyField('Genre', blank=True) author = models.ManyToManyField('Author', blank=True) description = models.TextField() age_range = models.ManyToManyField( 'Age_range') image_url = models.URLField(max_length=1024, null=True, blank=True) image = models.ImageField(null=True, blank=True) price = models.DecimalField(max_digits=6, decimal_places=2, default=0.00) discount = models.DecimalField(max_digits=2, decimal_places=0, default=0) set_sale_price = models.DecimalField(max_digits=6, decimal_places=2, default=0.00) original_sale_price = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True) final_price = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=False, editable=False) -
Django how to pass arguments from views.py to websocket "on_open" function in another file
In my Django in tasks.py file I am using websocket connection - on_open_socket function: def on_open__socket(ws): print("Socket connected") My connection: ws.on_open = on_open_socket How can I pass additional arguments dynamically to "on_open_socket" from views.py, like following: def on_open__socket(ws, {new arguments -> name, date}): print("Socket connected") stream = { "name" = name "date" = date } I tried using partial, but I cannot figure out how to do this from views.py. -
Adding the first product in cart returns intergrity error
In the views.py logic, as you can see that i have printed three characters x, y and z for the outer else block which create a new order with the first product being added. However if the cart is empty and try to add a product , it throws an error saying: null value in column "order_id" of relation "onlineshopping_order" violates not-null constraint DETAIL: Failing row contains (2021-09-23 07:49:55.861471+00, 2021-09-23 07:49:55.861471+00, f, 2, null, null, null, null). views.py: @login_required def add_to_cart(request, slug): item = get_object_or_404(AffProduct, slug=slug) order_item, created = OrderItem.objects.get_or_create( item=item, user=request.user, ordered=False ) order = Order.objects.filter(user=request.user, ordered=False).first() if order: # check if the order item is in the order if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() messages.info(request, "This item quantity was updated.") else: order.items.add(order_item) messages.info(request, "This item was added to your cart.") else: # ordered_date = timezone.now() print('x') order = Order.objects.create(user=request.user) print('y') order.items.add(order_item) print('z') messages.info(request, "This item was added to your cart.") return render(request, 'cart.html', {'order_item': order_item, 'object': order}) -
Reverse for 'printReports' with arguments '('',)' not found. 1 pattern(s) tried
My app currently runs through settings that are saved to the database in-order to print financial documents. I am using the pk variable to fetch the correct forms etc. However now when I am trying to redirect to the pk for 'printReports' in my project. It returns the above error. I am trying to figure out where I have mapped this wrongly , but I can't seem to find any errors Please see the below code: Views.py: def printReports(request , reports_pk): pkForm = get_object_or_404(SettingsClass , pk=reports_pk) form= SettingsClass(instance=pkForm) complexName = form.Complex printTrialBalance = True includeOpeningBalance = '' useMainAccounts = 'len(Master_Sub_Account) < 5 ' printNullValues = '' # else it will print null values printDescription = '' # if false it wil remove the print description line printAccount = '' # if false it wil remove the print account line OrderByAccount = 'ORDER BY iAccountType ' #CHECKING TRIAL BALANCE SETTINGS if form.Trial_balance_Year_to_date == True: printTrialBalance = True baseTRBYear = 'Inner JOIN [?].[dbo].[Accounts] '\ 'on Accounts.AccountLink = genLedger.AccountLink '\ 'Inner JOIN [?].[dbo].[_etblGLAccountTypes] as AccountTypes '\ 'on Accounts.iAccountType = AccountTypes.idGLAccountType '\ 'WHERE genLedger.AccountLink not in (161,162,163,164,165,166,167,168,122) '\ 'AND genLedger.TxDate > ?'\ op1 = '' op2 = '' op3 = '' op4 = '' … -
Problem with dynamic media in django project when i deploy on server with docker and nginx
I have a problem with an image that I upload to django-admin. Photos are added to the media folder in the running container, but it seems that the photos are trying to be taken from local files where they are not present. All working on my own computer, but i have faced with this problem when tried to deploy on server That's how it's looking in site enter image description here nginx can't find it enter image description here i have tried something like this Django static files not served with Docker but its not work for me This is my files structure: booking2 assets media main-app booking2 docker nginx Dockerfile nginx.conf docker-compose.yml Dockerfile entrypoint.sh .env main Dockerfile FROM python:3.8-alpine ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /app RUN apk --update add RUN apk add gcc gcc python3-dev libc-dev libffi-dev jpeg-dev zlib-dev libjpeg libxml2-dev libxml2 libxslt-dev gettext RUN apk add postgresql-dev RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt COPY . . RUN chmod +x entrypoint.sh ENTRYPOINT ["/app/entrypoint.sh"] docker-compose.yml version: "3.7" services: web: build: context: . dockerfile: Dockerfile ports: - "8000:8000" entrypoint: - ./entrypoint.sh depends_on: - postgresdb postgresdb: build: context: ./docker/postgres dockerfile: Dockerfile environment: - … -
Does not show the login page
I am totally new in django. I tried to make a login form .whenever i press submit button i get the login/login URL it doesn't exist. This is my method in View.py(where i think the problem happens hereenter image description here) (when i go to the login page it shows me the page correctly but button do something wrong) def login(req): if req.method=='post': username=req.POST['username'] password=req.POST['password'] print(username,password) user=auth.authenticate(username=username,password=password) if user is not None: auth.login(req,user) return redirect("/") else: return redirect("task:all") else: return render(req, "Login.html") this is in urls.py path("login/", views.login, name='login'), path("logout/", views.logout, name='logout'), and this is my HTML <form action="login" method="post"> {% csrf_token %} <label for="username"><b>Userame</b></label> <input type="text" placeholder="Enter Username" name="username" required> <label for="psw"><b>Password</b></label> <input type="password" placeholder="Enter Password" name="password" required> <div class="row justify-content-center "> <button type="submit" class="signupbtn btn btn-primary" name="btn">Login</button> </div> </form> -
Convert Django framework to Django rest framework
To make the curl post request work, I am converting my existing Django project to Django REST framework. I have installed djangorestframework==3.12.4. My settings.py INSTALLED_APPS = [ .... 'rest_framework', ] REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ] } My views.py from django.shortcuts import render from . import forms from . import student_details_module from django.http import HttpResponseRedirect def student_details(request): submitted = False print (request) if request.method == 'POST': form = forms.studentDetailsForm(request.POST) if form.is_valid(): cd = form.cleaned_data return_message,return_code = student_details_module.show_data(cd['name']) return HttpResponseRedirect('/student_details?submitted=True') else: form = forms.studentDetailsForm() if 'submitted' in request.GET: submitted = True return render(request, 'student_details.html', {'form': form, 'submitted': submitted} ) How do I convert my view so it works well with djangorestframework. Please suggest. -
How do you customize dropdown container of option in html/css? please help i'm a beginner
i would like to change the border radius and border of the thing that is pointed by an arrow Here's my code: HTML- I use django forms and defined the class there: <div class="container-form"> <h1>ADD ISSUE</h1> <form action="" method="POST"> {% csrf_token %} {% for form in forms %} {{ form|safe }} {% endfor %} <input type="submit" value="create" class="submit-form"> </form> </div> Django forms: class IssueForm(ModelForm): project_bug = forms.CharField(max_length=200, required=True, widget=forms.TextInput(attrs={'class':'bug_form_text', 'placeholder':'Write your issue here'})) status = forms.ChoiceField(choices=Issue.StatusType.choices, required=True, widget=forms.Select(attrs={'class':'bug_form_dropdown'})) difficulty = forms.ChoiceField(choices=Issue.DifficultyType.choices ,required=True, widget=forms.Select(attrs={'class':'bug_form_dropdown'})) Css: .bug_form_text{ margin-top: 1em; border: none; border-bottom: 2px solid black; padding-bottom: .5em; outline: none; font-size: 1rem; background-color: transparent; } .bug_form_dropdown{ margin-top: 1em; border: none; outline: none; height: 4vh; background-color: #262626; color: #f2f2f2; border-radius: 3px; width: 70%; overflow: hidden; transition: ease-in 1s; } .submit-form{ margin-top: 1em; border: none; border-radius: 3px; outline: none; padding: .7em 2em; background-color: #e50914; color: #f2f2f2; } Attempted: I tried .bug_form_dropdown option{} it didn't work please help -
How django-filter called inside class based view?
I am just trying to work with django-filters. Below are the details : filters.py import django_filters from .models import work_allocation class WorkFilter(django_filters.FilterSet): class Meta: model = work_allocation fields = '__all__' views.py from .filters import WorkFilter class get_task_list(ListView): model = work_allocation myFilter = WorkFilter() work.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h2>List of Tasks</h2> <form method="GET"> {{myFilter.form}} </form> </body> </html> But I do not see any changes on my web page. Is that the right way I am calling filter? Please suggest -
How do I run a functon right after posting a model DRF
I have an api that has two models Company (which requires company name) and Info (which i want to be filled automatically based on the Company name) So what I'm doing there is asking for a company name at "localhost:8000/company/" then I want to get this name, add it to the link then get the information from finance.yahoo.com with get request as csv, run through it and fill my Info model with the information. The problem is when I'm calling Company.objects.last() it gets me the information about previous company For example: I post ZUO, it gets me nothing, then i post PD and I get info about ZUO Here is my models.py class Company(models.Model): company = models.CharField(max_length=10) class Info(models.Model): Date = models.CharField(max_length=64) Open = models.CharField(max_length=64) High = models.CharField(max_length=64) Low = models.CharField(max_length=64) Close = models.CharField(max_length=64) AdjClose = models.CharField(max_length=64) Volume = models.CharField(max_length=64) Here is my view.py def get_download_url(): comp = Company.objects.last() downloadUrl = ('https://query1.finance.yahoo.com/v7/finance/download/' + comp.company.upper() + '?period1=0&period2=5000000000&interval=1d&events=history&includeAdjustedClose=true') return downloadUrl def get_information(): downloadUrl = get_download_url() headers = {'User-Agent': 'user-agent'} response = requests.get(downloadUrl, headers=headers) info = [string.split(',') for string in response.text.split('\n')[1::]] return info class CompanyViewSet(viewsets.ModelViewSet): serializer_class = CompanySerializer queryset = Company.objects.none() def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) Info.objects.all().delete() info = … -
AttributeError 'list' object has no attribute '_committed'
I have created a page where the staff will upload their image and description, but when i click on the submit button, I got this error: AttributeError 'list' object has no attribute '_committed' as shown in the picture below. How do I fix this error? What die I do wrong in my code? AttributeError 'list' object has no attribute '_committed' traceback: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/add/ Django Version: 2.2.20 Python Version: 3.8.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'account.apps.AccountConfig', 'crispy_forms'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django_session_timeout.middleware.SessionTimeoutMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs) File "E:\Role_based_login_system-master\account\views.py" in addPhoto 422. photo = Photo.objects.create( File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py" in create 422. obj.save(force_insert=True, using=self.db) File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py" in save 743. self.save_base(using=using, force_insert=force_insert, File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py" in save_base 780. updated = self._save_table( File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py" in _save_table 873. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py" in _do_insert 910. return manager._insert([self], fields=fields, return_id=update_pk, File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) … -
How to add values for checked rows
The code below prints the list of students in Django as a table. I would like to add the name of the currently logged in account to the teacher column in the checked row when the 'Add Teacher' button is clicked. And I want the added data to be reflected in the DB. <table id="student-list" class="maintable"> <thead> <tr> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Name</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Register Date</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Age</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Sex</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Teacher</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Select</th> </tr> </thead> <tbody> {% for student in students %} <tr> <td>{{ student.name }}</td> <td>{{ student.register_date|date:'Y-m-d' }}</td> <td>{{ student.age }}</td> <td>{{ student.sex }}</td> <td>{{ student.teacher}}</td> <td><input type="checkbox"></td> </tr> {% endfor %} </tbody> </table> <input type="button" value="Add Teacher" class="addteacher"> </table> <script> $(function() { $(document).on("click", ".addteacher", function() { var getselectedvalues=$(".maintable input:checked").appendTo($(".maintable tbody").add(getselectedvalues)); }) }); </script> -
Ger all form data as a list, iterate over it and dilplay them in a table on template
I am working on a simple school project where students and teachers are registered as users. class monitors get a student list of their class and monitors have to submit and send a report to class teacher that all the students in the class are present for a certain lesson. So I have created a student model where parent class is the admission number. Then I have filtered a certain class (ex: Grade-6) and render them in to a template (grade-6 dashboard) and gave access to grade 6 class monitor. So the monitor can see all the student with their admission number on monitor dashboard. Then I have insert a select option with each student to select yes or no to say he or she is present or not. Then submit. After submitting in my view.py I get all the data as request.POST. But after saving the form (form.save()) I get last student details only. But all the details are in request.POST but I cannot get them to render in to a template. I dont know how. So I tried getting them as a list or a dict but couldnt. Please help me on getting this done. My form in …