Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
is there any performance benefit to using bulk_update as compared to just update in django for a same value update?
I have the following piece of code Subscription.objects.filter(id__in=[subscription.id for subscription in subscriptions]).update(renewal_notification_sent=True) but I'm wondering if something like updatable_subscriptions = [] subs = Subscription.objects.filter(id__in=[subscription.id for subscription in subscriptions]) for sub in subs: sub.renewal_notification_sent = True updatable_subscriptions.append( subs ) # then Subscription.objects.bulk_update(updatable_subscriptions, ["renewal_notification_sent"]) would have any performance benefit. Does calling filter followed by update make 2 database queries? -
JWT authentication does not work in Django Rest Framework after deploying it to IIS on live server
I built a Rest API using Django's Rest framework. And I've deployed it on Windows OS's IIS. When I deploy the application to the live IIS server, it throws the following issue even though it functions well on the local IIS server. Note: I have passed the Authorization header correctly. { "errors": { "detail": "Authentication credentials were not provided." } } -
How to fill automatically selectsize JS when edit the HTML form?
I have a form with 3 fields which are 2 input text and 1 select from dropdown menu. When I add the data then I want edit them, I want to the old data appearing on the field. Input text field is already OK but the select field (Country) which I build using select size js is not appearing the old value. <form action="" method="post" id="EditForm"> {% csrf_token %} <div class="col-md-12"> <div class="form-group"> <label for="NameEdit" class="control-label">Name</label> <input name="Name" id="NameEdit" type="text" class="form-control" required oncopy="return true;" onpaste="return true;" oncut="return true;" /> </div> <div class="form-group"> <label for="AddressEdit" class="control-label">Address</label> <input name="Address" id="AddressEdit" type="text" class="form-control" data-toggle="popover" data-trigger="focus" required data-placement="left" oncopy="return true;" onpaste="return true;" oncut="return true;" /> </div> <div class="form-group"> <label for="CountryEdit" class="control-label">Country</label> <select name="CountryEdit" type="text" class="form-control" id="CountryEdit" required data-placement="left" oncopy="return true;" onpaste="return true" oncut="return true;" > <option value="">Select the country</option> {% for x in countries %} <option value="{{x.CountryCode}}">{{x.CountryCode}} ({{x.CountryName}})</option> {% endfor %} </select> </div> </div> </form> $(document).on('click', '.editUserBtn', function () { var user = $(this).data('id'); editUrl = 'edit/'+user; var currentURL = window.location.href; console.log(currentURL + 'edit/' + user); $.ajax({ type: "GET", url: currentURL + 'edit/' + user, success: function (data) { $('#EditForm').attr('action', 'edit/' + user); $('#EditModal').modal('show'); $('#NameEdit').val(data.Name); $('#AddressEdit').val(data.Address); $('#CountryEdit option:checked').val(data.Country); } }) }); -
Return JSON or template based on query parameter with django restframework
''' class ProfileList(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'profile_list.html' def get(self, request): queryset = Profile.objects.all() return Response({'profiles': queryset}) ''' As documented, the above View renders and returns a html template. However, how to control the view to return the json or html template in the view? For example, by providing parameter as ?type=html, it returns the html page; and with ?type=json it return the json data. -
Django - Counting ManyToMany Relationships
In my model, I have many Things that can have many Labels, and this relationship is made by user-submitted Descriptions via form. I cannot figure out how to count how much of each Label each Thing has. In models.py, I have: class Label(models.Model): name = models.CharField(max_length=100) class Thing: name = models.CharField(max_length=100) class Description: thingname = models.ForeignKey(Thing, on_delete=models.CASCADE) labels = models.ManyToManyField(Label,blank=True) If we say our current Thing is a cat, and ten people have submitted a Description for the cat, how can we make our template output an aggregate count of each related Label for the Thing? For example: Cat 10 fluffy 6 fuzzy 4 cute 2 dangerous 1 loud I've tried a few things with filters and annotations like counts = Label.objects.filter(description_form = pk).annotate(num_notes=Count('name')) but I think there's something obvious I'm missing either in my views.py or in my template. -
"formfield_overrides" vs "formfield_for_dbfield()" vs "form" vs "get_form()" to change the width of the field in Django Admin
For example, there is Person model below: # "models.py" from django.db import models class Person(models.Model): name = models.CharField(max_length=20) age = models.PositiveSmallIntegerField() def __str__(self): return self.name Then, when using formfield_overrides, formfield_for_dbfield(), form or get_form() below: # "admin.py" from django.contrib import admin from .models import Person from django.db import models from django import forms @admin.register(Person) class PersonAdmin(admin.ModelAdmin): formfield_overrides = { # Here models.PositiveSmallIntegerField: { 'widget': forms.NumberInput(attrs={'style': 'width:100ch'}) }, } Or: # "admin.py" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): # Here def formfield_for_dbfield(self, db_field, request, **kwargs): field = super().formfield_for_dbfield(db_field, request, **kwargs) if db_field.name == 'age': field.widget.attrs['style'] = 'width: 100ch' return field Or: # "admin.py" from django.contrib import admin from .models import Person from django import forms class PersonForm(forms.ModelForm): age = forms.CharField( widget=forms.NumberInput(attrs={'style':'width:100ch'}) ) @admin.register(Person) class PersonAdmin(admin.ModelAdmin): form = PersonForm # Here Or: # "admin.py" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): # Here def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) form.base_fields['age'].widget.attrs['style'] = 'width: 100ch;' return form I can change the width of age field on "Add" and "Change" pages as shown below: Now, are there any differences between formfield_overrides, formfield_for_dbfield(), form and get_form() to change the width of the field in … -
ValueError at /book/add Field 'id' expected a number but got 'add' --- django
A working site was bringing the collection of books with its content displayed But when I add a function def addbook(request): it gives me a problem this: ValueError at /book/add Field 'id' expected a number but got 'add'. in -- all_book.html: {% extends 'base.html' %} {% block content %} <h1>kljgf</h1> <a href ="{% url 'addbook' %}">Add Book</a> {% for book in books %} <h3> <a href = "{% url 'detail_book' book.id %}">{{book.namebook}}</a> </h3> <hr> {% endfor %} {% endblock content %} in views: def detail_book(request, id): boo = book.objects.get(id=id) context = {'book' : boo} return render(request, 'detail_book.html', context) def addbook(request): book_form = book_form() context = {'form' : book_form} return render(request, 'add_book.html', context) in url: path('book/<id>', views.detail_book, name="detail_book"), path('book/add', views.addbook, name="addbook"), in add_book.html {% extends 'base.html' %} {% block content %} <h1>add book </h1> <form method="POST"> {% csrf_token %} {{form}} </form> {% endblock content %} -
How to create a function for Phone Dialing [for Python Django]?
I am an Python Django newbie , trying to find an function to add to my website im working on. What Im trying to do is simple operation - when you click a "Call us" button in my website, to open the Phone Dial with the specific number inputed in the phone dial input line not call immeadiately, just automatically prewrited the set phone number, as shown in the picture I searched alot in google,git,youtube, but I couldn't find what exacly I am looking for.