Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Load external data into an admin model - DJANGO
Is it possible to load external data into a field for filling in? Example: A field with for product names. However we already have the names of the products in another location, we just need to list these products within the field in the default django admin. Using resquets. Thank you very much for your attention. -
django.db.utils.IntegrityError: UNIQUE constraint failed: new__Boutique_boutique.product_id
I had 7 unapplied migrations when I ran manage.py migrate I got a unique constraint error Models.py : from django.db import models import uuid class boutique(models.Model): product_id = models.AutoField desc = models.CharField(max_length=300) pub_date = models.DateTimeField(auto_now_add=True) product_name = models.CharField(max_length=50) category = models.CharField(max_length=50, default="") price = models.IntegerField(default=0) image = models.ImageField(upload_to='index/images', default="") slug = models.SlugField(unique=True, default=uuid.uuid1) def __str__(self): return self.product_name I have added the slug field according to a similar question on stack but that doesn't work. Views.py : ` from django.shortcuts import render from math import ceil from .models import boutique from django.http import HttpResponse def Boutique(request): allProds = [] catprods = boutique.objects.values('category', 'id') cats = {item['category'] for item in catprods} for cat in cats: prod = boutique.objects.filter(category=cat) n = len(prod) nSlides = n // 4 + ceil((n / 4) - (n // 4)) allProds.append([prod, range(1, nSlides), nSlides]) # params = {'no_of_slides':nSlides, 'range': range(1,nSlides),'product': products} # allProds = [[products, range(1, nSlides), nSlides], # [products, range(1, nSlides), nSlides]] params = {'allProds': allProds} return render(request, 'Boutique/Boutique.html', params) def individual(request,product_id): #fetching product using the id all_products = boutique.objects.filter(id = product_id) context = {'all_products' : all_products[0]} return render(request,'Boutique/individual.html' , context ) -
DayArchiveview is not detected in urls.py(Django)
I created several date-based views in Django, and while views for year and month function as expected, the view to display days is not detected. For instance, if I try to get http://127.0.0.1:8000/blog/archive/2021/, or http://127.0.0.1:8000/blog/archive/2021/01 the views will be displayed, http://127.0.0.1:8000/blog/archive/2021/01/07 will fail. I understand that the problem must be with urls.py configuration, but I just cannot find it in documentation. I also tried passing day_format='%d' to as_view method, without any results. urls.py from django.urls import path, re_path from blog import views app_name = 'blog' urlpatterns = [ # Example: /blog/ path('', views.PostListView.as_view(), name='index'), # Example: /blog/post/ (same as /blog/) path('post/', views.PostListView.as_view(), name='post_list'), # Example: /blog/post/django-example/ re_path(r'^post/(?P<slug>[-\w]+)/$', views.PostDetailView.as_view(), name='post_detail'), # Example: /blog/archive/ path('archive/', views.PostArchiveView.as_view(), name='post_archive'), # Example: /blog/archive/2019/ path('archive/<int:year>/', views.PostYearArchiveView.as_view(), name='post_year_archive'), # Example: /blog/archive/2019/nov/ path('archive/<int:year>/<int:month>/', views.PostMonthArchiveView.as_view(month_format = '%m'), name='post_month_archive'), # Example: /blog/archive/2019/nov/10/ path('archive/<int:year>/<int:month>/<int:day>/', views.PostDayArchiveView.as_view(), name='post_day_archive'), # Example: /blog/archive/today/ path('archive/today/', views.PostTodayArchiveView.as_view(), name='post_today_archive'), ] views.py from django.shortcuts import render # Create your views here. from django.views.generic import ListView, DetailView, ArchiveIndexView, YearArchiveView, MonthArchiveView, \ DayArchiveView, TodayArchiveView from blog.models import Post class PostListView(ListView): model = Post template_name = 'blog/post_all.html' context_object_name = 'posts' paginate_by = 2 class PostDetailView(DetailView): model = Post class PostArchiveView(ArchiveIndexView): model = Post date_field = 'modify_dt' class PostYearArchiveView(YearArchiveView): model = Post date_field … -
How to use PermissionRequiredMixin in FBV?
I am thinking about how I can use PermissionRequiredMixin in FBV.(I have used the same in CBV and it is working as expected). Please find the FBV(here need to implement permission). I don't want to use @login_required() @login_required() This will check only if the user is authenticated or not. def delete_viewgen(request,PermissionRequiredMixin,id): oneuser=ShiftChange.objects.get(id=id) permission_required = ('abc.add_shiftchange',) oneuser.delete()# delete return redirect('/gensall') I am getting ERROR : missing 1 required positional argument: 'PermissionRequiredMixin' CBV Case where it is working fine. class ShiftChangeUpdateView(PermissionRequiredMixin,UpdateView): permission_required = ('abc.change_shiftchange',) login_url = '/login/' model=ShiftChange fields='__all__' In CBV it is working fine and if user is not having change permission it is giving 403 Forbidden how to implement same in FBV and also how to customize 403 Forbidden message. Thanks! -
int() argument must be a string, a bytes-like object or a number, not 'NoneType' - Django
I'm creating a way on a website, for a user to 'bid' on an item, similar to ebay. I'm getting the error: int() argument must be a string, a bytes-like object or a number, not 'NoneType' This is for the line: user_bid = int(request.POST.get("bid")) I think it thinks 'bid' is None or NoneType. But I'm not sure why. Is there a way to convert this into a float or int? When I do: int(float('bid') or int(float(request.POST.get('bid') it also doesn't work. I need to convert it to int or float because I cannot use the > with a string, I just get another error. I'd appreciate any insight you have! views.py def new_bid(request, listingid): current_bid = Listings.objects.get(id=listingid) current_bid = current_bid.starting_bid if request.method == "POST": user_bid = int(request.POST.get("bid")) if user_bid > current_bid: listing_items = Listings.objects.get(id=listingid) listing_items.starting_bid = user_bid listing_items.save() try: if Bid.objects.filter(id=listingid): bidrow = Bid.objects.filter(id=listingid) bidrow.delete() bidtable = Bid() bidtable.user = request.user.username bidtable.title = listing_items.title bidtable.listingid = listingid bidtable.bid = user_bid bidtable.save() except: bidtable = Bid() bidtable.user = request.user.username bidtable.title = listing_items.title bidtable.listingid = listingid bidtable.bid = user_bid bidtable.save() Bid.objects.filter(id=listingid) return render(request, "auctions/listing.html", { "i": "id" }) else: response = redirect('listingpage', id=listingid) response.set_cookie('error', 'Bid should be greater than current price', max_age=3) return … -
python crash course heroku ModuleNotFoundError: No module named 'bootstrap4'
I am currently following along python crash course to deploy my learning log project to heroku, having errors. Would appreciate any help as I am new to this. Running 'heroku open' in cmd gives me the application error page, which I have tried to fix but running 'heroku run python manage.py migrate' gives me the following error Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/app/.heroku/python/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/app/.heroku/python/lib/python3.9/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'bootstrap4' in settings.py at the very bottom I have added import django_heroku django_heroku.settings(locals()) and at the top INSTALLED_APPS = [ #My apps 'learning_logs', 'users', #Thirsd party apps. 'bootstrap4', #Default django apps. 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] my pipfile(which I have locked while trying to follow other solutions) [[source]] … -
(begginner) how complete is really django?
Hello i am new in python programmation and programation in general(even if i have some IT related knowledge) i have few basic questions to be sure about how django work so as i understand its a framework for web, and you can use it fully with python What are the limitations of django compared to "basic" html/css/sql/php/js combo ? i also know that django is server side framework which make it work kinda like an app running on your web browser Is it possible/most convenient to do a website ONLY by using python with django ? does the framework really take care of all by itself and we can use python for anything ? How does it handle sql ? does it do some kind of local sql base ?(i only knew basic of sql) Thank you -
Django RelatedObjectDoesNotExist at /HomeFeed/comments/slug-1
Comments Functionality I decided to add a "comments" functionality for anyone to post comments on anyone's post. Everything works except one line of code which is giving me the problem. I receive the following error: RelatedObjectDoesNotExist at /HomeFeed/comments/slug-1 Comment has no post. The error is directed to the views.py Specifically this line of code: form.instance.post.slug = self.kwargs['slug'] Please kindly advise how this code can be altered to remove the error. views.py class AddCommentView(CreateView): model = 'Comment' form_class = CommentForm template_name = 'HomeFeed/add_comment.html' def form_valid(self, form): form.instance.post.slug = self.kwargs['slug'] return super().form_valid(form) success_url =reverse_lazy('main') urls.py path('comments/<slug>', AddCommentView.as_view(), name= "add_comment"), forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['name', 'body'] widgets = { 'name' : forms.TextInput(attrs={'class': 'form-control'}), 'body' : forms.Textarea(attrs={'class': 'form-control'}), } models.py class BlogPost(models.Model): chief_title = models.CharField(max_length=50, null=False, blank=False) body = models.TextField(max_length=5000, null=False, blank=False) likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='blog_posts', blank=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) date_published = models.DateTimeField(auto_now_add=True, verbose_name="date published") def __str__(self): return self.chief_title def total_likes(self): return self.likes.count() class Comment(models.Model): post = models.ForeignKey(BlogPost, related_name='comments', on_delete=models.CASCADE) name = models.CharField(max_length=255) body = models.TextField() date_added = models.DateField(auto_now_add=True) def __str__(self): return '%s - %s' %(self.post.chief_title, self.name) add_comment.html (this html is for ppl to add their comments) <div class="form-group"> <form method="POST"> {% csrf_token … -
NoReverseMatch at /admin/ when add custom url
I'm trying to add a custom page in django admin. I wrote code as I've learned, but everytime I try to access the custom page I created, NoReverseMatch exception keeps occuring. NoReverseMatch at /admin/order/order/date_view/ Reverse for 'app_list' with keyword arguments '{'app_label': ''}' not found. 1 pattern(s) tried: ['admin/(?P<app_label>auth|fcuser|product|order)/$'] I've tried various code I could find online, but none is working. Following is my code. class OrderAdmin(admin.ModelAdmin): .... def get_urls(self): urls = super().get_urls() # urls = super(OrderAdmin, self).get_urls() custom_urls = [ # path('date_view/', self.admin_site.admin_view(self.custom_date_view)) # url(r'^date_view/', self.admin_site.admin_view(self.custom_date_view)) path('date_view/', self.custom_date_view) ] return custom_urls + urls def custom_date_view(self, request): context = dict() return TemplateResponse(request, 'admin/order_date_view.html', context) None of the comment solved the issue. I'd be really grateful if anyone can help me out. I want my OrderAdmin class keeps inheriting ModelAdmin. -
how to make attribute in django 3
(myvenv) basekmacbook@BASEK-MACBOOK-PRO portfolio-project % python manage.py makemigration Traceback (most recent call last): File "/Users/basekmacbook/Desktop/portfolio-project/manage.py", line 22, in main() File "/Users/basekmacbook/Desktop/portfolio-project/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/basekmacbook/Desktop/myvenv/lib/python3.9/site-packages/django/core/management/init.py", line 401, in execute_from_command_line utility.execute() File "/Users/basekmacbook/Desktop/myvenv/lib/python3.9/site-packages/django/core/management/init.py", line 377, in execute django.setup() File "/Users/basekmacbook/Desktop/myvenv/lib/python3.9/site-packages/django/init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/basekmacbook/Desktop/myvenv/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File"/Users/basekmacbook/Desktop/myvenv/lib/python3.9/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Cellar/python@3.9/3.9.1_3/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1030, in _gcd_import File "", line 1007, in _find_and_load File "", line 986, in _find_and_load_unlocked File "", line 680, in _load_unlocked File "", line 790, in exec_module File "", line 228, in _call_with_frames_removed File "/Users/basekmacbook/Desktop/portfolio-project/jobs/models.py", line 3, in class Job(models.Model): File "/Users/basekmacbook/Desktop/portfolio-project/jobs/models.py", line 5, in Job summary = models.Charfield(max_length=200) AttributeError: module 'django.db.models' has no attribute 'Charfield' -
Django foreign key field not updating with selected value from React Select component
I have a webpage in my issue tracker project that allows a project manager to assign a user to a project. I am using React Select to allow the manager to select a user from a dropdown. When they click the add user button, the selected value gets sent to the backend through an api call. I have an APIView called assignuser, which takes in the post request and updates the user foreign key field in my Project model. Am I referencing the selected value wrong? I have tried sending selectedValue.value to my backend but it keeps on coming up as undefined. React Frontend import React, { Component } from "react"; import { useState, useEffect } from "react"; import { Grid, TextField, Button, Typography } from "@material-ui/core"; import { FixedSizeList as List } from 'react-window'; import css from './style.css'; import Select from 'react-select'; import {useLocation} from "react-router"; const manageusers = () => { const [role, setRole] = useState([]); const location = useLocation(); const [project_name, setProjectName] = useState(); const [selectedValue, setSelectedValue] = useState() const rolelist = []; const handleChange = obj => { setSelectedValue(obj); } useEffect(() => { fetch("/api/manageroles") .then((response) => response.json()) .then((data) =>{ setRole(data) }) }, []) const post = … -
TemplateDoesNotExist at
I have a problem with REQUEST. Add myapp, so that it recognizes the parameters in request, however, it keeps throwing me an error when reloading the page. What is the problem? Ilustration of problem in WEB CMD def index(request): def index(request): html= """ <h1>Inicio</h1> <p>Años hasta 2050:</p> <ul> """ year =2021 while year<=2050: if year%2 == 0: html+=f"<li>{str(year)}</li>" year+=1 html +="</ul>" #return HttpResponse(layout + html) return render(request, 'index.html') (Index function) -
I Want to create a unique id in django model with customer-auto incremented number
There are 2 models, customer model and ticket creation for a customer class cust_M(models.Model): customer = models.TextField(max_length=8) class TKT(models.Model): tkt_unique_id = models.ForeignKey(customer) + autoincremented when ever we create a instance for the TKT i want to increment the number for the customer. eg: customer1 - 1 customer1 - 2 customer1 - 3 customer2 - 1 customer2 - 2 customer2 - 3 ... ... -
Django custom form - is_valid does not call clean method when __init__ method available
I have the following custom form code in Django: class JoinMeetingForm(forms.Form): meeting_id = forms.UUIDField(help_text="Enter the UUID") def __init__(self,user,*args,**kwargs): self.user=user super(JoinMeetingForm,self).__init__(*args) def clean_meeting_id(self): data = self.cleaned_data['meeting_id'] meeting = Meeting.objects.filter(pk=data) querySuccess = False if len(meeting) == 1: if(meeting[0].joined_user==None): querySuccess = True # ToDo return data First, I call JoinMeetingForm(request.user), which calls the init method. Then, I call form.is_valid(), however, this does not call the clean_meeting_id() method - why is this the case? Strangely, if I comment out the init method, the is_valid() method calls the clean_meeting_id() method. Thanks in advance! -
ValueError: The view mode.views.userSettings didn't return an HttpResponse object. It returned None instead
I am trying to fix this error but I don't know what is the reason for getting it. I am working on a Django Project trying to add a Theme Selection Functionality. The user can select the theme either Light or Dark and it reflects in the backend by the CSS file under the setting.value. The idea is that when a user selects a theme it is saved in the backend and it doesn't chage(unless another theme is chosen). The problem now is that when I refresh the page it returns back to the initial theme and I receive the below error: Traceback (most recent call last): File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\base.py", line 186, in _get_response self.check_response(response, callback) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\base.py", line 307, in check_response raise ValueError( ValueError: The view mode.views.userSettings didn't return an HttpResponse object. It returned None instead. Here is the model.py class Setting(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="mode",null=True,blank=True) name = models.CharField(max_length=200, null=True) value = models.CharField(max_length=200) def __str__(self): return self.name Here is the views.py def userSettings(request): user, created = User.objects.get_or_create(id=1) setting = getattr(user, 'setting', None) if setting: seralizer = UserSerailizer(setting, many=False) return JsonResponse(seralizer.data, safe=False) def updateTheme(request): data = json.loads(request.body) theme = data['theme'] user … -
Many-to-many and hierarchical database design
i'm designing a database and run into some problems: I have a Document entity consisting of many fields. Mostly i want to use the same version of that document but sometimes users should be able to customize some of the fields for a specific usage of the document. Not customized fields should use the value of the parent document as a default. Changes to the parent document should get propagated to any not customized field of a specific usage. I have a table Document: Document: id | field1| field2 | field3| parentDocumentId For parent documents is parentDocumentId = Null. Customized usages of a document have the new value for the customized fields saved and for not customized fields simply null. Is this a good design? Furthermore the Document entity has a many-To-many relationship with another entity Course. My problem now is when i look at a row of Document with parentDocumentId != null and courses = null i can't determine if the relationship is either not customized by the user yet and i should use the value of the parent document or the field is customized by the user and simply has no courses. How can i solve that? Thanks -
Django Error - Reverse for 'new_bid' with arguments '('',)' not found. 1 pattern(s) tried:
I'm somewhat new to Django and creating a way for users to 'bid' on items, similar to ebay. I am getting the error: Reverse for 'new_bid' with arguments '('',)' not found. 1 pattern(s) tried: ['new_bid/(?P[0-9]+)$'] I know I have some things mixed up, specifically the end of views.py in the return render request but I'm not sure what I need to have there. I know in the html {% url 'new_bid' i.id %} is also not correct, but I'm struggling to figure out what should be here as well. Any help is appreciated as I'd like to learn more. views.py def new_bid(request, listingid): current_bid = Listings.objects.get(id=listingid) current_bid = current_bid.starting_bid if request.method == "POST": user_bid = int(request.POST.get("bid")) if user_bid > current_bid: listing_items = Listings.objects.get(id=listingid) listing_items.starting_bid = user_bid listing_items.save() try: if Bid.objects.filter(id=listingid): bidrow = Bid.objects.filter(id=listingid) bidrow.delete() bidtable = Bid() bidtable.user = request.user.username bidtable.title = listing_items.title bidtable.listingid = listingid bidtable.bid = user_bid bidtable.save() except: bidtable = Bid() bidtable.user = request.user.username bidtable.title = listing_items.title bidtable.listingid = listingid bidtable.bid = user_bid bidtable.save() Bid.objects.filter(id=listingid) return render(request, "auctions/listing.html", { "i": "id" }) else: response = redirect('listingpage', id=listingid) response.set_cookie('error', 'Bid should be greater than current price', max_age=3) return response else: return redirect('index') The urls in urls.py path("listings/<int:id>", views.listingpage, … -
Return the instance of the model, if a value in it contains a string passed in by a user. Django Rest Framework, filtering
So lets say i have a model called Article, which hold a field called article_title(CharFiled). On the client side, the user passes in a keyword and sends it to the server. Can i make a serialized view, which returns every database instance, on a condition that it contains the passed in keyword in the article_title field? Is there a way to implement this? -
When building forms in Django, is it good practice to use one 'fat' model to contain all my fields for multiple forms?
Context: I am building a car dealership app and have multiple forms to create such as: A basic contact requesting a name, email, phone and comments. A service form requesting the above along with the users make, model and mileage A sales form, requesting all the above again along with a few other similarly relevant questions. Problem: So I'm trying to find out is it best practice to have one 'fat' model containing all these fields and then create multiple forms from them or to create a model per form? I know that I should stick to the DRY practices but I would really benefit from a stronger understanding. -
I can extends + with?
I need to pass the value from the template when connecting extends. So that I can check whether to connect the style or not. I need to pass the page title, is main page {% extends "base_not_auth.html" with page="main" %} If main page, i use css file {% if page == "main" %} <link rel="stylesheet" href="{% static 'css/page.css' %}"> {% endif %} -
user.is_authenticated works in html but not views
I just learned about the django.contrib.auth built-in package and am trying to implement user authentication for my blog application! Doing user.is_authenticated in my html works: <div class="footer"> <div class='sub-footer'> <ul style="list-style:none;"> <li>-<a href="{% url 'login' %}">Admin, Login Here!</a></li> <li>- <a href="https://www.flaticon.com">Pencil Icon made by </a><a href="https://www.flaticon.com/authors/becris">Becris </a><a href="https://www.flaticon.com">from www.flaticon.com</a> <li>- <a href="https://www.flaticon.com">Heart Icon made by </a><a href="https://www.flaticon.com/authors/gregor-cresnar">Gregor Cresnar </a><a href="https://www.flaticon.com">from www.flaticon.com</a> </ul> </div> </div> {% if user.is_authenticated %} yo whats good authenticated user {% endif %} But, when I try this in my views: if user.is_authenticated: return render(request, 'admin.html', context) return render(request, 'registration.html') I get this error: NameError at /admin-dash/ name 'user' is not defined Request Method: GET Request URL: http://127.0.0.1:8000/admin-dash/ Django Version: 3.1.2 Exception Type: NameError Exception Value: name 'user' is not defined Exception Location: C:\Users\benja\Desktop\mysite\mysite\blog\views.py, line 137, in admin_view Python Executable: C:\Users\benja\anaconda3\envs\mysite\python.exe Python Version: 3.8.5 Python Path: ['C:\\Users\\benja\\Desktop\\mysite\\mysite', 'C:\\Users\\benja\\anaconda3\\envs\\mysite\\python38.zip', 'C:\\Users\\benja\\anaconda3\\envs\\mysite\\DLLs', 'C:\\Users\\benja\\anaconda3\\envs\\mysite\\lib', 'C:\\Users\\benja\\anaconda3\\envs\\mysite', 'C:\\Users\\benja\\anaconda3\\envs\\mysite\\lib\\site-packages'] Server time: Sun, 10 Jan 2021 00:03:09 +0000 Traceback Switch to copy-and-paste view C:\Users\benja\anaconda3\envs\mysite\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) … ▶ Local vars C:\Users\benja\anaconda3\envs\mysite\lib\site-packages\django\core\handlers\base.py, line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars C:\Users\benja\Desktop\mysite\mysite\blog\views.py, line 137, in admin_view if user.is_authenticated: … ▶ Local vars It makes sense, but I … -
How to autofocus a Charfield in a Django ModelForm
In my django app I want to set focus to the first CharField (task) when the page loads. my models.py is from django.db import models class ListModel(models.Model): task = models.CharField(max_length=255) status = models.BooleanField(default=False) def __str__(self): return f"{self.task} : {str(self.status)}" and forms.py is from django.forms import ModelForm from .models import ListModel class ListForm(ModelForm): class Meta: model = ListModel fields = ["task", "status"] I have tried adding the following widget in my CharField (in models.py): task = models.CharField(max_length=255, widget=models.TextInput(attrs={'autofocus': True}) but it gives an AttributeError: module 'django.db.models' has no attribute 'TextInput' I have also tried adding the following to the ListForm class (in forms.py): def __init__(self): self.fields['task'].widget.attrs.update(autofocus = 'autofocus') though I am not getting any error for this, but when I load my page the focus is not set to the task CharField either. What can I do add auto-focus to my CharField? -
Setup a ready signup template in django instead of the UserCreationForm
So I have a designed signup form template in html & css and I want to know how to setup it in Django instead of using its forms -
Django Rest how to test a DELETE request using pytest
So i'm trying to test deleting a post. my post view is using RetrieveUpdateDestroyAPIView which enable me to use GET, PUT and DELETE requests. but for some reason I get a testing error saying: Method Not Allowed @pytest.fixture def delete_post(api_client): post_id = Post.objects.all()[0].id delete_post_url = '/posts/{post_id}/' delete_post = api_client.delete(delete_post_url) return delete_post @pytest.mark.django_db def test_post_detail_render(self, api_client, login, create_post ,delete_post): delete_post_page_render = delete_post assert delete_post_page_render.status_code == 200 E assert 405 == 200 E + where 405 = <HttpResponseNotAllowed [GET, HEAD, OPTIONS] status_code=405, "text/html; charset=utf-8">.status_code WARNING django.request:base.py:101 Method Not Allowed (DELETE): /posts/{post_id}/ WARNING django.request:log.py:224 Method Not Allowed: /recipes/{recipe_id}/ -
Django3 ListView with Conditional WHERE
I have simple ListView in Django 3: path("show/<int:pk>", ApplicantListView.as_view(), name='applicant-list'), my view is as follow: class ApplicantListView(ListView): model = Applicant paginate_by = 100 template_name = 'applicant_list.html' and the model class Work(models.Model): title = models.CharField(max_length=200) body = models.TextField() published = models.BooleanField(False) date = models.DateTimeField() def __str__ (self): return self.title class Applicant(models.Model): name= models.CharField(max_length=200) email = models.EmailField(max_length=100) country = CountryField(blank_label='(select country)') work= models.ForeignKey(Work, on_delete=models.CASCADE) upload = models.FileField(upload_to='up/') def __str__ (self): return self.name so what I would like to achieve is to show only the applicants for the work ID used in the URL path. At the moment it shows all the records diregrading the pk used in the path.