Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i work with 3 django models linked by a foreign field?
I've been able to display all offices in an election, but have been unable to display all candidates in an office on the same page models.py class Election(models.Model): name = models.CharField(max_length = 30) slug = models.SlugField(max_length = 250, null = False, unique = True) class Office(models.Model): election = models.ForeignKey(Election, on_delete=models.CASCADE, default=None) name = models.CharField(max_length = 30) class Candidate(models.Model): office = models.ForeignKey(Office, on_delete=models.CASCADE, default=None) name = models.CharField(max_length = 30) views.py def poll(request, id): context = { 'election' : Election.objects.get(pk=id), 'off' : Office.objects.all() } return render(request, 'poll.html', context) poll.html {% for office in election.office_set.all %} <div class="text-center"> <h3>{{ office.name }}</h3> {% for candidate in off.candidate_set.all %} <h5><a href="">{{ candidate.name }}</a></h5> {% endfor %} </div> {% endfor %} -
Cannot resize one specific field in Django admin
I’m overriding fields in Django admin like this: class MyPageAdmin(FlatPageAdmin): def formfield_for_dbfield(self, db_field, **kwargs): if db_field.name == 'url': return db_field.formfield(widget=forms.TextInput(attrs={'size': 100})) if db_field.name == 'title': return db_field.formfield(widget=forms.TextInput(attrs={'size': 150})) return super(MyPageAdmin, self).formfield_for_dbfield(db_field, **kwargs) admin.site.unregister(FlatPage) admin.site.register(MyPage, MyPageAdmin) Now, the problem is that for the "Title" field in Django admin, the field width changes just as expected – size attribute is set to 150, but for the URL field, there’s absolutely now change. Yet, the code does run into the specific if statement, so the URL field is definitely there, but for the life of me, I cannot figure out, why only this field is unaffected by the override. Other fields do not suffer this problem (I have other overrides besides the "Title" field, but only the URL is stuck in its original size). -
Django UpdateView CheckboxSelectMultiple - How do I load an object's ManyToMany field in CheckboxSelectMultiple?
My UpdateView draws from a ModelForm where the sport_prefs field loads as CheckboxSelectMultiple. The form loads correctly and submits data to the MemberRecord model successfully. My issue is in the UpdateView even though the sport_prefs field shows up as checkboxes, it does not load the current object sport_prefs field's data. The checkboxes load as blank and while I can select options and it will update and save correctly, I cannot load the sport_prefs data from when it was first created or last updated. models.py class SportOptions(models.Model): sport_name = models.CharField(max_length=200) class MemberRecord(models.Model): name = models.ForeignKey(ContactInfo, on_delete=models.PROTECT) age = models.IntegerField() join_date = models.DateField(default=timezone.now) sport_prefs = models.ManyToManyField(SportOptions) notes = models.TextField(blank=True) author = models.ForeignKey(User, on_delete=models.PROTECT) forms.py class createForm(ModelForm): sport_preference = forms.ModelMultipleChoiceField( queryset=SportOptions.objects.filter(), widget=forms.CheckboxSelectMultiple ) class Meta: model = MemberRecord fields = [ 'name', 'age', 'join_date', 'sport_preference', 'notes' ] My guess is I created a new CheckboxSelectMultiple field and I load the correct options because I draw from the SportOptions model but I do not draw from the specific object's sport_prefs. This shows true when I change the ModelForm 'sport_preference' back to 'sport_prefs' as it loads the data correctly but it does not load as CheckBoxSelectMultiple. I am guessing I need to pass the object … -
Visibility of a Django formview in templates
I've followed the tutorial here to implement a basic search function: https://learndjango.com/tutorials/django-search-tutorial I'd like to extend that tutorial by making the search function visible on the results page, allowing for repeated search. However, when I do this I can't get the search form to show up on the search results page. The search button shows up, but not the field to provide input. Relevant code: home.html: <div name="searchform"> <form action="{% url 'search_results' %}" method="get"> {{ form }} <input type="submit" value="Search"> </form> </div> {% block content %} {% endblock %} search_results.html: {% extends home.html} {% block content %} <h1>Search Results</h1> <ul> {% for city in object_list %} <li> {{ city.name }}, {{ city.state }} </li> {% endfor %} </ul> {% endblock %} Views.py: from django.db.models import Q from django.views.generic import TemplateView, ListView, FormView from .models import City class HomePageView(FormView): template_name = 'home.html' form_class = SearchForm class SearchResultsView(ListView): model = City template_name = 'search_results.html' def get_queryset(self): query = self.request.GET.get('q') object_list = City.objects.filter( Q(name__icontains=query) | Q(state__icontains=query) ) return object_list urls.py: from django.urls import path from .views import HomePageView, SearchResultsView urlpatterns = [ path('search/', SearchResultsView.as_view(), name='search_results'), path('', HomePageView.as_view(), name='home'), ] forms.py: from django import forms class SearchForm(forms.Form): q = forms.CharField(label='', max_length=50, widget=forms.TextInput(attrs={'placeholder': 'Search Here'}) … -
Django Upload button in Bootstrap href without JS
Is there a way to insert a Django FileInput form field in bootstrap href link without using JS. I have something like this: <div class="post-new-tab-nav"> <a href="{{ form.viPicture }}" uk-tooltip="title:Close"> <i class="uil-image"></i> </a> <a href="#"> <i class="uil-user-plus"></i> </a> <a href="#"> <i class="uil-video"></i> </a> </div> The form field that I am trying to insert would be {{ form.viPicture }}. What I intend to achieve would be to trigger the file upload once the href is clicked. Can this be done without using JS? -
My navbar is being overridden by something else and I can't figure out what
so every once in a while, I do collectstatic or something happens where my navbar gets overridden. I can't figure out what's going on. When I would do collectstatic, I would have a staticfiles folder get created, with an admin folder with a bunch of Dif css sheets that were different than mine. Usually when I would delete that folder, things would go back to normal. However, after deleting it, I'm still missing my navbar. My actual links work fine if I manually type them in, but my navbar is getting overridden or something, and I'm not sure why. This problem occurs both locally and on my heroku server. my app https://cupids-corner.herokuapp.com github https://github.com/RezaZandi/Dating-App -
The cards clutter in a single row, while they're supposed to break up into multiple rows when the browser is resized
I am having trouble getting the cards in this django project to be responsive the way I want them to be. I followed a tutorial to create this: But when I resize the browser: As you can see, the cards clutter in a single row, while they're supposed to break up into multiple rows when the browser is resized. My code: {% extends 'base.html' %} {% block content %} <h1>Products</h1> <div class="row"> {% for product in products %} <div class="col"> <div class="card" style="width: 18rem;"> <img src="{{product.image_url}}" class="card-img-top" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">The best Pyshop {{product.name}}s!</h5> <p class="card-text">Only ${{product.price}}!</p> <a href="#" class="btn btn-primary">Add to cart</a> </div> </div> </div> {% endfor %} </div> {% endblock %} Please point out what I did wrong. -
What happens if I change file name from foo.png to foo.png.txt?
Dears, i have a file xxx.png and and I change the name to xxx.png.txt. Then I have lots of strange strings in the txt file. I made the changes in my os. What are these strange strings? -
Overridden error message not being displayed in serializer
I have a ListField serializer where if it's empty, it should display the appropriate message: class CreatePostSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField( read_only=True, ) topics = serializers.ListField( child=serializers.CharField( max_length=50, error_messages={'max_length': 'Each tag should be no more than 50 characters.'} ), max_length=3, write_only=True, error_messages={'required': 'You need to add at least one tag to your question.'} ) class Meta: model = Question fields = ('user', 'status', 'topics') The error message: You need to add at least one tag to your question. is not being thrown when the list is empty, instead the default error message is thrown: `This field is required." How can I make it so that my custom error message is displayed instead? -
Django - Any issues with having similar urls in same urls.py?
Please comment on: A) Will the below cause any unexpected errors because urls are similar and B) Is this approach of using similar url names fine, or not recommended for Django from django.urls import path from . import views urlpatterns = [ path('subcribers/', views.subscribers, name='unsubcribers'), path('subcribe/', views.unsubscribe, name='unsubcribe'), ] -
Accessing JSON data in template in Django
I have a view that retrieves a JSON file like this: json_lang = requests.get('path/to/file.json').json() return render(request, "chat/chatroom.html", {'jsonLang': json.dumps(json_lang)}) Let's say the json file is structured somewhat like this: { "en": { "action.send": "Send", "chat.joined": "joined the chatroom", "chat.left": "left the chatroom", ... } If I try to access one of those strings in a template like this {{ json_lang.en.chat.joined }} I get an empty output. Other methods, like trying to access it like this json_lang.["en"]["chat.joined"] result in an error: TemplateSyntaxError at /chat/ Could not parse the remainder: '["en"]["chat.joined"]' from 'json_lang.["en"]["chat.joined"]' What's the correct method to do this? -
How to Serve User-Uploaded pdf Files in Django?
I am attempting to display user uploaded PDF files in Django. I am successfully able to display images, but not pdf files. On the landing page, a user is being asked to fill out a Form: class Profile_Form(forms.ModelForm): class Meta: model = User_Profile fields = [ 'fname', 'lname', 'technologies', 'email', 'display_picture' ] I built a model that sets the display_picture to be a simple FileField. class User_Profile(models.Model): display_picture = models.FileField() def __str__(self): return self.fname On the view (for both landing page and display of pdf/image, I am sending the user to the details.html after they submit their form IMAGE_FILE_TYPES = ['png', 'jpg', 'jpeg', 'pdf'] def create_profile(request): # Create Form form = Profile_Form() # If Request is a POST, User needs to be Directed Somwehwere if request.method == 'POST': # Form Information is extracted from Forms.py form = Profile_Form(request.POST, request.FILES) if form.is_valid(): user_pr = form.save(commit=False) user_pr.display_picture = request.FILES['display_picture'] File_Upload_Name = str(request.FILES['display_picture']) print("File Name:", File_Upload_Name) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) print("Base Dir: ", BASE_DIR) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') print("Media Root: ", MEDIA_ROOT) # Define Invoice Path invoice_path = File_Upload_Name user_pr.invoice_path = invoice_path # Copy File # copyfile("../media/" + user_pr.invoice_path, "../static/" + user_pr.invoice_path) print("Invoice Path: ", user_pr.invoice_path) # Grab the File Type (Should be ZIP) … -
Vue.js (axios) ignoring Django Set-Cookie Response
I am migrating a Django project to Vue.js + DRF, because I need it to be SPA. I went into trouble regarding sessions and csrf cookie which is needed for obvious security reason. Vue app runs on 127.0.0.1:8080 DRF api runs on 127.0.0.1:8000 Response headers used for request (AXIOS): Accept: application/json, text/plain, */* Accept-Encoding: gzip, deflate, br Accept-Language: en,zh-CN;q=0.9,zh;q=0.8,es;q=0.7 Connection: keep-alive Host: 127.0.0.1:8000 Origin: http://127.0.0.1:8080 Referer: http://127.0.0.1:8080/ Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: same-site User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36 X-CSRFToken: undefined Response headers from api: Access-Control-Allow-Origin: http://127.0.0.1:8080 Allow: GET, HEAD, OPTIONS Content-Length: 25 Content-Type: application/json Date: Tue, 14 Jul 2020 20:55:13 GMT Server: WSGIServer/0.2 CPython/3.8.2 Set-Cookie: csrftoken=wFeB48cStoHy2hupKZNciGvYKFIlq4Y9QCfzCQ0Qfe5RMdRzolxcYK5MgefvLBcp; expires=Tue, 13 Jul 2021 20:55:13 GMT; Max-Age=31449600; Path=/; SameSite=Lax Vary: Accept, Cookie, Origin X-Content-Type-Options: nosniff X-Frame-Options: DENY Expected outcome: The browser sets the cookie specified by the response headers. I suspect the issue is due to the port being different, I found no solution but to build the Vue in the directory "dist" and Django serves the entry point, but that may not be what I want. -
django: getting a Error inside signup-form
Error: object of type 'NoneType' has no len() Error in Signupform validation in django request show correct if I send get request print(request) [output: GET] and post request [output:POST] but get request also show a value of 'value':value variable I didn't pass any value in GET request def signup(request): print(request) if request.method == "POST": error_msg = None fname = request.POST.get('fname') lname = request.POST.get('lname') email = request.POST.get('email') password = request.POST.get('password') value = {'fname': fname, 'lname': lname, 'email':email} customer = Signup(first_name=fname, last_name=lname, email=email, password=password) if len(fname) < 4: error_msg = "First Name Must Be More Than 4 Character" elif len(lname) < 4: error_msg = "Last Name Must Be More Than 4 Character" elif customer.is_exist(): # describe in models.py error_msg = "Email is Registered" if not error_msg: customer.save() return redirect('index') else: context = {'error': error_msg, 'value':value} return render(request, 'product/signup.html', context) else: print('get request') return render(request, 'product/signup.html') models.py : class Signup(models.Model): first_name=models.CharField(max_length=100) last_name=models.CharField(max_length=100) email = models.EmailField() password = models.CharField(max_length=500) def __str__(self): return self.first_name def is_exist(self): return Signup.objects.filter(email = self.email) -
Django ContentFile() unexpected empty line (django.core.files.base)
I have a problem with the ContentFile function of django.core.files.base I wrote a function that allows me to save text into an .md file def save(title,content) filename = f"entries/{title}.md" if default_storage.exists(filename): default_storage.delete(filename) default_storage.save(filename, ContentFile(content)) I am using a simple textarea in a form that submits the content to the route that will save it. The problem is that after saving every new line is duplicated: Hello World Becomes Hello World And this happens all the time. If you have 2 empty lines you end up having 4 of them... Am I doing something wrong? -
Associating authenticated user to form object Djano
I am having troubles passing a User(a foreign key) into a submitted form. Here is what the model looks like: from django.db import models from person.models import UserProfile from django.urls import reverse from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth.models import User from django.db.models import signals User = get_user_model() # Create your models here. class UserPost(models.Model, Activity): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='userpostauthor') content = models.TextField(max_length=2000, blank=True, null=True) postvideo = models.FileField(upload_to='UserPost/postvideo', blank=True, null=True) postPicture = models.FileField(upload_to='UserPost/postpicture', blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) Here's my views.py form: class TimelineView(CreateView): fields= ['content', 'postvideo', 'postPicture'] model = UserPost success_url = reverse_lazy('timeline_feed') template_name = 'main/timeline.html' def form_valid(self, form): form.instance.user = self.request.user return super(TimelineView, self).form_valid(form) def get_context_data(self, form=None): context = super(TimelineView, self).get_context_data() I would get this error when I try to submit the form: IntegrityError at /timeline/ null value in column "author_id" violates not-null constraint DETAIL: Failing row contains (20, , , , 2020-07-14 20:43:53.631628+00, null). Request Method: POST Request URL: http://127.0.0.1:8000/timeline/ Django Version: 2.2.12 Exception Type: IntegrityError Exception Value: null value in column "author_id" violates not-null constraint DETAIL: Failing row contains (20, , , , 2020-07-14 20:43:53.631628+00, null). Obviously I am doing something wrong. What would be the best way to fix this? -
Django rest framework: Chain nested serializers
I have a DRF API which contains several models that basically form the following hierarchy: Farm -> herd/s -> group/s -> cow/s I've set up the models successfully but I'm not sure how to serialize it. class CowSerializer(serializers.ModelSerializer): class Meta: model = Cow fields = '__all__' class GroupSerializer(serializers.ModelSerializer): cows = CowSerializer(many=True) class Meta: model = Group fields = '__all__' class HerdSerializer(serializers.ModelSerializer): groups = GroupSerializer(many=True) class Meta: model = Herd fields = '__all__' class FarmSerializer(serializers.ModelSerializer): herds = HerdSerializer(many=True) class Meta: model = Farm fields = '__all__' This setup raises the following error: Got AttributeError when attempting to get a value for field `cows` on serializer `GroupSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Farm` instance. Original exception text was: 'Farm' object has no attribute 'cows'. -
Django is not recognizing my static folder
Ok so I created a project called "first_project" and I got stuck at rendering my static file. I've literally searched everywhere for the solution i couldn't find it. In my settings.py I have BASE_DIR = os.path.dirname(os.path.direname(is.path.abspath(__file__))) TEMPLATES_DIR = os.path.join(BASE_DIR, "templates") STATIC_DIR = os.path.join(BASE_DIR, 'static') And at the bottom of the settings.py file I have STATIC_URL = '/static/' MEDIA_URL = '/images/' STATICFILES_DIR = [STATIC_DIR,] The problem is both the CSS folder and the image folder in static is not being recognised whenever I runserver(i.e it doesn't reflect on the website) -
I'm getting 'No Access-Control-Allow-Origin header is present on the requested resource' even with all configured in Django Rest Framework
Even with all configuration made, when I try to access my DRF Api by XMLHttpRequest(using Axios), I'm getting the error below: Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/posts' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. When I use Postman I do not have any errors whatsoever. settings.py import os import django_heroku from decouple import config from dj_database_url import parse as dburl # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = config('SECRET_KEY') DEBUG = config('DEBUG') ALLOWED_HOSTS = ['ablog-back.herokuapp.com', 'localhost:3000'] # Application definition CORS_ORIGIN_ALLOW_ALL = True # CORS_ORIGIN_WHITELIST = ( # 'http://localhost:3000', # ) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'ablogback.api', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'ablogback.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'ablogback.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases default_dburl = 'sqlite:///' + os.path.join(BASE_DIR, 'db.sqlite3') DATABASES = { 'default': config('DATABASE_URL', default=default_dburl, cast=dburl), } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': … -
Django: How can I add a looked up field to ListView?
I have a model (Listing below) that contains information about ship sailings. The ports for the sailings are given by the duple of xxxx_country and xxxx_port. I list the sailings with a class ListingView based on ListView. I want to pass the port name to the template rather than xxxx_country and xxxx_port, and I can get the name from a Port model. Here's the code: # from listing/models.py class Listing(models.Model): # Port Codes - see https://www.worldnetlogistics.com/seaport-codes/ orig_country = models.CharField(max_length=2, blank=True) orig_port = models.CharField(max_length=3, blank=True) dest_country = models.CharField(max_length=2, blank=True) dest_port = models.CharField(max_length=3, blank=True) # from codes/models.py class Port(models.Model): country_code = models.CharField(max_length=2, blank=True) location_code = models.CharField(max_length=3, blank=True) name = models.TextField() # from listing/views.py class ListingView(ListView): model = Listing # need code here that looks up the port name by combination of country_code and location_code # one Port object will be returned orig_port_name = ? dest_port_name = ? template_name = 'listing/home.html' # change from default template name ordering =['-ship_sailing'] # reordering the list in reverse order paginate_by = 16 What code do I need to put into the view so that I can pass the orrig_port_name and dest_port_name to the template? Best regards...Paul -
Search QuerySet of Dates Django
I have a QuerySet of dates in my Django project. Consider the following dates in the QuerySet as an example: mm-dd-YYYY 01-15-2003 12-03-1971 04-23-1970 03-08-2005 Now, I also have a search bar to search through these dates. I want to enable the functionality so that the user can type "Jan" and all dates in January would remain. Or, if they were to type "J", then all dates in January, June, or July would remain. I guess, what I am asking, is how can I enable a search bar to filter through a QuerySet of dates? -
Django Search not working for Project 1 need code
I have a code to have a search box do the following: Search: Allow the user to type a query into the search box in the sidebar to search for an encyclopedia entry. If the query matches the name of an encyclopedia entry, the user should be redirected to that entry’s page. If the query does not match the name of an encyclopedia entry, the user should instead be taken to a search results page that displays a list of all encyclopedia entries that have the query as a substring. For example, if the search query were Py, then Python should appear in the search results. Clicking on any of the entry names on the search results page should take the user to that entry’s page. this is the code I have: views.py from django.shortcuts import render from django.http import HttpResponseRedirect from . import util from django.urls import reverse def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def wiki(request, title): return render(request, "encyclopedia/wiki.html", { "entries": util.get_entry(title) }) def search(request): entries = util.list_entries() query = request.session['query'] find_entries = list() search_box = request.POST.get("q", "").capitalize() if search_box in entries: return HttpResponseRedirect(f"wiki/{search_box}") for entry in entries: if re.search(query, entry): find_entries.append(entry) if find_entries: return … -
Django, Empty module name when adding urls
I have a Django rest framework API. When registering the following router and adding the URL patterns the following error rises: ... File "/home/yovel/PycharmProjects/scr/venv/lib/python3.8/site-packages/django/urls/conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1011, in _gcd_import File "<frozen importlib._bootstrap>", line 950, in _sanity_check ValueError: Empty module name URLs file: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api', include('farm_api.urls')) ] App's URLs file: from django.urls import include from rest_framework.routers import DefaultRouter from .views.group_view import GroupView group_router = DefaultRouter() group_router.register(prefix=r'groups', viewset=GroupView, basename='groups') urlpatterns = [ include('', group_router.urls) ] -
Update models.py from my views after check if some data exists
I'd like to fill my two columns in my database after check if some data exists. It was created a html page to check 'epass' value and if it exists, it should edit models to add "main_status","main_dt". ftForm.html <form action="{% url 'ft_new' %}" method="POST" enctype="multipart/form-data" style="width:70%;margin:0 auto;"> {% csrf_token %} <div class="form-row"> <div class="col"> <label for="epass">E-PASS</label> <input id="epass" class="form-control" type="text" name="epass" value=""> </div> </div> {% if messages %} <ul class="messages"> {% for message in messages %} <li class="{{ message.tags }}" style="color:red">{{ message }}</li> {% endfor %} </ul> {% endif %} <button type="submit" class="btn btn-info my-4 btn-block">Salvar</button> views.py def ft_new(request): form = EPASSForm(request.POST or None) if form.is_valid(): post = form.save(commit=False) epassForm = request.POST.get('epass') if FtMain.objects.filter(epass=epassForm): all = FtMain.objects.filter(epass=epassForm) post.epass = all.get('epass') post.insp_ymd = all.get('insp_ymd') post.line_nm = all.get('line_nm') post.model_code = all.get('model_code') post.pba_status = all.get('pba_status') post.pba_dt = all.get('pba_dt') post.main_status = 'Y' post.main_dt = datetime.now() post.bcr = all.get('bcr') form.save() messages.success(request, 'Salved with success') return redirect('ft_new') else: messages.error(request, 'There is no insppection') else: return HttpResponse('Page Error') return render(request,'control/ftForm.html',{'form':form}) models.py class FtMain(models.Model): insp_ymd = models.DateField(blank=True, null=True) line_nm = models.CharField(max_length=20, blank=True, null=True) model_code = models.CharField(max_length=20, blank=True, null=True) epass = models.CharField(max_length=25, blank=True, null=True) pba_status = models.CharField(max_length=20, blank=True, null=True) pba_dt = models.DateTimeField(blank=True, null=True) main_status = models.CharField(max_length=20, blank=True, null=True) main_dt … -
Django project error: TypeError: 'module' object is not subscriptable
I am learning about Django and Rest Framework, I have a little project to practice, but I have an error when trying to access http://localhost:8000/admin: TypeError: object 'module' is not subscribable. These are the Python files I created: admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.utils.translation import gettext as _ from . import models class UserAdmin(BaseUserAdmin): ordering = ['id'] list_display = ['email', 'name'] fieldsets = ( (None, {'fields': ('email', 'password')}), (_('Personal Info'), {'fields': ('name',)}), ( _('Permissions'), { 'fields': ( 'is_active', 'is_staff', 'is_superuser', ) } ), (_('Important dates'), {'fields': ('last_login',)}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2') }), ) admin.site.register(models.User, UserAdmin) models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, \ PermissionsMixin ... class User(AbstractBaseUser, PermissionsMixin): """Custom user model that supports using email instead of username""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email'