Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'ReturnList' object has no attribute 'get' in django restframework
I'm trying to create a custom render method in DRF , here are my code : serializers class SupplierSerializer(serializers.ModelSerializer): class Meta: model = models.Supplier fields = [ # "plan", "type", "created", "id", "name", "bio", "established", "logo", "last_updated", "is_active", "date_to_pay", "mobile", "password", ] the Renderer class ApiRenderer(BaseRenderer): media_type = 'text/plain' format = 'txt' def render(self, data, accepted_media_type=None, renderer_context=None): response_dict = { 'status': 'failure', 'data': {}, 'message': '', } if data.get('data'): response_dict['data'] = data.get('data') if data.get('status'): response_dict['status'] = data.get('status') if data.get('message'): response_dict['message'] = data.get('message') data = response_dict return json.dumps(data) settings RENDERER_CLASSES = ( 'market_control_panel.renderers.ApiRenderer', ) REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', # <-- And here 'rest_framework.authentication.TokenAuthentication', # <-- And here ], # testing ftp upload after comment 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_RENDERER_CLASSES': RENDERER_CLASSES, } But I get this error when I try to open any API link : 'ReturnList' object has no attribute 'get' -
Is there a way to know if a website is in development mode or production mode in Django?
Because when in development and production, the setting file has to be so much different For example Development: DEBUG = true ... ALLOWED_HOSTS = [] ... EMAIL_PAGE_DOMAIN = 'http://127.0.0.1:8000' Production: DEBUG = false ... ALLOWED_HOSTS = ['example.com'] ... EMAIL_PAGE_DOMAIN = 'https://example.com' I don't know if there is a condition to check if the app is in development mode or production mode so that I don't hard-code it. The code should change automatically based on its mode. I imagine something like this if in-development-mode() == true: #code for devopmenet else: #code for production -
How to make video storage in django using youtube videos?
I am developing video content project, where videos are paid. when user pay for video, the videos should be available to users, otherwise videos are not available. Is it possible to use Youtube as video storage. I read about django-embed-video library, maybe it is for only public videos, my videos are private. When user buys video, then video should available for that user. -
Create an instance from TextInput in CreateView
I know the tittle doesn't make much sense, bear with me I can find shorter way to describe my problem. models.py class Aurthor(models.Model): name = models.CharField("Author Name", max_length=100) def __str__(self): return self.name class Article(models.Model): title = models.CharField("Title", max_length=100) content = RichTextField(blank=True, null=True) pub_date = models.DateTimeField("Publish Date", auto_now_add = True) aurthor = models.ForeignKey(Aurthor, on_delete=models.CASCADE) def __str__(self): return self.title Article has a foreign key Aurthor so in my html when creating an article select will be used, but I don't want to select from Aurthors, I want to input type='text' then use that input to create an Aurthor instance. Like the way I have don it here: views.py def blog(request): articles = Article.objects.all() context = { 'date': datetime.timetuple(datetime.now()).tm_year, 'articles': articles } if request.method == 'POST': aurthor = Aurthor(name=request.POST['aurthor_name']) article = Article(title=request.POST['article_title'], content=request.POST['article_content'], pub_date=str(datetime.now().date()), aurthor=aurthor) aurthor.save() article.save() blog.html <form action="" method="post"> {% csrf_token %} <h3>Write an Article here.</h3> <label for="article_title">Title</label> <input type="text" name="article_title" required> <textarea name="article_content" id="article_content" required></textarea><br /> <label for="aurthor_name">Aurthor Name</label> <input type="text" name="aurthor_name" required> <button type="submit">Post</button> </form> This works well, now the question is that I want to do this but using CreateView as my class based view and Django forms.py -
I am working on a django project. and my loops are iterating two times but I only want it to iterate one time
.I've used loops to display data from database.I want the contents of two tables to display next to each other in a card so I used two loops that is a loop within a loop {%for plan in plans%} {%for natural in naturals%} Card title Some quick example text to build on the card title and make up the bulk of the card's content. Go somewhere {{plan.name}} {{natural.name}} {{natural.amount}} function createPaymentParams() { // Create payment params which will be sent to Flutterwave upon payment {% autoescape off %} let pay_button_params = JSON.parse('{% if user.is_authenticated %}{% pay_button_params user_pk=user.pk plan_pk=plan.pk %}{% endif %}'); {% endautoescape %} paymentParams['{{ plan.name }} '] = { public_key: pay_button_params.public_key, tx_ref: pay_button_params.tx_ref, amount: '{{plan.amount}} ', currency: '{{plan.currency}}', redirect_url: pay_button_params.redirect_url, payment_plan: '', payment_type:'', customer: { email: '{{ user.email }}', name: '{{ user.first_name }} {{ user.last_name }}', }, customizations: { title: '', logo: 'https://edoctorug.com/static/img/edoctor.png', }, } } if ('{{ user.is_authenticated }}' === 'True') { createPaymentParams(); } {% if user.is_authenticated %} {{ plan.pay_button_text }} {% else %} User must be signed in {% endif %} function createPaymentParams() { // Create payment params which will be sent to Flutterwave upon payment {% autoescape off %} let pay_button_params = JSON.parse('{% if user.is_authenticated %}{% … -
When trying to use export as csv i get only id
I am using django export as CSV, i have this model: class Order(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="product") customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) fname = models.CharField(max_length=100, null=True) address = models.CharField(max_length=1000, null=True) phone = models.CharField(max_length=12, null=True) price = models.IntegerField() disc_price = models.IntegerField(null=True, blank=True) date = models.DateTimeField(blank=True, null=True, auto_now_add=True) status = models.CharField( max_length=100, blank=True, null=True, default="Unpaid") payment_method = models.ForeignKey( PaymentMethod, on_delete=models.CASCADE, blank=True, null=True) order_status = models.ForeignKey(OrderStatus, on_delete=models.CASCADE, null=True, blank=True) total = models.IntegerField(null=True, blank=True) transaction_id = models.CharField(max_length=255, blank=True, null=True, unique=True) i get everything but I am getting product id and order status id Here I want product name status name but I am getting product ID, status ID def export_orders(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="Orders.csv"' writer = csv.writer(response) writer.writerow(['id', 'Customer', 'Full Name', 'Phone Number', 'address', 'product', 'quantity', 'price', 'total', 'Payment Status', 'Order Status']) orders = Order.objects.all().values_list('id', 'customer', 'fname', 'phone', 'address', 'product', 'quantity', 'price', 'total', 'status', 'order_status') for order in orders: writer.writerow(order) return response -
Field 'id' expected a number - Uploading ForeignKey to django-import-export
I am trying to import data from an csv file into a django db using django-import-export. My problem is trying to upload data with a ForeignKey as an object. I have migrated, followed docs, and still no solution. You can see my error below in the django admin: Here is my csv data with a blank 'Id' column: models.py from django.db import models from django.shortcuts import reverse from urllib.parse import urlparse class States(models.Model): name = models.CharField(max_length=96, blank=False, unique=True) abbrv = models.CharField(max_length=2, null=True, blank=True) class Meta: ordering = ['name'] verbose_name = 'State' verbose_name_plural = 'States' def __str__(self): return f'{self.name}' class Person(models.Model): last_name = models.CharField( max_length=255, help_text="Enter your last name.") first_name = models.CharField( max_length=255, help_text="Enter your first name or first initial.") address = models.CharField( max_length=255, blank=True, help_text="Enter your street address.") city = models.CharField( max_length=255, blank=True, help_text="Enter your city.") state = models.ForeignKey('States', to_field='name', on_delete=models.SET_NULL, null=True) zipcode = models.CharField(max_length=50) website = models.URLField( max_length=255, blank=True) profession = models.CharField(max_length=50, blank=True) # META CLASS class Meta: verbose_name = 'Person' verbose_name_plural = 'Persons' ordering = ['last_name', 'first_name'] # TO STRING METHOD def __str__(self): """String for representing the Model object.""" return f'{self.last_name}, {self.first_name}' admin.py: from django.contrib import admin from .models import Person, States from import_export.admin import ImportExportModelAdmin from import_export.widgets … -
Transferring 100+GB of data from a database table to UI using Django ReST apis
I am trying to show data in React UI from a database using Django ReST APIs. Since my table has more than a billion rows, I can't fetch all the data at once and keep it into memory. I can only display 10-20 rows at a time. While user scrolling down I would like to call apis to fetch the data(Approximately for every 200 rows I will call an API). In this case, I can achieve it by setting chunk_size in pandas using SQLAlchemy. In order to get next set of data the python session shouldn't be closed. But according to my knowledge, the python session is persistent to each API. But, I want to share same python session for multiple APIs. Kindly help me to handle this situation. -
Django - Customize Form, Specifically how fields look
I have a form class which has several fields. One of them is the first and last name field. My goal is to modify my form in my html file so that it can take in input and pass it into a model object. However, I want this to not change how my form displays. The problem is that the fields show up differently when I use django's template language. I tried to modify the first name field with django's template language by replacing the following bootstrap code with django template language code: <div class="form-group col-md-12"> <label for="{{ form.first_name.id_for_label }}">First Name</label> <input type="text" class="form-control" id="first_name" placeholder="Ex. John"> </div> has been changed to: <div class="form-group col-md-12"> {{ form.first_name.label_tag }} {{ form.first_name }} </div> This does not work. I want the first name field to display the same as the last name field. How can I do this? My full code right now: <div class="form-row"> {{ form.first_name.errors }} <div class="form-group col-md-12"> <!--<label for="{{ form.first_name.id_for_label }}">First Name</label>--> <!--<input type="text" class="form-control" id="first_name" placeholder="Ex. John">--> {{ form.first_name.label_tag }} {{ form.first_name }} </div> </div> <div class="form-row"> <div class="form-group col-md-12"> <label for="last_name">Last Name</label> <input type="text" class="form-control" id="last_name" placeholder="Ex. Doe"> </div> </div> -
Create model instance on subclassing
Prerequisite I want to implement abstract inheritance: class Base(models.Model): title = models.CharField() slug = models.SlugField() description = models.TextField() class Meta: abstract = True class ChildA(Base): foo = models.CharField() class ChildB(Base): bar = models.CharField() For multiple reasons I need a db representation of hierarchy of these classes. So I want to create a model like this one (left and right attributes allow us to identify instance's place in the node tree): class Node(models.Model): app_label = models.CharField() model_name = models.CharField() parent = models.ForeignKey('self', blank=True, null=True) right = models.PositiveIntegerField() left = models.PositiveIntegerField() The Problem I need something similar to this: class Base(models.Model): ... def __init_subclass__(cls): app_label = cls._meta.app_label model_name = cls._meta.model_name parent_id = ? # I am not sure how do we get parent's id for now, but it should be manageable obj = Node.objects.create('app_label'=app_label, 'model_name'=model_name, 'parent'=parent_id) obj.save() So, as we subclass an abstract model, a new node is created that represents this new model in the hierarchy tree. Unfortunately, it won't work. It seems __init_subclass__ is invoked before Model class is properly initialized, so cls._meta.model_name will return incorrect value (parent's model_name, in fact). Can we bypass this (or use some other hook)? Other concerns I am not sure if this whole idea … -
Overriding save method doesnt work Django
My goal was to autocomplete the reservation_days field based on the initial_day and days_delta fields so that the reservation_days field contains a list of dates from initial_day to days_delta models.py from django.db import models from django.contrib.auth import get_user_model from datetime import datetime, date, timedelta User = get_user_model() class Office(models.Model): workplaces = models.IntegerField(verbose_name='number of workplaces') price = models.IntegerField(verbose_name='full office price') class Workplace(models.Model): price = models.IntegerField(verbose_name='workplace cost') office = models.ForeignKey(Office, verbose_name='workplace location', on_delete=models.CASCADE, null=True) class Reservation(models.Model): RESERVATION_TYPES = ( ('office', 'office'), ('workplace', 'workplace') ) reservation_type = models.CharField(verbose_name='reservation type', choices=RESERVATION_TYPES, max_length=9) offices = models.ForeignKey(Office, verbose_name='offices for reservation', on_delete=models.CASCADE, null=True) workplaces = models.ForeignKey(Workplace, verbose_name='workplaces for reservation', on_delete=models.CASCADE, null=True) initial_day = models.CharField(verbose_name='days delta initial day', max_length=10, default='123') days_delta = models.IntegerField(verbose_name='days delta', null=True) reservation_days = models.CharField(verbose_name='list with reservation days', max_length=1000) def save(self, *args, **kwargs): for delta in range(2): self.reservation_days += ',' + date.isoformat(date.fromisoformat(self.initial_day) + timedelta(days=1)) super(Reservation, self).save(*args, **kwargs) user = models.ForeignKey(User, verbose_name='owner', on_delete=models.CASCADE) but when i send the request i get { "reservation_days": [ "This field may not be blank." ] } or { "reservation_days": [ "This field is required." ] } -
In django, what is the correct way to pass a form input into a custom email template as a variable?
Here is my email view function in which I am passing form to context and I have tried using the {{ form.name.value }} as suggested in other posts but in the received email, it doesn't appear in email_invite.html template attachment; not even a white space. How can I get that name variable to render. I got it in the subject but do I need to also pass name in to the context and how if so is the correct way to use it in the template. Thanks in advance def email_invite(request): if request.method == 'POST': form = EmailInviteForm(request.POST) if form.is_valid(): cd = form.cleaned_data name = f'{cd["name"]}' subject = f'{cd["name"]} has sent you a invitation' from_email = settings.DEFAULT_FROM_EMAIL comment = f'{cd["comment"]}' html_template = get_template('profiles/email/email_invite_message.html').render() msg = EmailMultiAlternatives(subject, comment, from_email, [cd['to']]) msg.attach_alternative(html_template, 'text/html') msg.send(fail_silently=False) messages.success(request, 'Your email has been sent') return HttpResponseRedirect(reverse('profiles:find_friends')) else: form = EmailInviteForm() template = 'profiles/email_invite.html' context = { 'form': form, } return render(request, template, context) -
django.urls.exceptions.NoReverseMatch: Reverse for 'email-verify' not found. 'email-verify' is not a valid view function or pattern name
Not sure why this error is happening to me, I'm trying to send a verification email to a new registered user. Here is my error: django.urls.exceptions.NoReverseMatch: Reverse for 'email-verify' not found. 'email-verify' is not a valid view function or pattern name. I clearly state the name of the url and link everything up to my understanding. Here is my code: users/urls.py from django.urls import path from .views import CustomUserCreate, VerifyEmail, BlacklistTokenUpdateView app_name = 'users' urlpatterns = [ path('register/', CustomUserCreate.as_view(), name="register"), path('email-verify/', VerifyEmail.as_view(), name="email-verify"), path('logout/blacklist/', BlacklistTokenUpdateView.as_view(), name='blacklist'), ] users/view.py from django.urls import reverse from django.contrib.sites.shortcuts import get_current_site from rest_framework_simplejwt.views import TokenObtainPairView from rest_framework import generics ,status from rest_framework.response import Response from rest_framework.views import APIView from rest_framework_simplejwt.tokens import RefreshToken from rest_framework.permissions import AllowAny from .models import NewUser from .serializers import RegisterSerializer from .utils import ConfirmEmail class CustomUserCreate(generics.GenericAPIView): permission_classes = [AllowAny] serializer_class = RegisterSerializer def post(self, request, format='json'): user = request.data serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() user_data = serializer.data user = NewUser.objects.get(email=user_data['email']) token = RefreshToken.for_user(user).access_token current_site = get_current_site(request).domain relativeLink = reverse('email-verify') #Error starts here absurl = 'http://'+current_site+relativeLink+"?token="+str(token) email_body = 'Hi '+user.username + \ ' Use the link below to verify your email \n' + absurl data = {'email_body': email_body, 'to_email': user.email, 'email_subject': 'Verify … -
How to fix unsupported operand type(s) for +: 'NoneType' and 'str'
I am trying to interate Weazyprint to my project so that I can download order details as a PDF as a Receipt from admin side for my Django E-commerce project, but I am receiving the following error: TypeError at /store/admin/order/3/pdf/ unsupported operand type(s) for +: 'NoneType' and 'str' I have installed pip install weasyprint Here is the views.py: @staff_member_required def admin_order_pdf(request, order_id): order = get_object_or_404(Order,ordered=True, id=order_id) html = render_to_string('store/pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Order.id) weasyprint.HTML(string=html).write_pdf(response, stylesheets=[weasyprint.CSS(settings.STATIC_ROOT+ 'blog/main.css')]) return response Here is the traceback: Traceback (most recent call last): File "C:\Users\Ahmed\Desktop\Project\venv\lib\site-packages\django\core\handle rs\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Ahmed\Desktop\Project\venv\lib\site-packages\django\core\handle rs\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Ahmed\Desktop\Project\venv\lib\site-packages\django\contrib\aut h\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\Ahmed\Desktop\Project\store\views.py", line 593, in admin_order _pdf stylesheets=[weasyprint.CSS(settings.STATIC_ROOT+ 'blog/main.css')]) TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' Here is the settig.py STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Here is the admin.py from import_export.admin import ImportExportActionModelAdmin, ImportExportModelAdmin, ExportMixin def order_pdf(obj): return mark_safe('<a href="{}">PDF</a>'.format(reverse('store:admin_order_pdf', args=[obj.id]))) order_pdf.short_description = 'Order PDF' class OrderAdmin(ExportMixin, admin.ModelAdmin): list_display = ['id', ..... ,order_pdf] My question: What am i doing wrong which is leading to this error? How do I … -
Django DRF: default values in the model are not getting used
I have a model class Sample(model.Models): is_active = BooleanField(default=True) Now i craete a serializer class SampleSerializer(models.Model): class Meta: model = Sample Now trying to save with serializer and expecting it to use default value when not provided data = {} serializer = SampleSerializer(data = data) instance = serializer.save() but i see the value of instance.is_active as False -
django count and filter by the foreign key of foreign key
I'm struggling with getting a QuerySet of incomplete Poll objects in an optimal and fancy way. There is a poll model that has sections, each section has a group of questions. Then the answers have a foreign key to a question. This was modeled that way to allow an admin to create large polls separated into different sections and their questions have different answer types (Text, bool, choice, etc). A poll is considered incomplete if the number of answers is less than the number of questions. How can I get a list (QuerySet) of incomplete Polls of a given user? The simplified model is: class Polls(models.Model): name = models.TextField() active = models.BooleanField() @property def num_questions(self): return Questions.objects.filter(section__poll=self).count() @property def questions(self): """ Returns a Queryset of Questions that can be used to filter questions of this poll regardless how they were split by sections """ sections = Sections.objects.filter(Q(poll=self)) questions = Questions.objects.filter(Q(section__in=sections)) return questions def unanswered_questions_by_user(self, user: User): """ Returns a queryset of Questions that haven't been responded by a given user """ answered_questions = user.answers.filter( question__in=self.questions).values_list('question__pk', flat=True) unanswered_questions = self.questions.exclude(pk__in=answered_questions) return unanswered_questions class Sections(models.Model): name = models.TextField() poll = models.ForeignKey(Poll) class Questions(models.Model): question = models.TextField() section = models.ForeignKey(Section) class Answer(models.Model): user … -
Django REST API and Nuxt.js - (CORS error in Nuxt)
I can access my Django REST api using Postman however when I run it on Nuxt, I get the "has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource." Let me know which parts of my code you would like to see and I will be happy to share. -
Import and modify a .ics calendar file on my own webpage
So I am making a web app for an inventory and the web app needs a calendar which already exists in the form of an outlook calendar. I have managed to import the calendar link as a .html and as a .ics file and I have added the calendar to my website. The problem is modifying the calendar: the website needs me to add 'tags' on the calendar (for bookings made) such that hovering over or clicking on a tag shows booking details. Because the imported calendar is basically an outlook calendar I am unable to implement this. Is there a way to do that? Or perhaps, is there a way for me to make my own calendar on HTML/CSS and then add the .ics file to my own self-designed calendar? Ps: I am using Django, html, CSS for development. Thank you! -
Django get_absolute_url for ManyToManyField
I am trying to set up a site for the url flow to be: states -> county -> storename With ForeignKey between county and state I was able to use get_absolute_url with something like: def get_absolute_url(self): return reverse('county-detail', args=[str(self.states),str(self.county) I am now trying to create my model for storename and am having problems with manytomany relationships. I tried making states and county foreign keys within the model and it works with get_absolute_url. However, storenames can be in multiple states and counties. My current model code is: class StoreName(models.Model): name = models.CharField(max_length=100) county = models.ManyToManyField('county') states = models.ManyToManyField('states') def get_absolute_url(self): return reverse('StoreName-detail', args=[str(self.states),str(self.county),str(self.name)]) I am getting the error: 'Reverse for 'StoreName-detail' with arguments '('ls.states.None', 'ls.country.None', 'Ralphs')' not found' Is there a way to have states and county populate data for the args like it did when they were foreignkeys? -
Django model to automatically update username and date/time when Article modified
I have a model called Post and I am trying to automatically save the username of the logged in user who last modified the article along with the timestamp. So far DateTime timestamp is updating values but I am unable to achieve the same result with the username. class Post(models.Model): article = models.TextField(max_length=2000) username = models.ForeignKey(User, on_delete=models.CASCADE, related_name='usernames') updated_at = models.DateTimeField(auto_now=True) -
How I can all the current user who posses a subdomain using django tenant
I am using django tenant for a sass application. Following are the model configuration. How I can call the present user who owns the current subdomain class Client(TenantMixin): name = models.CharField(max_length=100) paid_until = models.DateField(default=ten_days) on_trial = models.BooleanField(default=True) created_on = models.DateField(auto_now=True) user = models.ForeignKey(User, related_name='clients', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.name class Domain(DomainMixin): pass DomainMixin config is as follows in the package class DomainMixin(models.Model): domain = models.CharField(max_length=253, unique=True, db_index=True) tenant = models.ForeignKey(settings.TENANT_MODEL, db_index=True, related_name='domains', on_delete=models.CASCADE) # Set this to true if this is the primary domain is_primary = models.BooleanField(default=True, db_index=True) settings.TENANT_MODEL is pointing to Client, I tried as follows current_site = Site.objects.get_current() try: current_domain = current_site.domain domain_active = Domain.objects.get(domain=current_domain) user = domain_active.tenant.user print(user) except: pass But not getting output on terminal, somebody can show me the right way -
Django Search Bar Function Not Yielding Results
I have a table that is shown in my django app that I am trying to filter with a search bar. I am not receiving any errors, but whenever I search anything (id, name, etc) no data pops up. search.html: {% extends "polls/stakeholders.html" %} {% block content %} {% for stakeholder in all_search_results %} <h3>{{stakeholder.employee}}</h3> <p>{{stakeholder.description}}</p> {% empty %} <h2>No results found</h2> {% endfor %} {% endblock %} stakeholders.html (table and search bar portion): <form class="form-inline my-2 my-lg-0" method="GET" action="{% url 'polls:search' %}"> <input class="form-control mr-sm-2" type="search" name="search"> <button class="btn btn btn-outline-info my-2 my-sm-0" type="submit"> Search </button> </form> <br> <table class="table table-hover" style="width:90% "> <thead> <tr style="font-family: Graphik Black; font-size: 14px"> <th scope="col">#</th> <th scope="col">Employee</th> <th scope="col">Stakeholder Group</th> <th scope="col">Quadrant</th> <th scope="col">Description</th> </tr> </thead> <tbody> {% for stakeholder in stakeholder_list %} <tr style="font-family: Graphik;font-size: 12px"> <td>{{ stakeholder.id }}</td> <td style="font-size: 15px">{{ stakeholder.employee }}</td> <td>{{ stakeholder.stakeholder_group }}</td> <td>{{ stakeholder.stakeholder_quadrant }}</td> <td>{{ stakeholder.description }}</td> <td><button type="button" class="btn btn-danger btn-sm badge-pill" style="font-size: 11px; width:60px" data-toggle="modal" data-target="#new">Edit</button></td> </tr> {% endfor %} </tbody> </table> urls.py path('results/', views.SearchView.as_view(), name='search'), views.py (currently filters by id, but i've already tried the other fields) class SearchView(ListView): model = Stakeholder template_name = 'polls/search.html' context_object_name = 'all_search_results' def get_queryset(self): result = … -
HTML Containers Going Over the Page
I am relatively new to HTML but am getting a weird result from my django app. I have outlined what I have vs. what I'm looking for below for reference. As you can see by my code, the only places that I have called out a height is in that iframe which is pushing down the rest of the contents outside of container two. Container one is also purposed to extend the entire height of the page (that's just a side bar) and there should be some padding at the bottom of the page after the last container. Any idea why this is happening? HTML <div class="two" style="padding-left: 15px;padding-right: 15px"> <div class="card"> <iframe width="1220" height="1241" src="x" ... > </div> <div class="card"> </div> </div> style.css .container { width: 100%; height: 100%; background: rgb(233, 236, 239); margin: auto; padding: 10px; } .one { width: 15%; background:white; float: left; } .two { margin-left: 15%; background: rgb(233, 236, 239); } Current: Desired: -
Django: Checkbox Onclick Event
I want to make it so that if To be annouced is clicked then the form input for the release date disapears. How can I add an onclick to the checkbox of a form input? Templates: {{form.tba.label}} {{form.tba}} <p>{{form.release_date.label}} (not required)</p> <div class="date_container">{{form.release_date}}</div> forms: tba = forms.BooleanField(label="Release date to be announced", widget=forms.CheckboxInput(attrs={'class': 'form_input_bool'}), required=False) release_date = forms.DateField(widget=forms.SelectDateWidget(attrs={'class': 'form_input_select_date'}, years=YEARS, empty_label="---"), required=False) -
How to configure viewset and router based on existing viewset and router?
I am a newbie in django and am trying to dabble with social website. I have a question. I have a Discussion Viewset class DiscussionViewSet(viewsets.ModelViewSet): # general implementation with urls.py router = DefaultRouter() router.register('discussions', views.DiscussionViewSet) app_name = 'discussion' urlpatterns = [ path('', include(router.urls)) ] So, this generate /discussion/discussions/, /discussion/discussions/2. etc.. Now, I am trying to add a similar "Comment" ViewSet on "Discussion" I am hoping to have the functionality like discussion/discussions/2/comment/ -> post new comment and discussion/discussions/2/comment/1 -> retrieves the comment. and so on.. I found an example here: https://github.com/DK-Nguyen/django-social-network/blob/master/discussion/urls.py but they are using a different way to achieve this but I want to use ViewSet and router to achieve this?