Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.db.utils.ProgrammingError: column tickets_ticket.track_code does not exist
I used postgresql and I want add a new field to my model: track_code = models.CharField(max_length=32, verbose_name=_('کد رهگیری'), default=generate_rrr_unique_trackcode) but after migrate i received this error: django.db.utils.ProgrammingError: column tickets_ticket.track_code does not exist LINE 1: SELECT (1) AS "a" FROM "tickets_ticket" WHERE "tickets_ticke... I used the command: python3 manage.py migrate app_name 0001 and delete the last migration file and then try again but not working... -
How to import csv or json file into the model & create taboe for that data
I've a csv/json file. I need to include the file as a database for the django app. & I need to show the data as a table in frontend. So can't understand where I should insert the file so that it create table for me. I've create a django web application. With a app. Just trying to import file intothe model but in dbsqlite there is no change. -
drf Writable nested serializers "This field is required."
Here is the code: Models.py class Question(models.Model): lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE, related_name='questions') question = models.CharField('lesson name', max_length=120) class Option(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='options') option = models.CharField('test option', max_length=100) correct = models.BooleanField(default=False) Views.py class QuestionAPIView(generics.CreateAPIView): queryset = Question.objects.all() serializer_class = QuestionSerializer Serializers.py class OptionSerializer(serializers.ModelSerializer): class Meta: model = Option fields = ('option', 'correct') class QuestionSerializer(serializers.ModelSerializer): options = OptionSerializer(many=True) class Meta: model = Question fields = ('lesson', 'question', 'options') def create(self, validated_data): options_data = validated_data.pop('options') question = Question.objects.create(**validated_data) for option_data in options_data: Option.objects.create(question=question, **option_data) return question I'm try create test question with few option of answers like this: data = { "lesson": 2, "question": "This is our first question?", "options": [ { "option": "Option 1", "correct": True }, { "option": "Option 2 ", "correct": False }, { "option": "Option 3", "correct": True } ] } But in postman and in the TestCase I've got: { "options": [ "This field is required." ] } What is the problem of validation? Documentation here https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers Thanks. -
How to return a value from javascript function to django template in the same view?
I am just getting a value from an input tag by javascript. But Now I need to pass this value to the Django template on the same page to do my required task. <!DOCTYPE HTML> <HTML> <body> <h1>In Django Template</h1> <input type="text" id="agency_id" name="fname" value="1"> <select class="select" name="delivery_agent" id="DeliveryAgent"> <option class="form-control" value="{{ agent.id }}" {% if agent.id == delivery_agency_id %} selected="selected" {% endif %}>{{ agent.name }} </option> {% endfor %} </select> <script> var delivery_agency_id = document.getElementById("agency_id").value; alert(delivery_agency_id ) </script> Here, I am getting the agency_id by script. Now I need to pass it to the if condition as above code. Please help me to solve it. -
Reset Avatar ImageField to Default when User Clear Avatar Through DRF or Django Admin
I have django model ImageField called avatar. I want to enable user clear their avatar, so Blank = True. The problem is when user clear their avatar, the ImageField path is now empty. What i want is, the ImageField back to default. models.py class Profile(models.Model): AVATAR_UPLOAD_TO = "account_avatar/" DEFAULT_AVATAR = "default.jpg" user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) avatar = sorl.thumbnail.ImageField(upload_to=AVATAR_UPLOAD_TO, default=AVATAR_UPLOAD_TO+DEFAULT_AVATAR, blank=True, null=True) I see some related questions Django ImageField overwrites existing path when empty. But the behaviour is not exactly what i want. This answer required the user to upload new avatar, so user couldn't clear their avatar. Another related questions Django - How to reset model fields to their default value?. But i can't implement the save() method on my models I have tried to implement save() method on Profile model, but it don't work as expected def save(self, *args, **kwargs): if not self.avatar.name: setattr(self, 'avatar.name', self.avatar.field.default) super().save(*args, **kwargs) # Call the "real" save() method. I am new to Django and Django Rest Framework. Please help me, i stuck with this problem from a few days ago. Could you please help with my problems. Thanks in advance! -
Share env across GitHub Actions workflows
I have a GitHub Action (test-python.yml) intended to test a Django application. It utilizes the env tag like so towards the top of the file: env: SECRET_KEY: test DEBUG: False ... I want to make another workflow - not a job in the same workflow - that is reliant on the same variables. I could obviously just make another file for said workflow and copy the env however this seems slightly flaky, I'd rather somehow share the env variables across numerous workflows so I only have to keep it up to date in one place. Is there a way to do this? Thank you in advance! -
I am developing ecommerce website from django. While integrating payment on the project and running the server I got page not found error (404)
The error I got while I enter the customer detail and click on checkout: This is my views.py of payment. Here I have imported stripe module using stripe api and created checkout session: from django.shortcuts import render, redirect, reverse, get_object_or_404 from decimal import Decimal import stripe from django.conf import settings from orders.models import Order # Create your views here. stripe.api_key = settings.STRIPE_SECRET_KEY stripe.api_version = settings.STRIPE_API_VERSION def payment_process(request): order_id = request.session.get('order_id', None) order = get_object_or_404(Order, id=order_id) if request.method == 'POST': success_url = request.build_absolute_uri(reverse('payment:completed')) cancel_url = request.build_absolute_uri(reverse('payment:canceled')) session_data = { 'mode': 'payment', 'client_reference_id': order_id, 'success_url': success_url, 'cancel_url': cancel_url, 'line_items': [] } for item in order.items.all(): session_data['line_items'].append({ 'price_data': { 'unit_amount': int(item.price * Decimal(100)), 'currency': 'usd', 'product_data': { 'name': item.product.name, }, }, 'quantity': item.quantity, }) session = stripe.checkout.Session.create(**session_data) return redirect(session.url, code=303) else: return render(request, 'payment/process.html', locals()) def payment_completed(request): return render(request, 'payment/completed.html') def payment_canceled(request): return render(request, 'payment/canceled.html') This is urls.py of payment where I have created URL patterns for process where the order summary is displayed, stripe checkout session. completed for the successfull payment and canceled for payment cancelation. : from django.urls import path from . import views app_name = 'payment' urlpatterns = [ path('canceled/', views.payment_canceled, name='canceled'), path('completed/', views.payment_completed, name='completed'), path('process/', views.payment_process, name='process'), ] This … -
How to run external python file and show data in front end of django in the form of table
Hi Guys I want to run my external py scipt and the output will be on json I want to show the data in form of rows and table in front end, the data is dynamic regression testing data. how to I show that using django -
What is the best way to parse this request.data in drf, when the request is form-data?
I have this form which sends an image along with some other data. I am using django-rest-framework in the back end. I need to take out couple of fields from this form input and do some operations and use the remaining fields to send to my ModelSerializer for posting the form data. What is the best way to achieve this? <QueryDict: {'areaName': ['Mall-24F'], 'devices': ['[\n {\n "name": "device_001",\n "coordinates": [\n 23,\n 56\n ],\n },\n {\n "name": "device_002",\n "coordinates": [\n 24,\n 57\n ],\n },\n {\n "name": "device_003",\n "coordinates": [\n 25,\n 58\n ],\n }\n]'], 'floorMap': [<InMemoryUploadedFile: 1653650801973.png (image/png)>]}> This is how request.data looks like. What I have tried doing is context = request.data context["name"] = context.pop("areaName")[0] context["floor_map"] = context.pop("floorMap")[0] Basically I only want "name" and "floor_map" to be sent to ModelSerializer. I have read that request.data is immutable, but here it is mutable. I think I am missing something. -
Heroku: python version problems
I am trying to deploy a Django app on Heroku, but I am having compatibility issues with the requirements.txt file, it specifies "python-3.11.1". According to Heroku's documentation, Heroku stack 22 supports Python 3.11.1. But each time I try to deploy using the Heroku CLI, I get an error message. -----> Building on the Heroku-22 stack -----> Using buildpack: heroku/python -----> Python app detected -----> Using Python version specified in runtime.txt Traceback (most recent call last): File "/tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/vendor/runtime-fixer", line 8, in <module> r = f.read().strip() File "/usr/lib/python3.10/codecs.py", line 322, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte /tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/bin/steps/python: line 9: warning: command substitution: ignored null byte in input ! Requested runtime '��python-3.11.1 ! For supported versions, see: https://devcenter.heroku.com/articles/python-support ! Push rejected, failed to compile Python app. ! Push failed I tried git push heroku master I have followed the buildpack checking tutorial in the documentation: heroku buildpacks heroku buildpacks:clear heroku buildpacks:add heroku/python -
My Paginator not working at the last page button
when click next and previous button is working, but the last page not working model.py class VenueForm(ModelForm): class Meta: model = Venue fields = ( 'name', 'address', 'zip_code', 'phone', 'web', 'email_address' ) labels = { 'name': '', 'address': '', 'zip_code': '', 'phone': '', 'web': '', 'email_address': '', } widgets = { 'name': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Venue Name'}), 'address': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Address'}), 'zip_code': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Zip Code'}), 'phone': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Phone'}), 'web': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Web'}), 'email_address': forms.EmailInput( attrs={'class': 'form-control', 'placeholder': 'Email'}), } view.py from .models import Event, Venue from django.core.paginator import Paginator def list_venues(request): venue_list = Venue.objects.all() p = Paginator(Venue.objects.all(), 3) page = request.GET.get('page') venues = p.get_page(page) nums = "a" * venues.paginator.num_pages return render(request, 'events/venue.html', { 'venue_list': venue_list, 'venues': venues, 'nums': nums}) events/venue.html <nav aria-label="Page navigation example"> <ul class="pagination justify-content-center"> {% if venues.has_previous %} <li class="page-item"> <a class="page-link" href="?page=1">&laquo; First</a> </li> <li class="page-item"> <a class="page-link" href="?page={{ venues.previous_page_number }}">Previous</a> </li> {% endif %} {% for i in nums %} <li class="page-item"> <a class="page-link" href="?page={{ forloop.counter }}">{{ forloop.counter }} </a> </li> {% endfor %} {% if venues.has_next %} <li class="page-item"> <a class="page-link" href="?page={{ venues.next_page_number }}">Next</a> </li> <li class="page-item"> <a class="page-link" href="?page={{ venues.paginator.num_pages ))">Last &raquo;</a> … -
Force login not working with fixtures (Django TestCase)
I'm populating my test db via a fixture, and everything loads fine. However, I'm unable to get either login or force_login to work. User is also in the fixture. When I try to test the first view, it redirects to the login page. class TestUnauthUser(TestCase): fixtures = ['project.json'] @classmethod def setUpTestData(cls): cls.client = Client() # Get User and Login cls.unauth_user = User.objects.get(username='unauth_user') print(cls.unauth_user.pk) #cls.login = cls.client.login(username=cls.unauth_user.username, password=cls.unauth_user.password) cls.client.force_login(cls.unauth_user) # Get Project cls.project = Project.objects.get(slug='test-project') cls.slug_dict = {'slug': cls.project.slug} # Get Task cls.task = Task.objects.get(slug='test-task') def test_login(self): self.assertTrue(self.unauth_user.login) def test_project_view(self): # Project Main response = self.client.get(reverse('customerportal:project', kwargs=self.slug_dict)) self.assertEqual(response.status_code, 403) I'm able to verify that I have the correct user object with: print(cls.unauth_user.pk). So the User exists and is being obtained. But, it's still not logging-in successfully. -
Is there a way to do {% url 'blog' blog[i].slug %} in Django?
I want to make this type of loops: {% for i in length %} where lenth = range(len(blogs)) in views.py. And then into that loop I want to do: <a href="{% url 'single_blog' blogs[i].slug %}"> blogs go from views.py too: blogs = Blog.objects.all() But it shows an error, it says it can't use [i] in this construction. Please let me know, how can I use blogs[i] in Django HTML? Thanks. -
Preserve and display Django form inputs on POST submission
--PROBLEM-- I have created a basic calculator using Django. The app takes some basic form inputs before executing some calculations and returning the outcomes to the user, however I want the user's inputs to remain visible in the form on submission. At present the followin experience occurs. User enters values into form and submits using 'Calculate' button. Results are returned as expected but form and values are no longer present. User can press 'Calculate' button to return to start of process and blank form. --DESIRED OUTCOME-- --CODE-- forms.py from django import forms class InvestmentForm(forms.Form): starting_amount = forms.FloatField() number_of_years = forms.FloatField() return_rate = forms.FloatField() annual_additional_contribution = forms.FloatField() views.py from django.shortcuts import render from django.views import View from .forms import InvestmentForm class Index(View): def get(self, request): form = InvestmentForm() return render(request, 'loancalculator/index.html', {'form': form}) def post(self, request): form = InvestmentForm(request.POST) if form.is_valid(): total_result = form.cleaned_data['starting_amount'] total_interest = 0 yearly_results = {} for i in range(1, int(form.cleaned_data['number_of_years'] +1)): yearly_results[i] = {} # CALCULATE THE INTEREST interest = total_result * (form.cleaned_data['return_rate'] / 100) total_result += interest total_interest += interest # ADDITIONAL CONTRIBUTION total_result += form.cleaned_data['annual_additional_contribution'] # SET YEARLY RESULTS yearly_results[i]['interest'] = round(total_interest, 2) yearly_results[i]['total'] = round(total_result,2) # CREATE CONTEXT context = { 'total_result': round(total_result,2), … -
With a Django QuerySet, how to get a list of the included columns?
In the application context, we have a dynamic QuerySet that may return variable number of columns, e.g. date_of_birth in type Date, and/or postalcode in type Text, etc. We wonder how to get a list of the columns included in the QuerySet, including: the column's name the datatype of the column corresponding to the serializer fields of serializers.IntegerField, serializers.DateTimeField, etc. We appreciate hints and suggestions. -
TypeError: unhashable type: 'dict' in Django
I',m working on django rest project and i'm getting an err, i'm getting an error can anyone help, below is my code & d err msg def get(self, request, reference): transaction = walletTransaction.objects.get( paystack_payment_reference=reference, wallet__user=request.user) reference = transaction.paystack_payment_reference url = 'https://api.paystack.co/transaction/verify/{}'.format(reference) headers = { {"authorization": f"Bearer {settings.PAYSTACK_SECRET_KEY}"} } r = requests.get(url, headers=headers) err message File "/home/olaneat/Desktop/files/project/django/jobConnect/job-connect/wallet/serializers.py", line 59, in save headers = { TypeError: unhashable type: 'dict' can anyone help pls -
crispy_forms is not working : ModuleNotFoundError: No module named 'crispy_forms'
Steps that I followed pip install django-crispy-forms add inside setting.py INSTALLED_APPS = [ ... 'crispy_forms', ... ] and CRISPY_TEMPLATE_PACK = 'uni_form' press the run icon of pycharm (top right) I tried to install pip install -e git+git://github.com/maraujop/django-crispy-forms.git#egg=django-crispy-forms I tried to make a migration but same error. I tried to install with pipenv install django-crispy-forms. I don't have the error if I do : "python3 manage.py runserver" but crispy-forms doesn't work ERROR : ... File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'crispy_forms' -
Django simplejwt validate token
I am implementing authentication with Django simpleJwt, and have a question. I want to create something with Client's jwt token. I use methods provided from simpleJwt to validate and decode jwt token. class AccountBookAPIView(APIView): def post(self, request): jwt_authenticator = JWTAuthentication() raw_access_token = request.META.get('access_token') validated_token = jwt_authenticator.get_validated_token(raw_access_token) user = jwt_authenticator.get_user(validated_token) However, I doubt that some methods really validate token. So I checked the method's implementation. Below is the code for question. def get_validated_token(self, raw_token): """ Validates an encoded JSON web token and returns a validated token wrapper object. """ messages = [] for AuthToken in api_settings.AUTH_TOKEN_CLASSES: try: return AuthToken(raw_token) except TokenError as e: messages.append( { "token_class": AuthToken.__name__, "token_type": AuthToken.token_type, "message": e.args[0], } ) raise InvalidToken( { "detail": _("Given token not valid for any token type"), "messages": messages, } ) # this class is AuthToken in my opinion. class AccessToken(Token): token_type = "access" lifetime = api_settings.ACCESS_TOKEN_LIFETIME I can't find the point that validate token from Database. It looks like just construction of token for me. Don't I need to check token in the Database(blacklist and outstanding tokens)? Plz help me. Any answer is welcome. Below is my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # my apps 'members', 'account_books', … -
WSGI django ModuleNotFoundError: No module named 'django'
I have been trying forever to get my django api to deploy via apache. I have installed mod_wsgi for python 3.7 and my venv is using python 3.7.15. Trying to go to my django app url I am getting a 500 error. Error log shows: [Tue Dec 20 21:31:30.690951 2022] [:error] [pid 19216] /usr [Tue Dec 20 21:31:30.691287 2022] [:error] [pid 19216] mod_wsgi (pid=19216): Target WSGI script '.../project/project/wsgi.py' cannot be loaded as Python module. [Tue Dec 20 21:31:30.691323 2022] [:error] [pid 19216] mod_wsgi (pid=19216): Exception occurred processing WSGI script '.../project/project/wsgi.py'. [Tue Dec 20 21:31:30.691393 2022] [:error] [pid 19216] Traceback (most recent call last): [Tue Dec 20 21:31:30.691423 2022] [:error] [pid 19216] File ".../project/project/wsgi.py", line 19, in <module> [Tue Dec 20 21:31:30.691428 2022] [:error] [pid 19216] from django.core.wsgi import get_wsgi_application [Tue Dec 20 21:31:30.691444 2022] [:error] [pid 19216] ModuleNotFoundError: No module named 'django' [Tue Dec 20 21:31:51.190670 2022] [:error] [pid 19217] 3.7.15 (default, Oct 31 2022, 22:44:31) [Tue Dec 20 21:31:51.190707 2022] [:error] [pid 19217] [GCC 7.3.1 20180712 (Red Hat 7.3.1-15)] apache conf file: <VirtualHost *:80> ServerName api.project.com DocumentRoot path/to/project/root WSGIScriptAlias / /path/to/wsgi.py WSGIDaemonProcess project-name processes=4 threads=1 display-name=%{GROUP} python-path=path/to/lib/python3.7/site-packages:/path/to/project/root WSGIProcessGroup project-group <Directory "/path/to/project/root"> Require all granted </Directory> #SSL stuff... </VirtualHost> wsgi.py: … -
django redirect to subdomain with exact same url
I have a Django website accessible at codewithbishal.com. This is basically a django blog website and all the blog articles are accessible at codewithbishal.com/example/<path> But now I want to completely restructure the website{such that it is accessible at blog.codewithbishal.com/<path>} and I do no want to lose the current SEO therefore I want to configure django redirect such that when someone launches codewithbishal.com/example/<path> through google search search result or directly through link, they are redirected to blog.codewithbishal.com/<path> instead of a 404 page and eventually google will start showing the new links instead of old once. -
Creating a simple multiple users app in Django
So I've created 3 different users: admins, developers, and project managers. When I use the individual signup forms for each of these users and log out, it works, but then I when try to use the login form, it seems to me that it's acting like the signup form. Because when I input the same user details as the one I just created into the login form, it throws up the built-in error message, 'A user with that user name already exists' I'm not sure how to proceed from here. Here's what I have so far. models.py class CustomUser(AbstractUser): ACCOUNT_TYPE_CHOICES = ( ('admin', 'Admin'), ('developer', 'Developer'), ('project_manager', 'Project Manager') ) account_type = models.CharField(max_length=20, choices=ACCOUNT_TYPE_CHOICES) login and signupviews class LoginView(View): def get(self, request): # Render the login form form = LoginForm() return render(request, 'users/login.html', {'form': form}) def post(self, request): # Get the form data from the request form = LoginForm(request.POST) # Validate the form data if form.is_valid(): # Get the username and password from the form username = form.cleaned_data['username'] password = form.cleaned_data['password'] # Authenticate the user user = authenticate(request, username=username, password=password) # If the user is authenticated, log them in and redirect to the homepage if user is not None: login(request, … -
Django-admin startproject
I am new to django and I tried to create a project with django-admin startproject command. The tutorial I was referring to had no errors while going through this command but I get the following error. The tutorial and I are not doing it in any virtual environment. Though this error comes, the files and folder is created in the directory I am working in, how should I solve this error? Traceback (most recent call last): File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 197, in run_module_as_main return run_code(code, main_globals, None, File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 87, in run_code exec(code, run_globals) File "C:\Users\username\AppData\Local\Programs\Python\Python39\Scripts\django-admin.exe_main.py", line 7, in <module> File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management_init.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management_init.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\startproject.py", line 21, in handle super().handle("project", project_name, target, **options) File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\templates.py", line 225, in handle run_formatters([top_dir]) File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\utils.py", line 165, in run_formatters subprocess.run( File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 501, in run with Popen(*popenargs, **kwargs) as process: File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 947, in init self._execute_child(args, executable, preexec_fn, close_fds, File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 1416, in _execute_child hp, ht, pid, tid = _winapi.CreateProcess(executable, args, PermissionError: [WinError 5] Access is denied -
Django Admin doesn't recognise blank=True in model
When I try to edit a user (using a custom UserChangeForm) in the Django admin panel, validation insists that fields I have set blank=True in the model are required. I don't know where to begin solving this; I had the same issue with the CustomUserCreationForm but reverted to using the default which works as expected (asks for username, password1 & password2, creates the user with blank display_name, bio and profile_picture fields). models.py: from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): display_name = models.CharField(max_length=30, blank=True, null=True) bio = models.TextField(blank=True, null=True) profile_picture = models.ImageField(upload_to='images/', blank=True, null=True) def save(self, *args, **kwargs): if not self.display_name: self.display_name = self.username super().save(*args, **kwargs) def __str__(self): return self.username forms.py: from django import forms from django.contrib.auth.forms import UserChangeForm from .models import CustomUser class CustomUserChangeForm(UserChangeForm): display_name = forms.CharField(label="display_name") bio = forms.CharField(widget=forms.Textarea) profile_picture = forms.ImageField(label="profile_picture") class Meta(): model = CustomUser fields = ("username", "email", "display_name", "bio", "profile_picture") admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .forms import CustomUserChangeForm from .models import CustomUser class CustomUserAdmin(UserAdmin): form = CustomUserChangeForm fieldsets = ( (None, {'fields': ('username', 'password', 'email', 'display_name', 'bio', 'profile_picture')} ), ) model = CustomUser list_display = ["username", "email",] admin.site.register(CustomUser, CustomUserAdmin) -
'NoneType' object has no attribute 'strip' - CS50W Wiki
I'm getting this error while trying to create a search function in Django. This is where I'm having trouble: 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 ytho, then Python should appear in the search results. This is the view: def search(request): if request.method == 'POST': search_title = request.POST['q'] content = converter(search_title) if search_title is not None: return render(request, "encyclopedia/entry.html", { "entry": content, "entryTitle": search_title }) else: entries = util.list_entries() search_pages = [] for entry in entries: if search_title in entries: search_pages.append(entry) return render(request, "encyclopedia/search.html",{ "entries": search_pages }) And the HTML: <form action="{% url 'search' %}" method="POST"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> Traceback: Traceback (most recent call last): File "C:\Users\anshi.virtualenvs\storefront-bp3LZ8Cr\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\anshi.virtualenvs\storefront-bp3LZ8Cr\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Python\Py Projects\CS50 attempt 00\wiki\encyclopedia\views.py", line 70, in search content = converter(search_title) File "D:\Python\Py Projects\CS50 attempt 00\wiki\encyclopedia\views.py", line 19, in converter html = Markdowner.convert(content) File "C:\Users\anshi.virtualenvs\storefront-bp3LZ8Cr\lib\site-packages\markdown\core.py", line 248, in convert … -
Adding widgets to django form does not update the forms
So I have a login form for which I am trying to edit the css attributes. However I cannot seem to find the correct solution. Below is my views.py, forms.py and html snippet accordingly. def index(request): context = {} if request.method == 'POST': form = LoginForm(data=request.POST) context['form'] = form logging.debug(form.is_valid()) logging.debug(form.cleaned_data) logging.debug(form.errors) if form.is_valid(): logging.debug("form valid") username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') if authenticate(username, password): logging.debug("logged IN") messages.success(request, f' welcome {username} !!') return redirect('loggedIn') else: logging.debug("wrong!") messages.info(request, f'Password or Username is wrong. Please try again.') form = AuthenticationForm() return render(request, "index_logged_out.html", {"form": form}) class LoginForm(forms.ModelForm): class Meta: model = WebsiteRegistrant fields = ['username', 'password',] widgets = { 'username': TextInput(attrs={ 'class': "form-control", 'style': 'max-width: 300px;', 'placeholder': 'Username' }), 'password': PasswordInput(attrs={ 'class': "form-control", 'style': 'max-width: 300px;', 'placeholder': 'Password' }) } <form method="POST"> {% csrf_token %} <center> <div class="form-group" style = "margin-bottom: 10px; width: 300px"> {{ form.password }} </div> <div class="form-group" style = "margin-bottom: 10px; width: 300px"> {{ form.password }} </div> <button class="btn btn-primary btn-block fa-lg gradient-custom-2 mb-3" type="submit" style="width: 300px;">Login</button> </center> </form> Any idea what I am doing wrong or what I could fix in order to add the class name and attributes as I have defined in the form widget? Thanks