Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'bootstrap4'
I installed bootstrap4 with $ pip install django-bootstrap4 It is being installed in this directory C:\Users\trade\techpit-match-env\Lib\site-packages Django seems to be looking at this directory C:\Users\trade\Anaconda3\lib\site-packages\django When I put 'bootstrap4' in the INSTALLED_APPS = ('bootstrap4') variable and then run $ python manage.py runserver I get this error C:\Users\trade\techpit-match-env\Scripts\techpit>python manage.py runserver Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000001C4D8F65488> Traceback (most recent call last): File "C:\Users\trade\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\trade\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "C:\Users\trade\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Users\trade\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "C:\Users\trade\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\trade\Anaconda3\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\trade\Anaconda3\lib\site-packages\django\apps\registry.py", line 89, in populate app_config = AppConfig.create(entry) File "C:\Users\trade\Anaconda3\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\trade\Anaconda3\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'bootstrap4' How can I resolve this error? I installed bootstrap4 in the django folder by using copy and paste and that did not work. Any help would be greatly appreciated. Thank You! -
'Event' object has no attribute 'get'
[Error on 'Event' object has no attribute 'get' ] (https://forum.djangoproject.com/t/error-event-object-has-no-attribute-get/596) anyone help me please -
Django Display User as user Full Name in Admin Field
I got stuck when trying to display User foreign as use full name models.py class Customer(models.Model): name = models.charfield(max_length=100) sales = models.foreignkey(User, on_delete=models.CASADE) admin.py <pre> @admin.register(Customer) list_display = ('name', 'sales') </pre> nah by default sales as user foreign display as username. But i want display it to first name or full name -
django two templates inside eachother Could not parse the remainder
I've got the error Could not parse the remainder: '"' from '"' in this part of my code: {% include 'test.html' with post_url="{% static 'blog-single.html' %}" %} Is it possible to write something like this in Django templates? -
How to access passed context objects in Django template without using loop (class based view )
views.py class RestaurantDashboard(TemplateView): template_name = "restaurant/restaurant_dashboard.html" def get_context_data(self, **kwargs): context = super(RestaurantDashboard, self).get_context_data(**kwargs) context['profile'] = RestaurantProfile.objects.order_by('id').filter(restaurant_id =self.request.user) return context template.html {% for obj in profile %} <div style="background-color:lightblue"> <h3>{{ obj.id }}</h3> <p>{{ obj.city }}</p> </div> {% endfor %} how to access this data without using a loop ? like i need use the name of the city inside a html tag -
Outputting variable that has new lines in the template breaks the JSON object
<script> window.some_object_that_will_be_used_by_react = { message: "{{ message }}" } </script> This is the code I have in my template. It works fine as long as the message has no newlines. However, if it does, it breaks the whole JSON object. I don't want to use linebreaksbr cause it is shown as <br /> on frontend. How I can solve this? -
Accessing request parameters django
Hi I am trying to capture sms parameters from a request that comes in this format b'name=kcom-sms04&number=%2B255688121131&content=Hello' Above appears when I print HttpRequest.body How can I access number, content and name parameters? I use django. -
How to add one custom column in Django built in auth_user table
I'm trying to ass one status field in my django auth_user(Built In) table. I'm using the below code. from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import User class Auth_user(AbstractBaseUser): status = models.CharField(max_length=12,unique=True) USERNAME_FIELD = 'status' An in the settings.py I'm mentioning like this. AUTH_USER_MODEL = "accounts.Auth_user" but the status field is not getting added in the table auth_user.Can somebody suggest how to add cutom field in Django in built table? -
How to export the result of Django admin custom views as csv?
I've got 4 custom admin views in my UserAdmin, which make queries to the database and render the results in new pages so that I can check a summary of user status immediately in the admin site. Actually, each view contains many Querysets from various models. @admin.register(User) class UserAdmin(admin.UserAdmin): # attributes omitted # ... def get_urls(self): """URLs for the admin views defined below.""" urls = super().get_urls() detail_urls = [ path( '<int:user_id>/challenge_history/', self.admin_site.admin_view(self.user_challenge_history), name='challenge_history', ), # omitted remaining three views # ... ] return detail_urls + urls @staticmethod def user_actions(obj): """Add buttons towards admin views.""" return format_html( '<a class="button" href="{}">Challenge History</a>&nbsp;', reverse('admin:challenge_history', args=[obj.pk]), # omitted remaining three views # ... ) def user_challenge_history(self.request, user_id): # Prepare querysets and some objects I need # ... context = dict( self.admin_site.each_context(request), # querysets and objects # ... ) return TemplateResponse(request, 'custom_admin/user_detail.html', context) # Three more admin views # ... This code works very well, it makes buttons on the User section in the admin site, and they are linked to the custom admin views (each one is connected to the different templates) that I've defined. Now, I'd like to add a button to each custom view which exports the result of each view as … -
How to make a form in django like google form? where user can add or delete field according to their need?User can add up to 10-20 field?
Need to create form where users can add or delete fields acc to their need like user can add email, phone no field in the form or like family info, etc or if the user doesn't want that field he can delete the field. Which Django property I can you to create this form or field. -
Deploying Django in nginx server on Windows
I have a django project . I want to deploy in nginx server.I have uploaded my files via FTP. How to configure my python files in nginx . I am using windows 7. -
AttributeError: 'NoneType' object has no attribute 'save' django
i have three models when i create user it will create userprofile and when i userprofile gets created it should create artist. everything working fine but when i update userprofile its getting error models.py: class Artist(models.Model): CHOICES = ( (0, 'celebrities'), (1, 'singer'), (2, 'comedian'), (3, 'dancer'), (4, 'model'), (5, 'Photographer') ) name = models.CharField(max_length=100,null= True) artist_category = models.IntegerField(choices = CHOICES, null=True) artist_image = models.ImageField(upload_to= 'media',null=True) bio = models.TextField(max_length = 500) def __str__(self): return str(self.name) class UserProfile(models.Model): CHOICES = ( (0, 'celebrities'), (1, 'singer'), (2, 'comedian'), (3, 'dancer'), (4, 'model'), (5, 'Photographer') ) user = models.OneToOneField(CustomUser, related_name='userprofile', on_delete= models.CASCADE) artist = models.ForeignKey(Artist,related_name='userprofile', on_delete=models.CASCADE, null=True) name = models.CharField(max_length=100, null=True) artist_category = models.IntegerField(choices= CHOICES, null=True) mobile_number = PhoneNumberField(null=True) country = CountryField(default = 'IN') city = models.CharField(blank=True, max_length=100) bio = models.TextField(blank=True) def __str__(self): return str(self.user) def create_profile(sender,instance, created,**kwargs): if created: data = { 'name': instance.name } UserProfile.objects.create(user=instance,**data) post_save.connect(create_profile,sender=CustomUser) @receiver(post_save, sender= CustomUser) def save_profile(sender,instance,**kwargs): instance.userprofile.save() def create_artist(sender,instance,created,**kwargs): if created: data = { 'name': instance.name, 'artist_category': instance.artist_category, 'bio': instance.bio } Artist.objects.create(**data) post_save.connect(create_artist,sender=UserProfile) @receiver(post_save, sender= UserProfile) def save_artist(sender,instance,**kwargs): instance.artist.save() its getting none type instance............................................................................ -
Looping through Django Many To Many Form Field
I want to use the Chosen library of Jquery for my ManyToMany Field , This is the model: class StockItem(models.Model): organisation = models.ForeignKey(Organisation, on_delete=models.CASCADE,related_name='organisation_stock_item', null=True, blank=True) stock_name = models.CharField(max_length=100) related_products = models.ManyToManyField("self", related_name="products", blank=True) This is what I have Tried: My forms.py: class StockItemForm(forms.ModelForm): """ Stock Item Form """ class Meta: model = StockItem fields = ('stock_name','related_products') def __init__(self, *args, **kwargs): self.company = kwargs.pop('organisation', None) super(StockItemForm, self).__init__(*args, **kwargs) self.fields['stock_name'].widget.attrs = {'class': 'form-control', } choices = [(ts.pk, ts.stock_name) for ts in StockItem.objects.filter(organisation=self.company)] self.fields['related_products'].choices = choices In my template I tried: <div class="form-group row"> <label class="font-normal col-lg-2">Related Products</label> <div class="col-lg-10"> <select data-placeholder="Choose a Product..." class="chosen-select col-lg-10" multiple style="width:350px;" tabindex="4"> <option value="">Select</option> {% for value, text in form.related_products.field.widget.choices %} <option value="{{ value }}">{{ text }}</option> {% endfor %} </select> </div> </div> The Items Are Rendering Correctly, But when trying to save the related products its not saving them at all i.e. when I am going to my update view I see the related product are not selected. Can any one tell me what is wrong in my code? I am Using Chosen jQuery Multi-Select for this operation. -
Django session in AWS EKS
My Django application is running in 3 nodes(AWS EKS) and the application is running in https. The Django session(LoginRequiredMixin) is dropping and I am not able to login to the application. I define the Django CACHE as below in settings.py SESSION_ENGINE = "django.contrib.sessions.backends.cached_db" SESSION_CACHE_ALIAS = "default" CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://XXXXXXXXXXXXXXX.XXXXX.amazonaws.com:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient" } } } How to create the session when the application is running in AWS EKS with multiple nodes? -
file uploading is successful in Postman but not in Ajax
I want to upload the file with Ajax in DRF, but I fail! var form = new FormData(); form.append("files[1]file", "/home/mshzsh/Pictures/photo.jpg"); var settings = { "async": true, "crossDomain": true, "url": "http://127.0.0.1:8000/api/pc/update/155/", "method": "PUT", "headers": { "User-Agent": "PostmanRuntime/7.20.1", "Accept": "*/*", "Cache-Control": "no-cache", "Postman-Token": "379c280a-c620-4e5f-8b9b-0ace0a9e6fa6,8c381931-20bb-480d-827d-11bb05718224", "Host": "127.0.0.1:8000", "Content-Type": "multipart/form-data; boundary=--------------------------641148104724362550775599", "Accept-Encoding": "gzip, deflate", "Content-Length": "1355503", "Connection": "keep-alive", "cache-control": "no-cache" }, "processData": false, "contentType": false, "mimeType": "multipart/form-data", "data": form } $.ajax(settings).done(function (response) { console.log(response); }); I have copied these codes from the postman but I get error : The submitted data was not a file. Check the encoding type on the form. in Ajax. I tried a variety of AJAX methods but failed! -
upstream prematurely closed connection while reading response header from upstream, Django + uWSGI + nginx, React as frontend
I am getting this error(upstream prematurely closed connection while reading response header from upstream) in nginx's error.log when sending post request to Django on send_mail, as the response it returns 502 Bad Gateway and also cors error(has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource), cors is enable on django, less secure apps is turned on on gmail. Thanks -
Serializer does not return all fields when saving
I have following serializer: class ClientSerializer(serializers.ModelSerializer): projects_count = serializers.ReadOnlyField() currency = CurrencySerializer(read_only=True) class Meta: model = Client fields = ('id', 'owner', 'name', 'icon_color', 'projects_count', 'hourly_rate', 'currency', ) def get_projects_count(self, obj): if hasattr(obj, 'projects_count'): return obj.projects_count return 0 And this is the view for getting and creating Client objects: class ClientListView(APIView): http_method_names = ['get', 'post'] authentication_classes = (authentication.SessionAuthentication, ) permission_classes = [IsAuthenticated] def post(self, request, format=None): serializer = ClientSerializer( context=dict(request=request), data=request.data ) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def get(self, request, format=None): qs_clients = Client.objects.filter( owner=request.user, ).annotate( projects_count=Count('project'), ) client_serializer = ClientSerializer( qs_clients, many=True, ) data = dict( clients=client_serializer.data, ) return Response( data, status=status.HTTP_200_OK, ) When calling POST, data returned does not contain project_count field: POST: {"id":9,"owner":1,"name":"zzz xxx","icon_color":"a45ac8","hourly_rate":null,"currency":null} But for GET, there is everything ok: GET: {"clients":[{"id":9,"owner":1,"name":"zzz xxx","icon_color":"a45ac8","projects_count":0,"hourly_rate":null,"currency":null}]} I need to have projects_count included in the POST response. Why is it missing? Thanks! -
apscheduler and django, but when i runserver,it's error,why?
eror info you can see error message is: UnicodeEncodeError: 'utf-8' codec can't encode character '\udc80' in position 156: surrogates not allowed -
how to save context without sessions in django
I am developing a multi channel chatbot in django where users can interact with facebook, whatsapp, and website. i am asking for user details one by one eg:- if user said "book test drive", bot will ask for name, address and other details one by one. I need to store those details which will obviously different for different users and respond accordingly, and finally save them. i have implemented that on website through sessions, but whatsapp and facebook won't support session without webview, is there any way to achieve this? -
Multiple fields update in a model using radio boxes
I am trying to make a page where admin can mark attendance for each student using absent and present radio boxes present besides each student My ClassRoom and ClassRoomStudents Model class ClassRoom(models.Model): # standard = models.CharField(max_length=50) classSection = models.CharField(max_length=50) teacher = models.OneToOneField(Teacher, on_delete = models.CASCADE) class ClassRoomStudent(models.Model): classRoom = models.ForeignKey(ClassRoom, on_delete=models.CASCADE) roll_number = models.IntegerField() student = models.OneToOneField(StudentInfo, on_delete=models.CASCADE) def save (self, *args, **kwargs): <logic to update roll number automatically for each classroom_student> model.py in my attendence app, status will store absent or present class StudentAttendence(models.Model): student = models.OneToOneField(ClassRoomStudent, on_delete=models.CASCADE) status = models.CharField(max_length=50) date = models.DateField() class TeacherAttendence(models.Model): teacher = models.OneToOneField(Teacher, on_delete=models.CASCADE) status = models.CharField(max_length=50) date = models.DateField() I have option in my template to search students using class. My views.py in attendence app def student_attendence(request): if request.method == "GET": if "add_no" in request.GET: add_no = request.GET["add_no"] students = ClassRoomStudent.objects.filter(classRoom__classSection__icontains = class_name) return render(request, 'attendence/student.html', {"students":students}) My question is how can I mark each student as absent or present using radiobox or something and store that in StudentAttendence model for each student? -
Access python script from one project to another
Main folder |-project1 |-project2 I have the above structure for django projects. When I am in project1 in a script i used os.chdir(to_project2) to project 2 I want to access project2's settings.py and fetch some attributes. Is it possible? -
Django logging module with TimedRotatingFileHandler logging to default logfile after restart
While using TimedRotatingFileHandler for logging in my Django project, the logger logs to the default file at the start and after midnight is reached, it will start logging to a new file with the date attached at the end. Ex: if the file name I have given is server_logs, it will log to this default file until midnight and then start logging in the new file, say: server_logs.2019-12-09. So far so good. But if restart the server, it will again start logging to server_logs file instead of the latest file with current date. I want it to continue logging to the latest file, even after the server restart. How do I resolve this issue? Also, in the log file, while logging, I want just the folder name and file name which is logging to the file. If I use %pathname, I get a path name like: "/some/log/path/appFolder/file.py". And if I use %filename, I get just "file.py". Ex: 2019-12-10 06:37:42,010, ERROR, views.py, get, LineNo 13 : This is the message. or 2019-12-10 03:54:47,173, ERROR, /some/long/path/name/that/I/want/to/avoid/testApp/views.py, get, LineNo 13 This is the message. I want to format it to "testApp/views.py". Ex: 2019-12-10 06:37:42,010, ERROR, testApp/views.py, get, LineNo 13 : This is the … -
Static files are not served during production in Django. How to solve the issue?
I want to deploy a Django app in my Linux server. I followed the Django docs and even configured the Apache config file as well but when running the Django server, none of my CSS and JS files are seen for: my website, Django admin interface and rest_framework as well. This is what I had done so far: A 'static' folder was created after initating the 'collectstatic' command and contains the following: blog_app (my website) rest_framework (my APIs) admin (Default Django Admin interface) settings.py: DEBUG = False [.] #all default settings # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES' : [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], } Apache config file (I named it as 'django_app.conf'): #django_app is the root folder for my Django project Alias /static /var/user/django_app/static <Directory /var/user/django_app/static> Require all granted </Directory> <Directory /var/user/django_app/django_app> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /var/user/django_app/django_app/wsgi.py WSGIDaemonProcess my_django_app python-path=/var/user/django_app python-home=/var/user/django_app/venv WSGIProcessGroup my_django_app After this, I typed: sudo a2ensite django.conf #to allow my Apache config file instead of 000-default.conf And: sudo a2dissite 000-default.conf #to disallow original Apache2 config file Then I included www-data user permission for my root project folder: … -
Table alignment in django template
I created a django template and the page contains a collapsible field but since I have added the collapsible field it shifts the rest of the row in the next line. Here's an image for better understanding: Earlier the edit and delete button were in the same row Here's the code: <div class="card"> <table class="table mb-0"> <thead> <tr> <th>Kit Name</th> <th>Kit Info</th> <th>Components per Kit</th> <th>Kit client</th> <th>Products</th> </tr> </thead> <tbody> {% for kit in kit %} <tr> <td class="align-middle">{{ kit.kit_name }}</td> <td class="align-middle">{{ kit.kit_info }}</td> <td class="align-middle">{{ kit.components_per_kit }}</td> <td class="align-middle">{{ kit.kit_client }}</td> <td class="align-middle"> <button class="btn" type="button" data-toggle="collapse" data-target="#multiCollapse{{ kit.pk }}" aria-expanded="false" aria-controls="multiCollapse{{ kit.pk }}"><img src="{% static 'img/cardopen.svg' %}" width="30" height="30" alt="card open"></button> </td> <tr class="collapse multi-collapse" id="multiCollapse{{ kit.pk }}"> <td colspan="7"> <table class="table table-bordered itemstable"> <thead> <tr> <th>Product Name</th> <th>Product Quantity</th> </tr> </thead> <tbody> {% if kit.product1 and kit.product1_quantity %} <tr> <td class="align-middle" id="p1">{{ kit.product1 }}</td> <td class="align-middle" id="pq1">{{ kit.product1_quantity }}</td> </tr> {% endif %} {% if kit.product2 and kit.product2_quantity %} <tr> <td class="align-middle" id="p2">{{ kit.product2 }}</td> <td class="align-middle" id="pq2">{{ kit.product2_quantity }}</td> </tr> {% endif %} {% if kit.product3 and kit.product3_quantity %} <tr> <td class="align-middle" id="p3">{{ kit.product3 }}</td> <td class="align-middle" id="pq3">{{ kit.product3_quantity }}</td> </tr> {% endif %} … -
Download multiple files in Django without creating zip
Is there a way to download multiple files in Django without creating zipfile on single click/request. For downloading single file I am using the following code in views.py: def download_file(request): the_file = '/some/file/name.png' filename = os.path.basename(the_file) chunk_size = 8192 response = StreamingHttpResponse(FileWrapper(open(the_file, 'rb'), chunk_size), content_type=mimetypes.guess_type(the_file)[0]) response['Content-Length'] = os.path.getsize(the_file) response['Content-Disposition'] = "attachment; filename=%s" % filename return response Also the code should be capable of downloading large files in size of 100GB max as I am dealing with video files with high resolution