Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Showing specific model data in html - Django
I am creating a donation application that allows donors to donate stuff. I have a screen, called availablesupplies.html which renders out all of the donations from the database using a for loop. Each donation is displayed in a user-friendly way, and contains a button that allows them to see details about that specific donation. When the button is clicked, the user is redirected to a page, which I want to contain details about the donation that they clicked on My problem is that I can't figure out how to display a specific donation from my models, for example if my user clicked on an apple donation, I want to get the details for this donation and display it on another page My code: Donation Model: class Donation(models.Model): title = models.CharField(max_length=30) phonenumber = models.CharField(max_length=12) category = models.CharField(max_length=20) quantity = models.IntegerField(blank=True, null=True,) HTML (this is where I want to render out the model data): {% extends 'suppliesbase.html' %} {% load static %} {% block content %} <div class="row"> <div class="col-lg-12"> <div class="box-element"> <a class="btn btn-outline-dark" href="/availablesupplies/">&#x2190; Back</a> <br> <br> <table class="table"> <tr> <th><h5>Date Posted: <strong>Date</strong></h5></th> <th><h5>Donor:<strong> User</strong></h5></th> <th> <a style="float:right; margin:5px;" class="btn btn-success" href="">Accept</a> </th> </tr> </table> </div> <br> <div class="box-element"> <div … -
Extending Django field raises exception in constructor
I have the following "custom" field: from django.db.models import DecimalField class CurrencyField(DecimalField): def __init__(self): super(DecimalField, self).__init__(max_digits=30, decimal_places=8) Where the constructor for DecimalField is: class DecimalField(Field): def __init__(self, verbose_name=None, name=None, max_digits=None, decimal_places=None, **kwargs): self.max_digits, self.decimal_places = max_digits, decimal_places super().__init__(verbose_name, name, **kwargs) Yet I'm getting: File "/x/x/custom_fields.py", line 13, in __init__ super(DecimalField, self).__init__(max_digits=30, decimal_places=8) TypeError: __init__() got an unexpected keyword argument 'max_digits' Why? -
Django how to write a function for changing user password
I want to write a function for changing the user's password after the first login, so I tried the following code. from django.contrib.auth import update_session_auth_hash from django.contrib.auth.forms import PasswordChangeForm from django.contrib.auth.decorators import login_required @login_required def change_password(request): if request.method == "POST": form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) return redirect("change_password") else: form = PasswordChangeForm(request.user) return render(request, "Authentication/change_password.html", {"form": form}) So, everything works fine, but when I type the old password and new passwords and submit the form, I get a popup dialog box with a list of my users that tells select which login to update. However, I am logged in as an active user. -
How to solve IntegrityError
I tried to write a review in a form,but after submitting the form it shows an error.I tried different ways to solve this issue but in vein.Actually I create a review form in such a way that any user can submit their review using this form or they can update their previous review.Here I used try and except methods.Can anyone suggest a solution for this. I got a Traceback like this: Internal Server Error: /User_Reviews/5 Traceback (most recent call last): File "D:\Project\movie_project\movie\review\views.py", line 42, in user_reviews ureview = reviews.objects.get( movie__id=movies_id,user__id=request.user.id) File "D:\Project\movie_project\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "D:\Project\movie_project\venv\lib\site-packages\django\db\models\query.py", line 435, in get raise self.model.DoesNotExist( review.models.reviews.DoesNotExist: reviews matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\Project\movie_project\venv\lib\site-packages\django\db\backends\mysql\base.py", line 73, in execute return self.cursor.execute(query, args) File "D:\Project\movie_project\venv\lib\site-packages\MySQLdb\cursors.py", line 209, in execute res = self._query(query) File "D:\Project\movie_project\venv\lib\site-packages\MySQLdb\cursors.py", line 315, in _query db.query(q) File "D:\Project\movie_project\venv\lib\site-packages\MySQLdb\connections.py", line 239, in query _mysql.connection.query(self, query) MySQLdb._exceptions.OperationalError: (1048, "Column 'movie_id' cannot be null") During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\Project\movie_project\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\Project\movie_project\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = … -
Cant resolve src/index.js
I've been trying to build a react app and I am encountering this error when I run my npm. My webpack.config file contains:- module.exports = { module: { rules: [ { test:/\.js$/, exclude: /node_modules/, use: { loader: "babel-loader" } } ] } } My package.json file contains:- { "name": "leadmanager", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev": "webpack --mode development ./leadmanager/frontend/src/index.js --output-path ./leadmanager/frontend/static/frontend/main.js", "build": "webpack --mode production ./leadmanager/frontend/src/index.js --output-path ./leadmanager/frontend/static/frontend/main.js" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.14.6", "@babel/preset-env": "^7.14.7", "@babel/preset-react": "^7.14.5", "babel-loader": "^8.2.2", "babel-plugin-transform-class-properties": "^6.24.1", "webpack": "^5.44.0", "webpack-cli": "^4.7.2" }, "dependencies": { "prop-types": "^15.7.2", "react": "^17.0.2", "react-dom": "^17.0.2" } } My file hierarchy looks like this:- I have tried lot of methods but none of them work. Please help -
How do I open my edit complaint page for one specific complaint in django
I have a view complaints page where a user can view the complaints he/she have submitted. When the user clicks on one of the cards, I need a new page to open where the user can view the details of that complaint and edit it as well. It should go from here: to here: Where they can view details and make changes as well: This is my models.py: class Complaint(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) id = models.AutoField(blank=False, primary_key=True) reportnumber = models.CharField(max_length=500 ,null = True, blank= False) eventdate = models.DateField(null=True, blank=False) event_type = models.CharField(max_length=300, null=True, blank=True) device_problem = models.CharField(max_length=300, null=True, blank=True) manufacturer = models.CharField(max_length=300, null=True, blank=True) product_code = models.CharField(max_length=300, null=True, blank=True) brand_name = models.CharField(max_length = 300, null=True, blank=True) exemption = models.CharField(max_length=300, null=True, blank=True) patient_problem = models.CharField(max_length=500, null=True, blank=True) event_text = models.TextField(null=True, blank= True) document = models.FileField(upload_to='static/documents', blank=True, null=True) def __str__(self): return self.reportnumber views.py: def EditComplaints(request): complaint = request.user.complaint form = ComplaintForm(instance=complaint) if request.method == 'POST': form = ComplaintForm(request.POST, request.FILES, instance=complaint) if form.is_valid(): form.save() context = {'form': form} return render(request, 'newcomplaint.html', context) template (the view history page): <div class="col right-pro-con"> <div class="img-cir"> <form method='POST' action="" enctype="multipart/form-data"> {% csrf_token %} {% if request.user.profile.profile_pic.url %} <img src={{request.user.profile.profile_pic.url}} alt="" width="100px" … -
Django - Got KeyError when attempting to get a value for field `address` on serializer `RegistrationSerializer`
I 'm trying to build a view to create a new user. In this view I call a serializer which must use 2 different tables Here is the request : { "email": "email@example.com", "name": "name", "surname": "surname", "phone": "0601234567", "password": "azerty", "address": { "osm": "N65719518", "lat": 18.072, "lon": 36.087, "street": "Name of the street", "postalCode": 123456, "city": "name of the city" } } I would like to separate the "address" field from my query which corresponds to another table. For this I use the pop method in my serializer Here is my serializer : serializers.py class AddressSerializer(serializers.ModelSerializer): class Meta: model = Address fields = '__all__' class RegistrationSerializer(serializers.ModelSerializer): """Create an account""" address = AddressSerializer() class Meta: model = User exclude = ['joined', 'lastLogin', 'is_staff', 'is_superuser', 'is_admin', 'is_active'] extra_kwargs = { # For security to hide the password (we can't read it) 'password': {'write_only': True}, } def save(self): # Pop the address of the user address = self.validated_data.pop("address") user = User.objects.create(**self.validated_data) user.set_password(self.validated_data['password']) user.save() Address.objects.create(user=user, **address) token = Token.objects.get(user=user) confirmation(user, token.key) return user Here is the view in which I call my serializer : views.py class HandleUsers(HandleUsersView): def post(self, request): """For everyone""" serializer = RegistrationSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() token = Token.objects.get(user=user).key … -
Django rest framework - Serializer always returns empty object ({})
I am creating first rest api in django using django rest framework I am unable to get object in json format. Serializer always returns empty object {} models.py class Shop(models.Model): id = models.PositiveIntegerField(unique=True) name = models.CharField(max_length=1000) address = models.CharField(max_length=4000) serializers.py class ShopSerializer(serializers.Serializer): class Meta: model = Shop fields = '__all__' views.py @api_view(['GET']) def auth(request): username = request.data['username'] password = request.data['password'] statusCode = status.HTTP_200_OK try: user = authenticate(username=username, password=password) if user: if user.is_active: context_data = request.data shop = Shop.objects.get(id = username) shop_data = ShopSerializer(shop).data if shop: print(shop_data) else: print('false') else: pass else: context_data = { "Error": { "status": 401, "message": "Invalid credentials", } } statusCode = status.HTTP_401_UNAUTHORIZED except Exception as e: pass return Response(context_data, status=statusCode) When i try to print print(shop_data) it always returns empty object Any help, why object is empty rather than returning Shop object in json format? -
Why my django server throws an error of invalid datatype?
Whenever i called my booking function with a post method in that it throws me an error of 'Invalid Data Type it expected dict but its an int'. So when i debug that i found a problem in my serializers so Please help me to resolve the error model.py class Booking(models.Model): details = models.ForeignKey(PersonalDetails, on_delete=models.CASCADE) quantity = models.IntegerField(null=False) total_amount = models.IntegerField() show = models.ForeignKey(ShowTime, on_delete=models.CASCADE) def __str__(self) -> str: return self.total_amount views.py class BookingTicketsQuery(APIView): permission_classes = [IsAuthenticated] def get(self, request, format=None): booking_id = request.query_params.get('booking_no', None) if booking_id is not None: queryset = Booking.objects.get(id=booking_id) else: return Response("invalid", status=status.HTTP_409_CONFLICT) seriliazer = BookingSerializer(queryset) return Response(seriliazer.data) def post(self, request, format=None): recieve_data = JSONParser().parse(request) showtime = ShowTime.objects.get(id=recieve_data['show']) print(showtime) if recieve_data['quantity'] > (showtime.total_seats - showtime.booked_seats): return Response("Error: No seats available", status=status.HTTP_409_CONFLICT) recieve_data['total_amount'] = showtime.total_price * \ recieve_data['quantity'] showtime.booked_seats += recieve_data['quantity'] showtime.save() serializer = BookingSerializer(data=recieve_data) if serializer.is_valid(): booking_obj = serializer.save() return Response(booking_obj.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class ShowMovieSerializer(serializers.ModelSerializer): cinema = CinemaSerializer() movie = MovieSerializer() class Meta: model = ShowTime fields = ('id', 'show_start_time', 'show_end_time', 'total_seats', 'booked_seats', 'cinema', 'movie') class BookingSerializer(serializers.ModelSerializer): show = ShowMovieSerializer() details = PersonalDetailsSerializer() class Meta: model = Booking fields = ('id', 'total_amount', 'quantity', 'details', 'show') my post data: { "details": 1, "quantity":1, "show":1 … -
No Procfile and no package.json file found in Current Directory - See run-foreman.js
I am trying to deploy a django app to heroku, and it is causing me errors. In the process of debugging when I run the command heroku local web -f Procfile.windows it shows me the following error: [FAIL] No Procfile and no package.json file found in Current Directory - See run-foreman.js --help From the application structure that is attached you can see that there is the Proc file and the content of the Procfile is as following: web: gunicorn klaviyo_integration.wsgi --log-file - Any guesses what might be wrong? And I am using Windows as OS, in case there is a problem with gunicorn on that sense. -
ModuleNotFoundError: No module named 'settings'
I had django project that was working just fine but I take all the apps and I copied them and pasted them in a new project so I got this. At first it was showing No module named 'backend' but I made few changes and now it shows this. The problem is the error message doesn't show where I mentioned a module named settings. So, how to know where is this mudle in my files? Traceback (most recent call last): File "/Users/apple/Desktop/vytrac-24106/backend/manage.py", line 21, in <module> main() File "/Users/apple/Desktop/vytrac-24106/backend/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/apple/.pyenv/versions/3.9.0/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Users/apple/.pyenv/versions/3.9.0/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/apple/.pyenv/versions/3.9.0/lib/python3.9/site-packages/django/core/management/base.py", line 367, in run_from_argv connections.close_all() File "/Users/apple/.pyenv/versions/3.9.0/lib/python3.9/site-packages/django/db/utils.py", line 208, in close_all for alias in self: File "/Users/apple/.pyenv/versions/3.9.0/lib/python3.9/site-packages/django/utils/connection.py", line 73, in __iter__ return iter(self.settings) File "/Users/apple/.pyenv/versions/3.9.0/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/apple/.pyenv/versions/3.9.0/lib/python3.9/site-packages/django/utils/connection.py", line 45, in settings self._settings = self.configure_settings(self._settings) File "/Users/apple/.pyenv/versions/3.9.0/lib/python3.9/site-packages/django/db/utils.py", line 144, in configure_settings databases = super().configure_settings(databases) File "/Users/apple/.pyenv/versions/3.9.0/lib/python3.9/site-packages/django/utils/connection.py", line 50, in configure_settings settings = getattr(django_settings, self.settings_name) File "/Users/apple/.pyenv/versions/3.9.0/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/Users/apple/.pyenv/versions/3.9.0/lib/python3.9/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/Users/apple/.pyenv/versions/3.9.0/lib/python3.9/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Users/apple/.pyenv/versions/3.9.0/lib/python3.9/importlib/__init__.py", line … -
Why do I fail Django migration in heroku server while succeeding in local server?
So I have deployed my Django project to Heroku, and now trying to migrate the database. I have everything working fine in my local sever. Then I tried to run the commands in heroku, as below. python manage.py makemigrations This worked fine. Migrations for 'app_name': contents\migrations\0001_initial.py - Create model Book - Create model Category - Create model Content Then of course, I tried : git add .git commit -m "migration" git push heroku master heroku run python manage.py migrate app_name But then I got this error CommandError: App 'app_name' does not have migrations. Strange thing is, after running python manage.py migrate, everything works fine in my local server. It's only the heroku server where the error occurs. I've done some research for possible issues, none of which were relevant to mine. For example I do have init.py in the migrations folder inside app_name directory. Also, I've tried heroku run python manage.py migrate as well as heroku run python manage.py migrate app_name but neither worked. I'm very confused. What do you think is the problem? Thanks in advance. :) -
I try to deploy my website in Django+Supervisor+NGINX on Ubuntu server 16.04
Here is my conf (supervisor): error massage FATAL Exited too quickly (process log may have details) ''' [program:gunicorn] directory=/home/ubuntu/allenon command=/home/ubuntu/env/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/allenon/app.sock AL-allenon.allenonproject.wsgi:application autostart=true autorestart=true stderr_logfile=/var/log/gunicorn/gunicorn.err.log stdout_logfile=/var/log/gunicorn/gunicorn.out.log [group:guni] programs:gunicorn ''' -
How to show model data in django template?
I am working on project and i have a problem with it.The problem is that django is not showing model data in template and i an unable to solve problem. Here is the models.py from django.db import models from django.contrib.auth.models import User from django.utils.timezone import now class videopost(models.Model): sno=models.AutoField(primary_key=True slug=models.CharField(max_length=130) title=models.CharField(max_length=255) image = models.ImageField(upload_to='staticfiles/images/') content=models.TextField() timeStamp=models.DateTimeField(blank=True) def__str__(self): return self.title Here is views.py def videoposts(request,slug): post=videopost.objects.filter(slug=slug).first() context={'post':post} return render(request,'videos/videopost.html',context) And here is template {% extends 'base.html' %} {% load static %} {% load embed_video_tags %} {% block title %}How to run python in mobile?{% endblock title %} {% block basecss%}"{% static '/css/home.css' %}" {% endblock basecss %} {% block extracss %}"{% static '/css/videos.css' %}" {% endblock extracss %} {% block classvideos%} current {% endblock classvideos %} {% block body %} {{post.content}} {{post.title}} {% endblock body %} -
unable to connect MongoDB with Django using PyMongo
Below issue is I'm facing while connecting the mongodb. Can someone help me out please Thanks Error============================ raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: 'pymongo' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' ======================================= Settings.py DATABASES = { 'default': { 'ENGINE': 'pymongo', 'NAME': 'workflow', 'HOST': 'localhost:27017/workflow', } } Views.py def dbconnection(): try: global _connection if _connection is None: client = MongoClient('mongodb://localhost:27017/', connect= False) db = client["workflow"] return db except Exception as ex: print(e , 'Exception') -
Django REST Framework: Updating via UpdateAPIView vs RetrieveUpdateDestroyAPIView / Prefilled Form in Browsable API
When I try to update a model instance via the generics.RetrieveUpdateDestroyAPIView I can see the instance's values prefilled in the form in the browsable API. However, when I use generics.UpdateAPIView I can't. Is this due to the fact that UpdateAPIView does not allow GET methods, so the view can't get the data to prefill the form or is there a special setting I need to add in my generics.UpdateAPIView to have the form prefilled automatically -
Related Field got invalid lookup while making a model relationship
I am trying to make relationships traversing through different models but am getting this error : django.core.exceptions.FieldError: Related Field got invalid lookup: occupational_group below are the models I have : class LoanApplication(models.Model, TimeStampedModel): loan_taker = models.ForeignKey( CustomerProfile, on_delete=models.PROTECT, null=True, blank=True, verbose_name=_('Customer Profile'), related_name='loan_entries') class CustomerProfile(models.Model, TimeStampedModel): is_copy_component = models.BooleanField( _('Is copy component'), default=False) cooperation_partner = models.ForeignKey( EmailUser, on_delete=models.PROTECT, null=True, blank=True, verbose_name=_('Jurisdiction'), related_name='partner_user_profile') user = models.OneToOneField( EmailUser, on_delete=models.PROTECT, null=True, blank=True, verbose_name=_('User'), related_name='user_profile') approval_inquiry_sent_at = models.DateTimeField( _('Approval inquiry sent at'), null=True, blank=True) email_content_customer = models.FileField( _('Content of the customer email'), upload_to="customer-emails/", blank=True) approved_at = models.DateTimeField( _('Approved at'), null=True, blank=True) class CustomerProfilePerson(models.Model, TimeStampedModel): person = models.ForeignKey( Person, on_delete=models.CASCADE, verbose_name=_('Person'), related_name='customer_profile_relation') customer_profile = models.ForeignKey( CustomerProfile, on_delete=models.CASCADE, verbose_name=_('Customer Profile'), related_name='persons') class Person(models.Model, TimeStampedModel): occupational_group = models.CharField( _('Occupational group'), max_length=16, blank=True, choices=OCCUPATIONAL_GROUP_CHOICES) Am trying to filter the LoanApplication model with the relationship of an occupation group, below is the list of the occupational group : OCCUPATIONAL_GROUP_CHOICES = ( ('pharmacist', _('Pharmacist')), ('architect', _('Architect')), ('doctor', _('Doctor')), ('consulting_eng', _('Consulting engineer')), ('notary', _('Notary')), ('psychotherapist', _('Psychotherapist')), ('lawyer', _('Lawyer')), ('tax_consultant', _('Tax Consultant')), ('vet', _('Vet')), ('sworn_auditor', _('Sworn auditor')), ('surveyor', _('Surveyor')), ('auditor', _('Auditor')), ('dentist', _('Dentist')), ('other', _('Other')), ) So this is my query below but failing : LoanApplication.objects.filter(loan_taker__persons_person_occupational_group__in: ['pharmacist']) Am getting this exception : … -
Deploying Django on IIS and ngrok
I am trying to deploy Django on local host and "tunnel" using ngrok. The ngrok works but the IIS (Internet Information Manager) gives 500 Error <handler> scriptProcessor could not be found in <fastCGI> application configuration. Reference into fastcgi shows that this feature is deprecated but what is the replacement for serving Django using local server and ngrok. I also pip installed pyngrok. Can you suggest a clear solution? -
Send API data from Backend to Frontend in real time with Django and React
I am working and I need your help. I am working on a website with Django with DRF on the backend and react on the frontend. I need a way of sending api data to the client whenever any changes are made. The data is only coming from the database, the client is only viewing the progress. What options do I have to acheive. I need it to handle a large number on people. Say 20 000. Please your help will do a lot for me. -
Password is not saving to data base after hashing
I am creating user registration api in django_rest_framework. I created a serializer and class view. but there is some problem with password. I use Registration class which inherits CreateAPIView to create user-registration and user a ModelSerializer to serialize it. Before saving the data, I validate email and passwords. Then I hashed the password with user.set_password(password) then saved it. when I try to register with the api it shows following error Error :- File "/home/rasheed/PycharmProjects/DRFtutor/myappclass/views.py", line 72, in post user = serializer.save() File "/home/rasheed/PycharmProjects/DRFtutor/myapp/serializers.py", line 36, in save user.set_password(password) File "/home/rasheed/PycharmProjects/env/lib/python3.8/site-packages/django/contrib/auth/base_user.py", line 99, in set_password self.password = make_password(raw_password) File "/home/rasheed/PycharmProjects/env/lib/python3.8/site-packages/django/contrib/auth/hashers.py", line 77, in make_password raise TypeError( TypeError: Password must be a string or bytes, got tuple. My serializers.py is :- class RegistrationSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True) class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password', 'password2'] extra_kwargs = {'password': {'write_only': True}} def save(self): user = User( username=self.validated_data['username'], first_name=self.validated_data['first_name'], last_name=self.validated_data['last_name'], ) password = self.validated_data['password'], password2 = self.validated_data['password2'], email = self.validated_data['email'], if password != password2: raise serializers.ValidationError({'password': 'Passwords dose not match.'}) elif User.objects.filter(email=email).exists(): raise serializers.ValidationError({'email': 'Email is already in use.'}) user.set_password(password) user.save() return user views.py is:- class Registration(CreateAPIView): queryset = User.objects.all() serializer_class = RegistrationSerializer def post(self, request, *args, **kwargs): … -
AttributeError: 'tuple' object has no attribute 'fetchall' in django
While join multiple sql query getting error -
Django - updating user account breaks the user password
I'm trying to set up an account update form, where a user can update its info but only when he/she provides its password at the end of the form. Unfortunately, when I try to update it (even with a correct password), I get logged off and I cannot log back in. I don't know why, but the password breaks completely and I have to reset it via shell. Also, when I look into the database, the password for each user that I tried to update, it's not hashed anymore, it's just in plain text. forms.py class UserProfileForm(forms.ModelForm): username = forms.CharField(label="Username", min_length=4, max_length=50, help_text="Required") email = forms.EmailField( label="Email", max_length=100, help_text="Required", error_messages={"required": "Sorry, you will need an email"}, ) password = forms.CharField(label="Password", widget=forms.PasswordInput) class Meta: model = UserAccount fields = [ 'username', 'email', 'first_name', 'last_name', 'about', 'password' ] def __init__(self,*args, **kwargs): super(UserProfileForm, self).__init__(*args, **kwargs) self.fields["username"].widget.attrs.update( { "class": "card bg-dark text-light form-control mb-3", "id": 'profile-username' } ) self.fields["email"].widget.attrs.update( { "class": "card bg-dark text-light form-control mb-3", "id": 'profile-email' } ) self.fields["first_name"].widget.attrs.update( { "class": "card bg-dark text-light form-control mb-3", "id": 'profile-first_name' } ) self.fields["last_name"].widget.attrs.update( { "class": "card bg-dark text-light form-control mb-3", "id": 'profile-last_name' } ) self.fields["about"].widget.attrs.update( { "class": "card bg-dark text-light form-control mb-3", "id": 'profile-about' … -
Django Resize Search Pane
I use to Django using this code forms.py from django import forms class PostSearchForm(forms.Form): search_word = forms.CharField(label='search', widget=forms.TextInput(attrs={'size': '80'})) views.py from django.views.generic import FormView class SearchDetailView(FormView): form_class = PostSearchForm template_name = 'search.html' search.html <form action="." method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" class="btn btn-primary btn-sm"> </form> When I run this code, the size of the search bar is only horizontally longer. I want to make it bigger vertically, so if you know how, please let me know. -
how to make a char field behave like URLField in django
I am using Django and I want a field for URLs I know there is a URLField in Django but I want that field to be a charfield and I don't want users to submit anything other than URL in that charfield take a look at my models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.EmailField(max_length=500, blank=True, null=True) social_github = models.CharField(max_length=200, blank=True, null=True) social_twitter = models.CharField(max_length=200, blank=True, null=True) social_linkedin = models.CharField(max_length=200, blank=True, null=True) social_youtube = models.CharField(max_length=200, blank=True, null=True) social_website = models.CharField(max_length=200, blank=True, null=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField( default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return str(self.username) Please answer how can I make a char field behave like a URL field -
Add more than 1 folder (network path) to static files with Django on IIS
I have a django website deployed on an IIS Server. in it, I have 2 different network paths I need to access via static STATICFILES_DIRS = [ "//server1/Shared1/folder/", "//Server2/folder2/", ] Now, currently my IIS has a static virtual directory that is set to "server1" this allows me to work with all the files I have in that shared network drive and opertate properly. The issue comes when I try to work with any files in the "server2" I don't know how to add it. I understand that exists something called "static root" but for that I need to do a "collect static" in this case, I can't do a collect static since both servers have over 60gb of data that I need to access. Is there a way I'm not seeing for adding this second server to be able to be used via IIS?