Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Integration of Django-PayPal subscription based payment system
I am trying to implement a Subscription-based payment method in Django. I have tried to Integrate the subscription-based button as per the PayPal guidlines. Screenshot is attached for same. But after clicking on either button screen is blank, and nothing happens, screenshot is attached for the same. Here is my code for button integration. <div id="paypal-button-container-P-789654"></div> <script src="https://www.paypal.com/sdk/js?client-id=123456&vault=true&intent=subscription" data-sdk-integration-source="button-factory"></script> <script> paypal.Buttons({ style: { shape: 'pill', color: 'blue', layout: 'vertical', label: 'subscribe' }, createSubscription: function(data, actions) { return actions.subscription.create({ /* Creates the subscription */ plan_id: 'P-789654' }); }, onApprove: function(data, actions) { alert(data.subscriptionID); // You can add optional success message for the subscriber here } }).render('#paypal-button-container-P-789654'); // Renders the PayPal button </script> -
Django: starting server using a specific database out of multiple databases
I am trying to set up 2 databases in django. The second database is meant for testing purposes, so the 2 databases practically have the same models. My question is how to start the server using the second database. The steps I did for setting up the databases: I created a second app called 'testing', so now in my project root folder there is the app api (the real one) and testing (the app meant for the test database). Afterwards, added the same models from api/models.py to testing/models.py Created router for the first database and the second database: class AuthRouter: route_app_labels = {'auth', 'contenttypes', 'admin', 'sessions'} def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'default' return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'default' return None def allow_migrate(self, db, app_label, model_name = None, **hints): if app_label in self.route_app_labels: return db=='default' return None def allow_relation(self, obj1, obj2, **hints): if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None class SpotTesting: route_app_labels = {'spot_testing'} def db_for_read(self, model, **hints): if model._meta.app_label == "spot_testing": return 'test_db' return None def db_for_write(self, model, **hints): if model._meta.app_label == "spot_testing": return 'test_db' return None def allow_relation(self, obj1, obj2, **hints): """ … -
Forbidden (403) CSRF verification failed - Error with Docker, Django and Nginx
I am new to docker. Starting from a Django project (Django 4.0), I am using Docker to side by side with Nginx. I used a docker-compose.yml file and used a custom configuration of Nginx, and everything works. Only when I go to the login screen and click the "Login" button it comes up "Forbidden (403) CSRF verification failed. Request aborted.". The code inside login.html is like this <form method="post">{% csrf_token %} {{ form|crispy }} <button class="btn btn-success ml-2" type="submit">Log In</button> Thanks in advance! -
how to fix roll up error while building vue apps?
i want to deploy simple personal website using vue but when i try to npm run build this error come up help me please... i try deleting the image but onother similiar error come's up error during build: RollupError: Could not resolve "../img/react%202.png" from "src/component/avatarmenu.vue" at error (file:///C:/Users/adity/OneDrive/Documents/LATIHAN/personal-w-vue/node_modules/rollup/dist/es/shared/rollup.js:2041:30) at ModuleLoader.handleInvalidResolvedId (file:///C:/Users/adity/OneDrive/Documents/LATIHAN/personal-w-vue/node_modules/rollup/dist/es/shared/rollup.js:23137 :24) at file:///C:/Users/adity/OneDrive/Documents/LATIHAN/personal-w-vue/node_modules/rollup/dist/es/shared/rollup.js:23099:26 -
Django app not able to find database engine when engine is specified
I have tried everything I can think of to run my initial migrations and get my django app up. I am currently getting this error: Traceback (most recent call last): File "manage.py", line 24, in <module> execute_from_command_line(sys.argv) File "/usr/lib/python3/dist-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/lib/python3/dist-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/python3/dist-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/lib/python3/dist-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/usr/lib/python3/dist-packages/django/core/management/commands/dbshell.py", line 22, in handle connection.client.runshell() File "/usr/lib/python3/dist-packages/django/db/backends/dummy/base.py", line 20, in complain raise ImproperlyConfigured("settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. But this is the DATABASES var in my settings.py file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } The db.sqlite3 file is at the location specified in the 'NAME' key. The app folder is in a subdirectory and uniquely named. The BASE_DIR var is constructed correctly and not causing the location string in the NAME key to be malformed. The models.py file is in the /app folder subdirectory. I am completely out of ideas on how to get this to work and considering giving up on making this project altogether. Please help. … -
Use HTML-template from other app, in same project (Django)
I have a project wich contains two apps User and Accounting. Since all of their HTML-templates should extend from the same base.html template, I made a third app called Shared, and my accounting/base.html and user/base.html would then extend from shared/base.html like {% extends "shared/base.html" %} {% block content %} <div>Hello world</div> {% endblock content %} but that does not work, since Django looks in <app>/templates/shared/base.html. Can this be done without having to just duplicate base.html and have the same file in Accounting and User? -
I have an error in django template for loop
I have an error in django template for loop. My code: <div class="form-group col-md-4 form-field"> <label>Year</label> <select name="year" id="year" name="year"> {% for y in range(1980, (datetime.datetime.now().year + 1)) %} <option value="{{ y }}">{{ y }}</option> {% endfor %} </select> </div> My error: 'for' statements should use the format 'for x in y': for x in y range(1980, (datetime.datetime.now().year + 1)) Please help me to resolve this issue. Please help me to resolve this issue. Please help me to resolve this issue. -
update value certain time later using django appscheduler
I want to update a value every day at a certain time later. I wrote my models and views look like models.py class InvestmentRequest(models.Model): user = models.OneToOneField(User, related_name=“investment_request”, on_delete=models.CASCADE) profit = models.DecimalField(max_digits=15, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.user.username}-{self.amount}" def increase_balance(self, profit ): self.profit += decimal.Decimal(profit ) self.save() def save(self, *args, **kwargs): super().save(*args, **kwargs) views.py scheduler = BackgroundScheduler() job = None def tick(): print(‘One tick!’) # roi_profit() --- any way like this def start_job(): global job job = scheduler.add_job(tick, 'interval', seconds=3) try: scheduler.start() except: pass I used here “appscheduler” library because my requirement is minimal, it’s not a complex configuration like celery. Is there any way to run ‘roi_profit’ views at a certain time every day? Here ‘tick’ function runs very smoothly because it is a normal function. But I can’t call the views function because it’s a required request. And without request, I can’t get any value from request.user. It’s necessary. So this way how I can update my model value at a certain time later every day. Over a couple of days I’m struggling with it but couldn’t find the exact solution. Any suggestions will be appreciated. Thanks. -
Why is my create button not redirecting to the form? (For django)
I am new to Django and am trying to make an online journal, and the server runs fine, but when I press the create button, it does not redirect to the form even though a POST request is being sent. screenshot of the create page. I'm not sure why. This is the code: views.py: from django.shortcuts import render, redirect, get_object_or_404 from ejournal.models import Journal from ejournal.forms import JournalForm def make_entry(request): if request.method == "POST": entry = JournalForm(request.POST, request.FILES) if entry.is_valid(): entry.save() return redirect('list_journals') else: entry = JournalForm() context = { 'entry':entry } return render(request, 'ejournal/create.html', context) def delete_entry(request, id): entry = get_object_or_404(Journal, id=id) if request.method == "POST": entry.delete() return redirect('list_journals') context = { 'object':object } return render(request, 'journal/delete.html',context) def list_journals(request): entries = Journal.objects.all() context = { 'entries': entries } return render(request, 'ejournal/list_journals.html',context) def journal_detail(request, id): journal = Journal.objects.get(id=id) context = { 'journal':journal } return render(request, 'journal/journal_detail.html', context) forms.py from ejournal.models import Journal from django.forms import ModelForm class JournalForm(ModelForm): class Meta: model = Journal fields = ['name','title','text','image'] models.py from django.db import models class Journal(models.Model): name = models.CharField(max_length=20) title = models.CharField(max_length=50) text = models.TextField(max_length=1000) date = models.DateField(auto_now_add=True) image = models.FileField(upload_to='') archived = models.BooleanField(default=False) def __str__(self): return self.name base.html {% load static %}<!DOCTYPE … -
Python, Django, HTMX, is it possible to save data, when a user clicks <button>
When a user click <button> on index page, can save data immediately? views.py def index(request): ... ... context = { ... } response = render(request, 'docu/index.html', context) ### Save visitors' IP and Keywords to KeyLOG table ### ip = request.META.get('REMOTE_ADDR') keywords = request.META.get('HTTP_REFERER', '') keylog = KeylogForm(request.GET) keylog = keylog.save(commit=False) keylog.ipaddr = ip keylog.keyquery = keywords keylog.svae() return response def keylog(request): if request.method == "GET": keylog_list = list(Keylog.objects.all().order_by()\ .values('idpaddr', 'keywords', 'tel_log', 'regtime')) return JsonResponse(keylog_list, safe=False) return JsonResponse({'message':'error'}) forms.py class KeylogForm(forms.ModelForm): class Meta: model = Keylog fields = ['ipaddr','keyquery','tel_log'] models.py class Keylog(models.Model): ipaddr = models.CharField(max_length=32,null=True, blank=True) #save IP addr keyquery = models.CharField(max_length=128,null=True, blank=True) #save keywords tel_log = models.CharField(max_length=256,null=True, blank=True) #save tel_log regtime = models.DateTimeField(auto_now_add=True) #created time Currently, it makes table as below; Ipaddr keyquery tel_log regtime 192.168.x.yy ?query=apple 2023.01.01.12.24.56 192.168.a.bb ?query=banana 2023.01.01.11.22.33 I hope to save Tel_log data in the above table, when a user clicks <butto>...</button>. So I made an index.html as below; index.html <div id="tel_log"> <button class="btn btn-danger"> hx-get="keylog/" hx-vals="[tel_log='CALL']" hx-trigger="click"> Phone NUMBER </button> </div> My expectation is that when I clicked [Phone NUMBER] on the index page, "CALL" is appeared on the "tel_log" column of the above table, but it didn't work, just shows {message:error} I'm a newbie … -
Getting error in Django Custom user model treating every created user as staff user why?
This is my code for Custom user model in Django app i want to make a ecommerce app but when i am creating a superuser in terminal and using that for login insted of making a super user the admin console is treating every account as staff account and even correct email and password is not working? can any one help from django.db import models from django.contrib.auth.models import AbstractBaseUser,BaseUserManager # Create your models here class MyAccountManager(BaseUserManager): def create_user(self,first_name,last_name,username,email,password=None): if not email: raise ValueError('User must have an email address') if not username: raise ValueError('User must have an username') user = self.model( email=self.normalize_email(email), username = username, first_name = first_name, last_name = last_name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,first_name,last_name,email,username,password): user = self.create_user( email=self.normalize_email(email), username = username, first_name = first_name, last_name = last_name, ) user.is_admin = True user.is_active = True user.is_staff = True user.is_superadmin = True user.save(using=self._db) return user class Account(AbstractBaseUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) username = models.CharField(max_length=50,unique=True) email = models.EmailField(max_length=100, unique=True) phone_number = models.CharField(max_length=50) #required date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_superadmin = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username','first_name','last_name'] objects = MyAccountManager() def __str__(self): return self.email def has_perm(self, perm,obj=None): return … -
Django Form with ForeignKey field NOT NULL constraint failed Error
Each model is chain-linked to the previous model. I make one form to fill in, since all the models are linked. When I try to link a model address to a project, an error appears NOT NULL constraint failed: crm_project.address_id /crm/views.py, line 39, in add_project form_project.save() Models class City(models.Model): obl = models.CharField(max_length=255, choices=REGIONS, default="24", verbose_name="Регион") name = models.CharField(max_length=128, verbose_name="Город") population = models.IntegerField() def __str__(self): return self.name class Address(models.Model): city = models.ForeignKey(City, on_delete=models.PROTECT, verbose_name="Город") street = models.CharField(max_length=255, verbose_name="Улица") numb = models.CharField(max_length=64, verbose_name="Номер дома") def __str__(self): return f"{self.street}, {self.numb}" class Project(models.Model): manager = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name="Сотрудник") address = models.ForeignKey(Address, on_delete=models.PROTECT, verbose_name="Адрес") # another fields class ProjectDetail(models.Model): project = models.OneToOneField(Project, on_delete=models.CASCADE, verbose_name="Проект") # another fields Forms class AddressForm(forms.ModelForm): class Meta: model = Address fields = ["city", "street", "numb"] def __init__(self, *args, **kwargs): city = kwargs.pop("city", "") super(AddressForm, self).__init__(*args, **kwargs) self.fields["city"] = forms.ModelChoiceField(queryset=City.objects.all()) class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ["file", "sq", "rent_tax"] class ProjectDetailForm(forms.ModelForm): class Meta: model = ProjectDetail exclude = ['project', 'comment', 'resume', 'complite', 'created_at'] Views def add_project(request): form_address = AddressForm(request.POST or None) form_project = ProjectForm(request.POST or None) form_detail = ProjectDetailForm(request.POST or None) if request.method == 'POST': if form_address.is_valid() and form_project.is_valid() and form_detail.is_valid(): address = form_address.save(commit=False) form_project.manager = request.user form_project.address … -
Django Variable Re-evaluation in Template
So let's say in my template, I use: <td> {{ model1.column1.column11.code1 }} </td> <td> {{ model1.column1.column11.code2 }} </td> <td> {{ model1.column1.column11.code3 }} </td> <td> {{ model1.column1.column11.code4 }} </td> <td> {{ model1.column1.column11.code5 }} </td> <td> {{ model1.column1.column11.code6 }} </td> <td> {{ model1.column1.column11.code7 }} </td> and for comparison: {% with col=model1.column1.column11 %} <td> {{ col.code1 }} </td> <td> {{ col.code2 }} </td> <td> {{ col.code3 }} </td> <td> {{ col.code4 }} </td> <td> {{ col.code5 }} </td> <td> {{ col.code6 }} </td> <td> {{ col.code7 }} </td> {% endwith %} My questions are: For the first code, does it imply that the model1.column1.column11 will be queried by Django 7 times? For the second code, will the usage of with col=model1.column1.column11 can make the template rendering faster, as the query of model1.column1.column11 is only once from the {% with %} block, and just get the variables from the col? Are there any alternatives to both these approaches? Currently, my SQL table consists of less than 1000 rows so any performance issues may not be seen. But, my concern is when the SQL table is large enough and will require many optimization on the query. -
FieldError: Unsupported lookup 'iexact' for EncryptedCharField or join on the field not permitted, perhaps you meant iexact or exact?
class UserDataIdModel(models.Model): user_id = encrypt(models.CharField(default=user_pk, primary_key=True, max_length=255, unique=True)) name = encrypt(models.CharField(max_length=100)) email = encrypt(models.EmailField(max_length=100)) phone = encrypt(models.CharField(max_length=100)) dob = encrypt(models.DateField()) created_dt = models.DateTimeField(auto_now_add=True) def data_delete(request, id): print('id:------------->', id) model_obj = UserDataIdModel.objects.get(user_id__iexact=id) print(model_obj) model_obj.delete() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) How to delete or get Records when data is EncryptedCharField.... -
problem in form not show in templates - django
problem in form not show django don't show form in template I applied everything in the Django tutorial, but foam does not appear, but I did not know the reason despite my research add_book.html {% extends 'base.html' %} {% block content %} <h1>add book </h1> <form method="post"> {% csrf_token %} <hr> {{form}} <hr> <a href="" type="submit">submit</a> </form> {% endblock content %} in forms from django import forms from .models import book class book_form(forms.Form): class meta: model = book fields = '__all__' in views from .models import * from .forms import book_form def addbook(request): bookform = book_form() context = {'form' : bookform} return render(request, 'add_book.html', context) in url path('book/add', views.addbook, name="addbook"), -
Login doesn't work for an ordinary user in Django DRF
I added the ordinary user through admin app but when i try to login to the site nothing happens. Maybe there is something wrong with my custom user model. Or it maybe something else? The custom user models' Models.py: from django.db import models from django.contrib.auth import models as auth_models class UserManager(auth_models.BaseUserManager): def create_user( self, first_name: str, last_name: str, email: str, password: str = None, is_staff=False, is_superuser=False, ) -> "User": if not email: raise ValueError("User must have an email") if not first_name: raise ValueError("User must have a first name") if not last_name: raise ValueError("User must have a last name") user = self.model(email=self.normalize_email(email)) user.first_name = first_name user.last_name = last_name user.set_password(password) user.is_active = True user.is_staff = is_staff user.is_superuser = is_superuser user.save() return user def create_superuser( self, first_name: str, last_name: str, email: str, password: str ) -> "User": user = self.create_user( first_name=first_name, last_name=last_name, email=email, password=password, is_staff=True, is_superuser=True, ) user.save() return user class User(auth_models.AbstractUser): first_name = models.CharField(verbose_name="First Name", max_length=255) last_name = models.CharField(verbose_name="Last Name", max_length=255) email = models.CharField(verbose_name="Email or Phone Number", max_length=255, unique=True) password = models.CharField(max_length=255) username = None objects = UserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name"] Admin.py: rom django.contrib import admin from . import models class UserAdmin(admin.ModelAdmin): list_display = ("id", "first_name", "last_name", "email") … -
how to solve the problem of DataTables warning: table id=table_detail - Requested unknown parameter 'admin' for row 0, column 0
Django html Error Result Please kindly help me to fix it. I want to put the JSON data into datatables. -
some parts of my form is rendering correctly but some arent Django
I am creating a ticket app in my django project. When I create a ticket and submit, parts of the form render correctly in the frontend except three fields. These are the ticket.name, category.name and ticket.description, in the frontend these fields display as 'None' but everything else renders as its supposed to in the frontend. I also checked my admin page and i see that neither the Ticket nor the Category get created properly. I'm not quite sure how to proceed. Here's what i have so far models.py class Category(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name or '' class Ticket(models.Model): STATUS = ( (True, 'Open'), (False, 'Closed') ) PRIORITIES = ( ('None', 'None'), ('Low', 'Low'), ('Medium', 'Medium'), ('High', 'High') ) TYPE = ( ('Misc', 'Misc'), ('Bug', 'Bug'), ('Help Needed', 'Help Needed'), ('Concern', 'Concern'), ('Question', 'Question') ) host = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True, related_name='host') category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='category') name = models.CharField(max_length=200, null=True) status = models.BooleanField(choices=STATUS, default=True) priority = models.TextField(choices=PRIORITIES, default='None', max_length=10) type = models.TextField(choices=TYPE, default='Misc', max_length=15) description = RichTextField(null=True, blank=True) # description = models.TextField(null=True, blank=True) participants = models.ManyToManyField(CustomUser, related_name='participants', blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-updated', '-created'] def __str__(self): return self.name or '' … -
Get the see only particular station which create by the login user in Django
I Tried to create Slot of station for EV Charging Booking Webiste. If i tried to creating slot of praticular station but I suggest all station which created by other of all. I should see the particular station has the created by login user in Slot in django Here is my Station list Django reflate 3 station from my database My Station 2 and 3 but I can see all 3 station Help to Slove my Query here my Slotviews.py class SlotCreateView(LoginRequiredMixin, CreateView): model = Slot fields = ('slot_name', 'per_unit_price', 'current_status','station') template_name = 'add_slot.html' def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) def get_success_url(self): return reverse('view_slot') here is slot models.py class Slot(models.Model): CURRENT_STATUS_CHOICE = ( ("AVAILABLE", "AVAILABLE"), ("OCCUPIED", "OCCUPIED") ) slot_id = models.AutoField(primary_key=True) station = models.ForeignKey(Station, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) slot_name = models.CharField(max_length=30) per_unit_price = models.DecimalField(max_digits=7, decimal_places=2) current_status = models.CharField(max_length=20, choices=CURRENT_STATUS_CHOICE, default="AVAILABLE") deleted = models.IntegerField(default=0, unique=False) def __str__(self): return f"{self.slot_name}" -
Couldn't find add-on hobby-dev for PostgreSQL database on Heroku
I'm trying to push my application to Heroku using Django, however when I run heroku addons:create heroku-postgresql:hobby-dev -a (appname) it gives me this error: Couldn't find either the add-on service or the add-on plan of "heroku-postgresql:hobby-dev". ! I have also checked that the free version was changed from November 28th, 2022. Is there any other Database add-ons that is reliable so I can use to deploy my app on Heroku. Any suggestions? -
Rollup complains "is not exported" when it is
I'm running into this error while bundling one JS library which includes a package from another of my JS libraries. Both are bundled via Rollup, as UMD modules. I've reacreated this issue in a separate repo in order to show a simple example. It'd be best to pull the repo and npm run build to see what I'm running into. build/index.js → dist/index.umd.js... (!) "this" has been rewritten to "undefined" https://rollupjs.org/guide/en/#error-this-is-undefined node_modules/some-package/index.umd.js 3: typeof define === 'function' && define.amd ? define(['exports'], factory) : 4: (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["clarakm-env-js"] = {})); 5: })(this, (function (exports) { 'use strict'; ^ 6: var MY_CONSTANT = "this is my constant"; [!] RollupError: "MY_CONSTANT" is not exported by "node_modules/some-package/index.umd.js", imported by "build/index.js". https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module build/index.js (1:9) 1: import { MY_CONSTANT } from 'some-package'; ^ 2: console.log(MY_CONSTANT); 3: //# sourceMappingURL=index.js.map at error (/home/josh/Desktop/rollup-issue/node_modules/rollup/dist/shared/rollup.js:210:30) at Module.error (/home/josh/Desktop/rollup-issue/node_modules/rollup/dist/shared/rollup.js:13578:16) at Module.traceVariable (/home/josh/Desktop/rollup-issue/node_modules/rollup/dist/shared/rollup.js:13961:29) at ModuleScope.findVariable (/home/josh/Desktop/rollup-issue/node_modules/rollup/dist/shared/rollup.js:12442:39) at Identifier.bind (/home/josh/Desktop/rollup-issue/node_modules/rollup/dist/shared/rollup.js:8371:40) at CallExpression.bind (/home/josh/Desktop/rollup-issue/node_modules/rollup/dist/shared/rollup.js:6165:28) at CallExpression.bind (/home/josh/Desktop/rollup-issue/node_modules/rollup/dist/shared/rollup.js:9888:15) at ExpressionStatement.bind (/home/josh/Desktop/rollup-issue/node_modules/rollup/dist/shared/rollup.js:6169:23) at Program.bind (/home/josh/Desktop/rollup-issue/node_modules/rollup/dist/shared/rollup.js:6165:28) at Module.bindReferences (/home/josh/Desktop/rollup-issue/node_modules/rollup/dist/shared/rollup.js:13574:18) All of this is built via tsc && rollup -c. Since MY_CONSTANT is clearly exported from some-module, why does Rollup complain that it is not exported? src/index.ts import … -
django don't show form in template ---
django don't show form in template I applied everything in the Django tutorial, but foam does not appear, but I did not know the reason despite my research add_book.html {% extends 'base.html' %} {% block content %} <h1>add book </h1> <form method="post"> {% csrf_token %} <hr> {{form}} <hr> <a href="" type="submit">submit</a> </form> {% endblock content %} in forms from django import forms from .models import book class book_form(forms.Form): class meta: model = book fields = '__all__' in views from .models import * from .forms import book_form def addbook(request): bookform = book_form() context = {'form' : bookform} return render(request, 'add_book.html', context) in url path('book/add', views.addbook, name="addbook"), -
Using ForeignKey in Django
Need help guys I am stuck. I've created 4 models, MasterLoan - listing of all loans, LoanExpenses - listing of all expenses incurred by loans, BillMaster - listing of all billing, BillDetails - expenses incurred by loans billed to client. models.py class LoanMaster(models.Model): loan_number = models.CharField(max_length=50, null=True) loan_name = models.CharField(max_length=150, null=True) class LoanExpenses(models.Model): loan_number = models.ForeignKey(LoanMaster, null=True, on_delete=models.SET_NULL) date = models.DateField(blank=True, null=True) expense_type = models.CharField(max_length=10, blank=True, null=True, choices=EXPENSES_TYPE) amount = models.DecimalField(max_digits=12, decimal_places=2, blank=True, null=True) class BillingMaster(models.Model): bill_number = models.CharField(max_length=50, null=True) bill_date = models.DateField(blank=True, null=True) bill_amount = models.DecimalField(max_digits=12, decimal_places=2, blank=True, null=True) bill_status = models.CharField(max_length=50, blank=True, null=True, default='Unpaid', choices=STATUS) class BillingDetail(models.Model): bill_number = models.ForeignKey(BillingMaster, null=True, on_delete=models.SET_NULL) loan_number = models.ForeignKey(LoanMaster, null=True, on_delete=models.SET_NULL, verbose_name="Loan Number") bill_item = models.CharField(max_length=150, blank=True, null=True) bill_amount = models.DecimalField(max_digits=12, decimal_places=2, blank=True, null=True) How can I automatically pull all the expenses incurred by the loan to a dropdown select for my HTML? Should my BillingDetail.bill_item be a FK to LoanExpenses? -
Making a search bar work in AlpineJS where the searched items in x-data come from x-init
Basically trying to modify the dynamic search bar that can be found in Alpine docs, but with "items" ("bands" in my case) coming from x-init that fetches a JSON. Outside of this search bar all the desired data from this JSON is displayed so it's not like the JSON itself is empty, but in this particular situation x-text doesn't even list any of the values, as if the JSON data never gets to the x-data/"bands" array. This is what I currently have, like I said it's a little modification of the search bar from the docs. <div x-data="{ search: '', bands: [], get filteredItems() { return this.bands.filter( i => i.startsWith(this.search) ) } }" x-init="bands = await (await fetch('/bands/')).json()"> <input x-model="search" placeholder="Search..."> <template x-for="band in filteredItems" :key="band"> <p x-text="`${band.name}`"></p> </template> </div> I'd be grateful if anyone told me what exactly this seemingly straightforward chunk of code is missing. -
I tried to create an html page within django but it does not seem to work
enter image description here For some reaons when i create an html page within django. The html page don't seem to work i attached a picture. anyone willing to help and tell me how to fix it. I tried to create an html page within django but it does not seem to work.