Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
an exception on Route method of Router in python
I created a small road map application and used the Router class from pyrolib3 but when I call the method doRoute(location, destination) I have an error SAXParseException at /"unclose token" -
How to pass comma seperated query parameters to SerializerMethodField - Django Rest Framework
I'm trying to pass comma seperated query parameters to serializer and return SerializerMethodField value in JsonResponse views.py: class MyModelViewSet(ModelViewSet): serializer_class = serializers.MyModelSerializer def get_serializer_context(self): context = {'request': self.request} years = self.request.GET.get("years") if names: context['years'] = "years" return context serializers.py: class MyModelSerializer(ModelSerializer): age = serializers.SerializerMethodField() class Meta: model = models.MyModel fields = ["id","first_name","last_name"] get_age(self): years = years.split(',') qs = list(models.MyModel.objects.filter(year__in=years) /* here I should call function my_func() for each object and return value in json response which looks like this */ [ { "id" : 1, "first_name" : "John", "last_name" : "Doe", "age": 31 } ] but I have no idea how to implement this part of serializer. Any help will be appreciated, thank you in advance! -
Dynamically updating values of a field depending on the choice selected in another field in Django
I have two tables. Inventory and Invoice. InventoryModel: from django.db import models class Inventory(models.Model): product_number = models.IntegerField(primary_key=True) product = models.TextField(max_length=3000, default='', blank=True, null=True) title = models.CharField('Title', max_length=120, default='', blank=True, unique=True) amount = models.IntegerField('Unit Price', default=0, blank=True, null=True) def __str__(self): return self.title InvoiceModel: from django.db import models from inventory.models import Inventory class Invoice(models.Model): invoice_number = models.IntegerField(blank=True, primary_key=True) line_one = models.ForeignKey(Inventory, on_delete=models.CASCADE, related_name='+', verbose_name="Line 1", blank=True, default='', null=True) line_one_quantity = models.IntegerField('Quantity', default=0, blank=True, null=True) line_one_unit_price = models.IntegerField('Unit Price(₹)', default=0, blank=True, null=True) line_one_total_price = models.IntegerField('Line Total(₹)', default=0, blank=True, null=True) line_two = models.ForeignKey(Inventory, on_delete=models.CASCADE, related_name='+', verbose_name="Line 2", blank=True, default='', null=True) line_two_quantity = models.IntegerField('Quantity', default=0, blank=True, null=True) line_two_unit_price = models.IntegerField('Unit Price(₹)', default=0, blank=True, null=True) line_two_total_price = models.IntegerField('Line Total(₹)', default=0, blank=True, null=True) line_three = models.ForeignKey(Inventory, on_delete=models.CASCADE, related_name='+', verbose_name="Line 3", blank=True, default='', null=True) line_three_quantity = models.IntegerField('Quantity', default=0, blank=True, null=True) line_three_unit_price = models.IntegerField('Unit Price(₹)', default=0, blank=True, null=True) line_three_total_price = models.IntegerField('Line Total(₹)', default=0, blank=True, null=True) line_four = models.ForeignKey(Inventory, on_delete=models.CASCADE,related_name='+', verbose_name="Line 4", blank=True, default='', null=True) line_four_quantity = models.IntegerField('Quantity', default=0, blank=True, null=True) line_four_unit_price = models.IntegerField('Unit Price(₹)', default=0, blank=True, null=True) line_four_total_price = models.IntegerField('Line Total(₹)', default=0, blank=True, null=True) line_five = models.ForeignKey(Inventory, on_delete=models.CASCADE, related_name='+', verbose_name="Line 5", blank=True, default='', null=True) line_five_quantity = models.IntegerField('Quantity', default=0, blank=True, null=True) line_five_unit_price = models.IntegerField('Unit Price(₹)', default=0, blank=True, null=True) line_five_total_price = … -
how to specify hourly time range in djagno?
I want to accept orders within specific timeframe, simply i want to validated orders if they are within 8:00-19:00 no matter what day it is or what date it is. -
How to pass django variable as parameter inside {% url %} tag?
Let's say I have a view function like this: def view(request): x = 5 y = 10 context = { 'x': x, 'y': y, } return render(request, 'index.html', context) and a result function like this: def result(request, number): square = int(number) * int(number) return HttpResponse(str(square)) I am passing context from the view function to the index.html template, which looks like this: <body> <h1>{{ str(x) }}</h1> <a href="{% url 'app:result' number=str(y) %}">Square it</a> </body> The template renders x successfully as a header, but I don't know how to pass y as the number parameter in the result view. -
What is the correct way to change html dynamically using django
Suppose we have a login page where, in the first stage, we are asked to enter our email. We send this information to the server, which searches whether there is an account with this email, and if there is, our goal is to change the state of the page, to a page where the user is asked to enter the password for this account. If, on the other hand, there is no account with that email, the state of the page changes to one where the user signs up. And let's say that, for the sake of aesthetics, all this happens using the same url. My question is, what is the correct way to inform the client's page to what stage to go into? Sending the whole html code is an option, but this seems like it will put too much pressure on the server. Is there a cleaner way, that we can send less information, and still be able to have the same result? I am new to django and web dev so please explain thoroughly. -
Object is not iterable in Django while returning objects to API
I'm using Django rest framework and Django to create a website showing events. I'm filtering my existing models in the database and outputting the new objects in a new API. So far I am returning all objects in the database while returning the filtered objects cases this error: TypeError: 'type' object is not iterable. In models.py Here you're seeing that I don't actually filter by date. Instead, I'm testing the code by filtering on status. from django.db import models class EventQuerySet(models.QuerySet): def today(self): return self.filter(status="Publish") class EventManager(models.Manager): def get_queryset(self): return EventQuerySet(self.model, using=self._db) def today(self): return self.get_queryset().today() class Event(models.Model): CATEGORY = ( ('Smiles', 'Smiles'), ('Laughter', 'Laughter'), ('Crazy', 'Crazy'), ('Food', 'Food'), ('Outside', 'Outside'), ) STATUS = ( ('Publish', 'Publish'), ('Draft', 'Draft'), ) title = models.CharField(max_length=200, blank=False) status = models.CharField(max_length=200, null=True, choices=STATUS) startDate = models.DateField(blank=True) endDate = models.DateField(blank=True) link = models.CharField(max_length=200, blank=False) category = models.CharField(max_length=200, null=True, blank=True, choices=CATEGORY) objects = models.Manager() date = EventManager() class Meta: unique_together = ('title', 'link') def __str__(self): return self.title Using python manage.py shell to test the query works and outputs the correct objects. Here is an example of some of the data that I'm getting: <EventQuerySet [<Event: Positivus Festival 2022>, Central European zone stage in equestrian show jumping … -
Django REST framework - additional field in JsonResponse
I've APIView, which should return model's field and one additional field - the value of which is returned by function. class MyView(APIView): def get(self,request): qs = list(MyModel.objects.values('name','last_name')) for q in qs: q['age'] = get_age(1980) return JsonResponse({'results': qs}) What is the better way to return combined - model fields and additional field in response? -
ProgrammingError at column "" does not exist
I added a custom extension to djangos User model and now I'm getting this error: return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: column users_account.birthday does not exist LINE 1: ... "users_account"."id", "users_account"."user_id", "users_acc... ^ It only appears when I try to either edit an existing User or create a new one. models.py: class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birthday = models.DateTimeField(blank=True, null=True) def __str__(self): return self.user admin.py: class AccountInline(admin.StackedInline): model = Account can_delete = False verbose_name_plural = 'Accounts' class CustomUserAdmin(UserAdmin): inlines = (AccountInline,) admin.site.unregister(User) admin.site.register(User, CustomUserAdmin) My original guess was the error was due to the fact that my existing Users have no birthday but that doesn't explain why I can't create a new User. Which makes me think I am unaware of what the actual problem is. I'm newish to django/SQl so I don't really understand the error itself. Any help what be greatly appreciated. -
Getting error when trying to log into admin page using django
I am trying to log into the admin page on django. I have a superuser account but when I try to login I get this error: ('42S02', "[42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name 'django_session'. -
Джанго форма "Выбор" [closed]
Я хочу сделать форму select с выбором страны, но не знаю, как засунуть options в select средствами django. В документациях искал, но в основном была не та информация или было не понятно, по итогу я не нашел. Я хочу сделать форму select с выбором страны, но не знаю, как засунуть options в select средствами django. В документациях искал, но в основном была не та информация или было не понятно, по итогу я не нашел Нужно, чтобы в пуcтом месте были options Код страницы: <html> <head> <meta charset="UTF-8"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384- 0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous"> </head> <body> <div class="col-md-7 col-lg-8 container"> <h4 class="mb-4 mt-4" style="text-align: center">Заполните форму</h4> <form class="needs-validation m-auto" novalidate="" method="post"> {% csrf_token %} <div class="row g-3"> <div class="col-sm-6"> <label for="country" class="form-label">Страна</label> {{ form.country }} </select> <div class="invalid-feedback"> Please select a valid country. </div> </div> <div class="col-sm-6"> <label for="lastName" class="form-label">Место</label> {{ form.title }} <div class="invalid-feedback"> Valid place is required. </div> </div> <div class="col-12"> <label class="form-label">Описание <span class="text-muted">(Optional)</span></label> {{ form.task }} <div class="invalid-feedback"> Please enter a valid email address for shipping updates. </div> </div> <hr class="my-4"> <button class="w-100 btn btn-primary btn-lg container" type="submit" >Continue to checkout</button> </form> </div> Код forms.py: from django import forms from django.forms import models, Textarea, TextInput, Select, SelectMultiple … -
Email not sending probably because of my service provider
I am searching if there is possibly a way to solve this problem. SMTPConnectError at /accounts/signup/ (421, b'Service not available') This error occurs when I use my home wifi during development, I know for the fact that it's the WiFi because connecting to another internet source solves this particular problem. Is there a work around this? Because I am in a situation where the only internet connectivity I have is this router and this happens with django/python development. -
How do I serve media files in Django DRF testing using APILiveServerTestCase?
I have some Django DRF tests that look like this: from django.conf import settings from rest_framework.test import APILiveServerTestCase, RequestsClient class APITests(APILiveServerTestCase): def setUp(self): self.client = RequestsClient() def test_endpoints(self): with self.settings(MEDIA_ROOT=f"{settings.BASE_DIR}/test_media/"): # Upload file self.client.post( URL, files={"my_file": ("filename", b"abc")}, ) # Download the file we just uploaded response = self.client.get( URL_to_FILE, ) The upload works fine, but the download fails with a 404, because the test webserver isn't serving media files, and more specifically, not serving them from my custom MEDIA_ROOT=f{settings.BASE_DIR}/test_media/ folder. Adding entries to urls.py to have Django serve media files didn't work. Django appears to have a TestCase subclass specifically designed for this: django.contrib.staticfiles.testing.StaticLiveServerTestCase. DRF doesn't have anything like this, but I figured I could make one like this: from django.contrib.staticfiles.testing import StaticLiveServerTestCase from rest_framework.test import APIClient class APIStaticLiveServerTestCase(StaticLiveServerTestCase): client_class = APIClient class APITests(APIStaticLiveServerTestCase): .... This didn't work either. Is there a way to make this work? -
unit testing for celery periodic task
I have a celery periodic task implemented to send email to users on certain date set on the model,How can i write the unit test for the following celery task. @app.task(bind=True) def send_email(self): send_date = timezone.now() records = Model.object.filter(due_date=send_date) for record in records: template_data = { 'homepage_url': settings.WWW_ROOT, 'domain_name': settings.DOMAIN_NAME, 'inq': record.inq, 'task_name': record.name, 'task_created': record.created, 'date': record.send_date, } user_emails = [] if record.send_email_to_users: **Boolean Flag on model** assignees_emails = [] for user in record.users.all(): user_emails.append(user.email) send_email_function( subject_template_path='', body_template_path='', template_data=template_data, to_email_list=user_emails, fail_silently=False, content_subtype='html' ) -
Preciso trazer as informações do banco de dados para o index.html
Preciso trazer as informações do banco de dados e rendereizar na pagina index.html apresenta o seguinte erro. (env) PS E:\crudpython> & e:/crudpython/env/Scripts/python.exe e:/crudpython/core/views.py Traceback (most recent call last): File "e:\crudpython\core\views.py", line 2, in from .models import Produto ImportError: attempted relative import with no known parent package (env) PS E:\crudpython> enter image description here -
How to filter by author in Django? Getting error: Field 'id' expected a number
I have a Django application that functions like a diary, where the homepage is an index list of all diary entries previously created. I am now trying to filter the index so that the user will only see the diary entries that they have created. Here is what I have done: Views.py from django.shortcuts import render from .models import DiaryEntry from django.views import generic from django.views.generic.edit import CreateView def index(request): """View function for MyDiary.""" author = DiaryEntry.author diary_entry = DiaryEntry.objects.filter(author=author).order_by('-created_on') context = { "diary_entry": diary_entry, } return render(request, 'diary_index.html', context=context) class EntryDetailView(generic.DetailView): model = DiaryEntry def get_data(self, **kwargs): context = super(EntryDetailView, self).get_data(**kwargs) return context class EntryCreate(CreateView): model = DiaryEntry fields = ['title', 'content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) Models.py from django.db import models from django.urls import reverse from django.conf import settings User = settings.AUTH_USER_MODEL class DiaryEntry(models.Model): title = models.CharField(max_length=255) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, on_delete = models.CASCADE ) def __str__(self): """String for representing the diary object.""" return self.title def get_absolute_url(self): """Returns the url to access a detail record for this user entry.""" return reverse('entry-detail', args=[str(self.id)]) HTML: {% extends "base.html" %} {% block page_content %} <div class="col-md-8 offset-md-2"> <h1>This is your diary!</h1> <hr> <h2>Here, … -
Unable to connect browser to any of my docker images
I downloaded cookiecutter django to start a new project the other day. I spun it up (along with postgres, redis, etc) inside docker containers. The configuration files should be fine because they were all generated by coockicutter. However, once I build and turn on the containers I am unable to see the "hello world" splash page when I connect to my localhost:8000. But there is something going wrong between the applications and the containers because I am able to connect to them via telnet and through docker exec -it commands etc. The only thing I can think of is some sort of permissions issue? So I gave all the files/directors 777 permissions to test that but that hasnt changed anything. logs % docker compose -f local.yml up [+] Running 8/0 ⠿ Container dashboard_local_docs Created 0.0s ⠿ Container dashboard_local_redis Created 0.0s ⠿ Container dashboard_local_mailhog Created 0.0s ⠿ Container dashboard_local_postgres Created 0.0s ⠿ Container dashboard_local_django Created 0.0s ⠿ Container dashboard_local_celeryworker Created 0.0s ⠿ Container dashboard_local_celerybeat Created 0.0s ⠿ Container dashboard_local_flower Created 0.0s Attaching to dashboard_local_celerybeat, dashboard_local_celeryworker, dashboard_local_django, dashboard_local_docs, dashboard_local_flower, dashboard_local_mailhog, dashboard_local_postgres, dashboard_local_redis dashboard_local_postgres | dashboard_local_postgres | PostgreSQL Database directory appears to contain a database; Skipping initialization dashboard_local_postgres | dashboard_local_postgres | 2022-07-07 14:36:15.969 … -
Call a function in DetailView, views.py. which returns bool. Django, python
I am building an e-commerce website with django. There is a homepage which lists all items on website and when the user click on any of those items they will direct to details page which shows details about that item. Also on that detail page, I added a "wishlist" button so that users can add that item to their wishlist. My problem is, if the user does not have that item in their wishlist, I want to display "Add to wishlist" button to add that item to their wishlist when they clicked on it, otherwise I want to display "remove from wishlist" button to remove the item from their wishlist when they clicked on it. I have two separate function to add and remove items and they perfectly work but I want to display only one of the buttons "add" or "remove" by checking if that item exists in their wishlist or not. So my logic was writing a function checks if the user has that item in their wishlist or not in DetailView which displays the "detail" page in views.py and display only one of them but I couldn't. This is views.py class ItemDetailView(FormMixin, DetailView): model = Auction form_class … -
Django - TailwindCSS won't load some attributes
I'm having issues when it comes to using some attributes with Django and TailwindCSS. Let's take this table for example: <div class="relative overflow-x-auto shadow-md sm:rounded-lg"> <table class="w-full text-lg text-left text-gray-500 rounded-2xl mt-4 dark:text-gray-400"> <thead class="rounded-2xl text-lg text-white uppercase bg-[#68BA9E] dark:bg-gray-700 dark:text-gray-400"> <tr> <th scope="col" class="px-6 py-3"> Report title </th> <th scope="col" class="px-6 py-3"> Company </th> <th scope="col" class="px-6 py-3"> Brand (if any) </th> <th scope="col" class="px-6 py-3"> Go to report </th> </tr> </thead> <tbody> {% for report in reports %} <tr class="bg-white border-b text-center dark:bg-gray-800 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-600"> <th scope="row" class="h-19 px-6 py-4 font-medium text-gray-900 dark:text-white whitespace-nowrap"> {{ report.title }} </th> <td class="px-6 py-4"> {{ report.company }} </td> <td class="px-6 py-4"> {% if report.brand %} {{ report.brand }} {% else %} - {% endif %} </td> <td class="px-6 py-4"> <a href="{% url 'tool:single-report' slug=report.slug %}">Access</a> </td> </tr> {% endfor %} </tbody> </table> </div> Gives the following: But when I try to change the bg-color from: <thead class="rounded-2xl text-lg text-white uppercase bg-[#68BA9E] dark:bg-gray-700 dark:text-gray-400"> To: <thead class="rounded-2xl text-lg text-white uppercase bg-red-700 dark:bg-gray-700 dark:text-gray-400"> The new color won't load. It gives: I don't understand why I'm getting nothing. In my configuration, following tasks are running: The server is running with python manage.py … -
How to use multiple models in django class based generic list view
Here, my code for models.py file, from django.db import models from config.g_model import TimeStampMixin # Create your models here. class Variant(TimeStampMixin): title = models.CharField(max_length=40, unique=True) description = models.TextField() active = models.BooleanField(default=True) class Product(TimeStampMixin): title = models.CharField(max_length=255) sku = models.SlugField(max_length=255, unique=True) description = models.TextField() class ProductImage(TimeStampMixin): product = models.ForeignKey(Product, on_delete=models.CASCADE) file_path = models.URLField() class ProductVariant(TimeStampMixin): variant_title = models.CharField(max_length=255) variant = models.ForeignKey(Variant, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) class ProductVariantPrice(TimeStampMixin): product_variant_one = models.ForeignKey(ProductVariant, on_delete=models.CASCADE, null=True, related_name='product_variant_one') product_variant_two = models.ForeignKey(ProductVariant, on_delete=models.CASCADE, null=True, related_name='product_variant_two') product_variant_three = models.ForeignKey(ProductVariant, on_delete=models.CASCADE,null=True, related_name='product_variant_three') price = models.FloatField() stock = models.FloatField() product = models.ForeignKey(Product, on_delete=models.CASCADE) now here I am using this class based list view, class ProductListView(generic.ListView): model = Product template_name = 'products/list.html' context_object_name = 'products' paginate_by = 2 def get_context_data(self, **kwargs): context = super(ProductListView, self).get_context_data(**kwargs) products = self.get_queryset() page = self.request.GET.get('page') paginator = Paginator(products, self.paginate_by) try: products = paginator.page(page) except PageNotAnInteger: products = paginator.page(1) except EmptyPage: products = paginator.page(paginator.num_pages) context['products'] = products return context I want to use productimage,product variant and product variant price in my template,I don't know actually how to use multiple models on this view ,if anyoneone can suggesst me it will be helpful -
django website that add name of uer on greeting image , how to refuse None names and how refuse accsess to "/pic" page?
I'm trying to make a django website that take name of user and add it to greeting picture now I'm using return return FileResponse(i_mg) to show picture with name of user in another page that name pic.html but i found its doesn't useful because everyone can accesses to the page direct and the website will show name is None how can i use a unique URL for every user and refuse None name ? this my views.py from django.shortcuts import render from .models import Name from django.shortcuts import redirect from PIL import Image,ImageDraw , ImageFont from django.http import FileResponse,HttpResponse # Create your views here. def Home(request): return render(request , 'index.html') def Show(request): name_input = str(request.POST.get('user_name')) img = Image.open("C:\\Users\\kmm\\Desktop\\my_django_stuff\\Eid_G\\files\\covers\\mypic.png") d = ImageDraw.Draw(img) fnt = ImageFont.truetype('C:\\Users\\kmm\\Desktop\\fonts\\static\Cairo-Bold.ttf',40) message = name_input d.text((540,1020),message, font=fnt, fill=(237, 185, 117),anchor="ms") img.save('Images/'+name_input+'.png') save_in_model = Name(massenger_name=name_input,image=name_input+'.png') save_in_model.save() i_mg = open('Images/'+name_input+'.png','rb') if name_input is None: return redirect(Home) else: return FileResponse(i_mg) this my urls.py from django.contrib import admin from django.urls import path from Eid_Post import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('',views.Home), path('pic',views.Show) ] urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) this my index.html <!DOCTYPE html> <html lang="en" dir="rtl"> <head> <meta charset="utf-8"> <title></title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous"> … -
Django Rest Framework: ordering lost when try to return get_queryset() in get method of modelviewset
in get_queryset I'm able to get the list of candidates in a order that i want but when i return it, then in the API response I'm seeing it in a different order serilizer.py class CandidateListSerializer(serializers.ModelSerializer): """ Candidate serializer """ job_skill_detail = serializers.SerializerMethodField(read_only=True) job_role_detail = serializers.SerializerMethodField(read_only=True) primary_skills_detail = serializers.SerializerMethodField(read_only=True) def get_job_skill_detail(self, obj): if obj.job_skill: return obj.job_skill.name def get_job_role_detail(self, obj): if obj.job_role: return obj.job_role.name def get_primary_skills_detail(self, obj): return obj.primary_skills.all().values( "id", "name", ) class Meta: model = Candidate fields = "__all__" my view.py get_queryset function in modelviewset api def get_queryset(self): if "Admin" in self.request.user.role or "Recruiter" in self.request.user.role: return self.queryset if "Client" in self.request.user.role: candidates_source_to_client = CandidateSubmission.objects.filter(company=self.request.user.company).values_list('candidate', flat=True) print(f"Candidates id from candidate submission model: {candidates_source_to_client}") candidates = self.queryset.filter( Q( band__in=CompanyBands.objects.filter( company=self.request.user.company ).values_list("band", flat=True) ) | Q(id__in=candidates_source_to_client) ) print(f"candidates from database with cliend company and company band: {candidates}") candidates_final = candidates.annotate( relevancy=Count(Case(When(id__in=candidates_source_to_client, then=1))) ).order_by("-relevancy") print(f"final candidates list: {candidates_final}") return candidates_final my print response from the final candidate list I'm getting final candidates list: <QuerySet [<Candidate: Amresh Giri>, <Candidate: Dishita Vishwakarma>, <Candidate: Rhaan Kumaad 2>, <Candidate: Raan Kaad>, <Candidate: Vigneshkumar Chinnadurai>, <Candidate: Rhan Kumad>, <Candidate: Apurva Dhakre>, <Candidate: Saiba Kumar>, <Candidate: Ramona>] This is the order that I want but am not able to … -
Changing style color via JavaScript isn't working
I have been trying to change the style color of an input field when a certain option is selected but it is not working. I have tried both onclick and oninput but to no avail. I suspect the issue lies with {{ type }} or == 'Buy'. function changeColor () { var transaction_type = document.getElementById('buysell'); var option_user_selection = transaction_type.options[ transaction_type.selectedIndex ].text; if (option_user_selection == 'Buy') { document.getElementById('costb').style.color = '#006400'; } else { document.getElementById('costb').style.color = '#DC143C'; } } <div class="transaction_type"> <p>Transaction Type:</p> <select style="font-size:16px" class="form-select" id='buysell' required> {% for type in form.transaction_type %} <option>{{ type }}</option> {% endfor %} </select> </div> forms.py transaction_choices = [ ('BUY', 'Buy'), ('SELL', 'Sell'), ] transaction_type = forms.CharField( max_length=4, widget=forms.Select( choices=transaction_choices, attrs={ 'class': 'form-select', 'name': 'transaction_type', 'id': 'floatingTransaction', 'oninput': 'changeColor();' }) ) cost_basis = forms.DecimalField( min_value = 0, widget = forms.NumberInput(attrs={ 'class': 'form-control', 'name': 'cost_basis', 'id': 'costb', }) ) -
Not able to Proxy Apache properly
I use a Django application. I want to access it via Apache. So, I've made DEBUG=False and tried to proxy ProxyPass "/" "http://localhost:8000/" So it routes to my application. Only problem is.. the static files don't load with this method. Therefore, I tried to put static folder in /var/www/html/static In console, this is where all the calls are going but they still don't load. This is my config file There must be something i'm missing or do not understand. Can someone please enlighten with some explanation! -
Django: there is no unique constraint matching given keys
I created an extension of the standard user model in models.py called Client. I added a manytomany relationship to it to indicate which clients are related to another: class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) clients = models.ManyToManyField("self", blank=True) This works perfectly fine in my local dev environment where I use python manage.py runserver. However, when I try to run python manage.py migrate on our testing server using a postgresql database, I get the following error: psycopg2.errors.InvalidForeignKey: there is no unique constraint matching given keys for referenced table "content_client" What am I missing here?