Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
hot to set tinymce.init in django-tinymce package
I can't use CDN of tinymce in my project. So I wanna use django-tinymce package. But don't know how to set tinymce.init to set my personal configuration. -
HTTP to HTTPS on NGINX Django server
I'm setting up a server on AWS from a Django project and my Nginx gives an error when trying to switch from HTTP to HTTPS. See my file: host = fantasy name server { listen 80; server_name host; return 301 https://host$request_uri; location = /favicon.ico { access_log off; log_not_found off; } location /staticfiles/ {alias /home/ubuntu/Filmes/staticfiles/;} location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Indeed when using the old domain over HTTP I am redirected to HTTPS but I get CONNECTION DENIED TO THIS DNS. -
Any idea why contexts are not showing in template?
So, I have this two function in my views.py class TheirDetailView(DetailView): model = List def listcomments(request): modell = Review.objects.all() return render(request, 'app/list_comment.html', {'model' : modell}) And have these two paths set in my apps urls path('list/<slug:slug>/', TheirDetailView.as_view(),name='list_detail'), path('comment/',views.listcomments, name='ListComments'), So I have two templates list_detail.html & list_comment.html Here in list_detail.html I have included list_comment.html (just the comment section is there in list_comment.html) In my list_detail.html .. ... .... <div class="commentss" id="comments-id"> <div class = "commentscarrier"> <div class="comment-contentsas comment-head"><p>Comments(3)</p></div> <hr> {% include "app/list_comment.html" %} ... .. In my list_comment.html {% load static %} {% for i in model %} <div class="comment-contentsas"><p class="commentor-name">{{i.user.username}} </p></div> <div class="comment-contentsas"><p>{{i.comment}}</p></div> </div> {% endfor %} In my models.py class Review(models.Model): user = models.ForeignKey(User, models.CASCADE) List = models.ForeignKey(List, models.CASCADE) comment = models.TextField(max_length=250) rate = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.comment) class List(models.Model): title = models.CharField(max_length=65) genre = models.ManyToManyField('Genre') creator = models.ForeignKey(User,on_delete=models.SET_NULL,blank=True, null=True) posted = models.DateTimeField(auto_now_add=True) content = RichTextField(null=True,default=' ') type = models.CharField(max_length=10,default="Movie") slug = models.SlugField(max_length= 300,null=True, blank = True, unique=True) I have created 5 objects of Review model manually in admin. So that should show in my template. But its not showing anything. I am guessing I must have been messed up in my urls. But … -
CookieCutter Django websocket disconnecting (using Docker)
I am trying to build a chat application. I am using Cookiecutter django as the project initiator. And using a docker environment, and celery as i need to use redis for websocket intercommunication. But websocket is constantly disconnecting even if i am accepting the connection is consumers using self.accept(). i have also included the CHANNEL_LAYERS in the config/settings/base.py file. Here is my local env file. # General # ------------------------------------------------------------------------------ USE_DOCKER=yes IPYTHONDIR=/app/.ipython # Redis # ------------------------------------------------------------------------------ REDIS_URL=redis://redis:6379/0 REDIS_HOST=redis REDIS_PORT=6379 # Celery # ------------------------------------------------------------------------------ # Flower CELERY_FLOWER_USER=xxxxx CELERY_FLOWER_PASSWORD=xxxx Here is my consumers.py file from channels.generic.websocket import JsonWebsocketConsumer class ChatConsumer(JsonWebsocketConsumer): """ This consumer is used to show user's online status, and send notifications. """ def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.room_name = None def connect(self): print("Connected!") self.room_name = "home" self.accept() self.send_json( { "type": "welcome_message", "message": "Hey there! You've successfully connected!", } ) def disconnect(self, code): print("Disconnected!") return super().disconnect(code) def receive_json(self, content, **kwargs): print(content) return super().receive_json(content, **kwargs) Heres my routing.py file from django.urls import path from chat_dj.chats import consumers websocket_urlpatterns = [ path('', consumers.ChatConsumer.as_asgi()), ] Heres my asgi.py file """ ASGI config It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/dev/howto/deployment/asgi/ """ import os … -
Code to display Django (Reverse) related table throws error
I'm quite new to Django and practicing Models section of Django by following its official tutorial. I also created a project of my own and try to apply similar concepts. This is my models.py; from django.db import models class Experience(models. Model): o01_position = models.CharField( max_length = 50 ) o02_year_in = models.DateField( null = True) o03_year_out = models.DateField( null = True) o04_project = models.CharField( max_length = 100 ) o05_company = models.CharField( max_length = 50 ) o06_location = models.CharField( max_length = 50 ) def __str__(self): return self.o01_position class Prjdesc(models.Model): o00_key = models.ForeignKey( Experience, on_delete = models.CASCADE) o07_p_desc = models.CharField( max_length = 250 ) def __str__(self): return self.o07_p_desc class Jobdesc(models.Model): o00_key = models.ForeignKey( Experience, on_delete = models.CASCADE) o08_job_desc = models.CharField( max_length = 250 ) def __str__(self): return self.o08_job_desc Now when I run below command in python / Django shell it runs as expected with the related data. >>> x = Experience.objects.get( pk = 2 ) >>> x <Experience: Head Office Technical Office Manager> Below two also work as expected; >>> y = Prjdesc.objects.get( pk = 11 ) >>> y <Prjdesc: Description 1> >>> x.prjdesc_set.all() <QuerySet [<Prjdesc: Description 1>, <Prjdesc: Description 2>]> However this expression does not return anything although it should return its … -
Django server running on a GCE instance cannot connect to postgres cloud SQL
I have a docker-compose that has django and an nginx as a reverse proxy docker-compose.yml: version: "3" services: app: restart: always command: ./startup.sh image: region-docker.pkg.dev/project_id/repo/image:tag container_name: backend expose: - "8000" volumes: - static_volume:/code/static hostname: app nginx: restart: always image: region-docker.pkg.dev/project_id/repo/image:tag volumes: - static_volume:/code/static ports: - "80:80" depends_on: - app volumes: static_volume: the database connection variables configuration in the settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'Instance': 'project_id:region:instance_name', 'NAME': 'database_name', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'database_internal_IP', 'PORT': '5432', } } whenever I run docker-compose up in the VMs CLI the nginx runs perfectly but the django servers comes with this error django.db.utils.OperationalError: could not connect to server: Connection timed out backend | Is the server running on host "instance-private-IP" and accepting backend | TCP/IP connections on port 5432? Note: when I run psql -h instance-private-IP -U username the connection is successfully established Note: when I run the exact same container on my local pc with the same configurations with only the public IP instead of the private IP the container runs just fine Note: the service account attached to the VM has access to the cloud SQL enabled -
Reverse for 'password_change_done' not found. 'password_change_done' is not a valid view function or pattern name
I'm trying to use my custom template for password change. So I created its template (registration/password_change_done.html) and wrote the urls as below: from django.contrib.auth.views import PasswordChangeView, PasswordChangeDoneView app_name = "accounts" urlpatterns = [ path( "accounts/password_change/", PasswordChangeView.as_view( success_url=reverse_lazy("accounts:password_change_done") ), name="password_change" ), path( "accounts/password_change/done/", PasswordChangeDoneView.as_view( template_name="registration/password_change_done.html" ), name="password_change_done" ), ] Password change works fine but when its form is submitted, I get this error: NoReverseMatch at /accounts/password_change/ Reverse for 'password_change_done' not found. 'password_change_done' is not a valid view function or pattern name. I searched about it and it seems like it should work when I set PasswordChangeView's success_url. But it didn't make any difference. -
Apache/mod_wsgi/Django AJAX : 500 Internal Server Error: ModuleNotFoundError: No module named 'corsheaders'
Our issue is stemming from a Django project finding the corsheaders module running via Apache/WSGI. The code runs fine using the Django's local runserver but throws a 500 Internal Server Error when acccessed throught Apache (v.2.4.41). If we comment out the application and middleware in settings.py, the site and other code works fine (execpt the API functionality that needs corsheaders). We have exhausted the online resources we can find, so thank you in advance for the advice to uninstall and reinstall django-cors-headers in a variety of ways using pip. We do use several other modules that have been installed via this gateway with no issue. The best we can tell, the issue stems from the django wsgi not seeing the module. I included the relevant logs and settings below. I also noted the install locations for the corsheader module. Relevant Versions django-cors-headers==3.13.0 (installed at: /home/geekfest/.local/lib/python3.8/site-packages) django-cors-middleware==1.5.0 python==3.8.10 Django==4.1.2 Ubuntu==20.04.1 pythonpath: ['', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/geekfest/.local/lib/python3.8/site-packages', '/usr/local/lib/python3.8/dist-packages', '/usr/lib/python3/dist-packages'] **settings.py** INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'corsheaders', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'stats', ] 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', 'django.middleware.common.CommonMiddleware', 'stats.middleware.EventData', ] ROOT_URLCONF = 'geekstats.urls' CORS_ORIGIN_ALLOW_ALL = True error.log [Fri Oct 07 11:01:49.957188 2022] [wsgi:error] [pid 11860] … -
Django user two-factor authentication
I want to make user two-factor authentication (especially qrcode). I tried to use django-otp, but faced with problems. I add two-factor for admin, but don't understand how to do this for casual users. What can i use for this? -
Custom HTTP error pages in Django not working as intended
I want to make custom error pages for 404, 403, etc, but when I do anything mentioned in the documentation or any other forums/stackoverflow posts, it ignores the custom functions. I tried this already: How do I redirect errors like 404 or 500 or 403 to a custom error page in apache httpd? and many others. Am I doing something wrong? engine(custom app) \ views.py def permission_denied(request, exception): context = {'e':exception} return render(request, '403.html', context, status=403) core (main project) \ urls.py handler403 = 'engine.views.permission_denied' urlpatterns = [ path('admin/', admin.site.urls), [...] ...and it just shows the built-in error pages. Changing debug mode on or off doesn't change it. P.E.: when I pasted the views.py function, it threw an error saying it takes 2 arguments, one for request and one for the exception, so it knows that the function is there, but when I added it to the arguments, it still got ignored. Any advice appreciated! -
Django cached_property is NOT being cached
I have the following in my models: class Tag(models.Model): name = models.CharField(max_length=255) type = models.CharField(max_length=1) person = models.ForeignKey(People, on_delete=models.CASCADE) class People(models.Model): name = models.CharField(max_length=255) @cached_property def tags(self): return Tag.objects.filter(person=self, type="A") I would expect that when I do this: person = People.objects.get(pk=1) tags = person.tags That this would result in 1 db query - only getting the person from the database. However, it continuously results in 2 queries - the tags table is being consistently queried even though this is supposedly cached. What can cause this? Am I not using the cached_property right? The models are simplified to illustrate this case. -
Where do I install Apache2 in my existing Django Project
I have an existing Django project running on uWSGI, and I want to install apache2 to act as the web server. I found instructions online on how to do the installation - see link below. https://studygyaan.com/django/how-to-setup-django-applications-with-apache-and-mod-wsgi-on-ubuntu One thing the instructions does not mention is where do I run the installation. Do I run the installation in /root? Or somewhere else. Also, any feedback on the online instructions would be greatly appreciated. Thanks in advance -
Django Link to form with condition
On my base.html I have 2 links which lead to the same post_form.html and use the same forms.py. Link: <a class="list-group-item list-group-item-light" href="{% url 'post-create' %}">Submit</a> Problem is, I would like to hide/show part of the page depending on which link did user select. How can I do that? Below is script I use to hide a field, but I don't know which link did they use. (currently the links are the same, don't know what to add to make a change on the page 'post_form.html) <script type="text/javascript"> function on_load_1(){ document.getElementById('div_id_type').style.display = 'none';} on_load_1(); </script> -
Django, keep initial url path unchanged
I have a Django project with 5 apps. Basically, in the homepage there are 3 links. I'm still not in deployment so the base url is localhost:8000 (the homepage app is called homepage). After the user clicks in one of the 3 links I want the url to stay with that number, even after using different apps. Example of what I'm looking for: User clicks on link 1 and then -> localhost:8000/1. User clicks on link that directs to another app (called ros) -> localhost:8000/1/ros. And keep that one at the start of the url and only change if another of the 3 links in homepage is selected. Example of what I'm getting so far: User clicks on link 1 and then -> localhost:8000/ros/1 or localhost:8000/ros/2 or localhost:8000/ros/3 depending on the link clicked. The question is, how can I modify the homepage URL's and the app ROS url's so that the ROS url receive the link parameter (either a 1,2 or 3) + ROS.urls. HTML homepage code <li><a href="/" class="nav-link scrollto"><i class="bx bx-home"></i> <span>Inicio</span></a></li> <li><a href="1/ros/1" class="nav-link scrollto"><i class="bx bx-file-blank"></i> <span>ROS 1</span></a></li> <li><a href="2/ros/2" class="nav-link scrollto"><i class="bx bx-file-blank"></i> <span>ROS 2</span></a></li> <li><a href="3/ros/3" class="nav-link scrollto"><i class="bx bx-file-blank"></i> <span>ROS 3</span></a></li> Homepage URL … -
Scattermapbox code works as Dash app but is blank with DjangoDash
I want to display a map in Django using django_plotly_dash and map box. It is based on the "Basic example" from https://plotly.com/python/scattermapbox/. It works FINE AS STAND ALONE Dash app: import dash_core_components as dcc import dash_html_components as html import plotly.graph_objects as go from dash import Dash external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = Dash('Location', external_stylesheets=external_stylesheets) mapbox_access_token = open("./finished_apps/mapbox_token.rtf").read() fig = go.Figure(go.Scattermapbox( lat=['45.5017'], lon=['-73.5673'], mode='markers', marker=go.scattermapbox.Marker( size=14 ), text=['Montreal'], )) fig.update_layout( hovermode='closest', mapbox=dict( accesstoken=mapbox_access_token, bearing=0, center=go.layout.mapbox.Center( lat=45, lon=-73 ), pitch=0, zoom=5 ) ) app.layout = html.Div([ dcc.Graph(id='maplocation', figure=fig) ]) if __name__ == '__main__': app.run_server(debug=True) But is does not work in Django. Remark: Other Dash Plotly diagrams work in Django in this portal. The code differs only in three lines (marked with ###) between map box stand alone and Django version. import dash_core_components as dcc import dash_html_components as html import plotly.graph_objects as go from django_plotly_dash import DjangoDash ### external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = DjangoDash('Location', external_stylesheets=external_stylesheets) ### mapbox_access_token = open("./mapbox_token.rtf").read()### fig = go.Figure(go.Scattermapbox( lat=['45.5017'], lon=['-73.5673'], mode='markers', marker=go.scattermapbox.Marker( size=14 ), text=['Montreal'], )) fig.update_layout( hovermode='closest', mapbox=dict( accesstoken=mapbox_access_token, bearing=0, center=go.layout.mapbox.Center( lat=45, lon=-73 ), pitch=0, zoom=5 ) ) app.layout = html.Div([ dcc.Graph(id='maplocation', figure=fig) ]) It finds the map box token (Reason for the third change is the different levels … -
{% block content %} {% endblock %} showing in html while making chatbot
so I was following one chatbot tutorial using Django I came across this error my frontpage.html https://i.stack.imgur.com/TET9w.png my base.html https://i.stack.imgur.com/1eVg1.png my output https://i.stack.imgur.com/r4R0K.png so {% block title %} {% end block %} is not working kindly help. -
Question about Django rest framework Serializers and Views working principles
I'm trying to build REST api with Django Rest Framework and kind a having diffuculty to understand how things connected each other in terms of when we need to use the custom functions. I have views.py like this class myAPIView(viewsets.ModelViewSet): queryset = myTable.objects.all() serializer_class = mySerializer this is my serializer.py class myserializer(serializers.ModelSerializer): class Meta: model = myTable fields = "__all__" def create(self, validated_data): #doing some operation here and save validated data def update(self, instance, validated_data): #doing some operation here and save validated data I want to add some custom function to do let's say sending emails with processed data. so when I add my_email_sender function to nothing happens (nothing prints to terminal). class myAPIView(viewsets.ModelViewSet): queryset = myTable.objects.all() serializer_class = mySerializer def my_email_func(): print("Hey I'm email function") my_email_sender() OTH, when do do this inside of the serializer its printing to the screen. I actually really don't know this my_email_func should be inside of views.py some sort of CRUD operation function like def create(), def update() etc.. I also don't know why we cannot call it from views.py ? Thank for your answer in advance! -
How to read text file and show content in textarea with python?
I have a django application. And I can upload files. But now I want to show the text from a text file in a text area. So I have this: forms.py: class ProfileForm(forms.Form): upload_file = forms.FileField() models.py: class UploadFile(models.Model): image = models.FileField(upload_to="images") vieuws.py: class CreateProfileView(View): def get(self, request): form = ProfileForm() return render(request, "main/create_profile.html", { "form": form }) def post(self, request): submitted_form = ProfileForm(request.POST, request.FILES) if submitted_form.is_valid(): uploadfile = UploadFile(image=request.FILES["upload_file"]) uploadfile.save() return HttpResponseRedirect("/") return render(request, "main/create_profile.html", { "form": submitted_form }) and the html file: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Create a Profile</title> <link rel="stylesheet" href="{% static "main/styles/styles.css" %}"> </head> <body> <form action="/" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <button type="submit">Upload!</button> </form> <textarea name="" id="" cols="30" rows="10"></textarea> </body> </html> But so I have this textfile: yes.txt with this content: Yes, we can. So my question is:how to output this text in the textarea? Thank you -
Deploy Django Project With SQLite on Azure
So I have created Django Based Project for the Academic Time Table Generator and have created some tables to generate time table, I want to deploy my Django project with SQLite using the Azure platform and I am completely new to any cloud platform. https://github.com/ArjunGadani/Time-Table-Generator I have seen a couple of tutorials but all of them are using static pages to just show demo pages, So I got no lead or reference on how to deploy a Django project with its default SQLite database. I have uploaded my project on GitHub and I need help how configuring to embed that default database on Azure. -
Modeling a messaging mechanism in Django
Using the m2m relationship (the 'watchers' field) in the models below and the default User model I'm able to keep track of what specific user tracks what specific items. Need a little help please with modelling the event of item(s) price change upon a periodic hourly check. How do I come up with a list of users, each to receive an email containing only the items on his watchlist that feature a price change? Thus far, after each check, I can come up with a list of items that have an price attribute change. How do I go about figuring out which of these items should be in the notification msg (nevermind if it's email or something else) to each user? Am I on the right path with the Notification class or I should scrap that? Thanks!!! class Notification(models.Model): is_read = models.BooleanField(default=False) message = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE) class Item(models.Model) : title = models.CharField( max_length=200, validators=[MinLengthValidator(2, "Title must be greater than 2 characters")] ) current_price = models.DecimalField(max_digits=7, decimal_places=2, null=True) last_price = models.DecimalField(max_digits=7, decimal_places=2, null=True) lowest_price = models.DecimalField(max_digits=7, decimal_places=2, null=True) description = models.TextField() owner = models.ForeignKey(User, on_delete=models.CASCADE) item_image = models.URLField(max_length=600, null=True) item_url = models.URLField(max_length=600, null=True) product_id = … -
Problem installing django on a virtual machine with no access to pypi.org
I developed a relatively simple site with Django and I need to deploy it on a Windows VM hosted on a PC on the local network. These are the requirements: requirements.txt asgiref==3.5.0 autopep8==1.6.0 Django==4.0.3 Pillow==9.0.1 pycodestyle==2.8.0 sqlparse==0.4.2 toml==0.10.2 tzdata==2022.1 Having no access to the internet, I followed these steps: PC With Internet mkdir dependencies pip download -r requirements.txt -d "./dependencies" tar cvfz dependencies.tar.gz dependencies I then moved the tar file on the VM and did the following: tar zxvf dependencies.tar.gz cd dependencies for %x in (dir *.whl) do pip install %x --no-index --force-reinstall The above commands resulted in this pip freeze: asgiref @ file:///C:/website/packages/dependencies/asgiref-3.5.0-py3-none-any.whl Pillow @ file:///C:/website/packages/dependencies/Pillow-9.0.1-cp310-cp310-win_amd64.whl pycodestyle @ file:///C:/website/packages/dependencies/pycodestyle-2.8.0-py2.py3-none-any.whl sqlparse @ file:///C:/website/packages/dependencies/sqlparse-0.4.2-py3-none-any.whl toml @ file:///C:/website/packages/dependencies/toml-0.10.2-py2.py3-none-any.whl tzdata @ file:///C:/website/packages/dependencies/tzdata-2022.1-py2.py3-none-any.whl As you can see Django and autopep8 fail to install even though the requirements should be met. What am I missing? Any help pointing me to the solution would be very much appreciated!! Thanks BTW, this is the log: log Processing c:\website\packages\dependencies\asgiref-3.5.0-py3-none-any.whl Installing collected packages: asgiref Attempting uninstall: asgiref Found existing installation: asgiref 3.5.0 Uninstalling asgiref-3.5.0: Successfully uninstalled asgiref-3.5.0 Successfully installed asgiref-3.5.0 Processing c:\website\packages\dependencies\autopep8-1.6.0-py2.py3-none-any.whl Processing c:\website\packages\dependencies\django-4.0.3-py3-none-any.whl Processing c:\website\packages\dependencies\pillow-9.0.1-cp310-cp310-win_amd64.whl Installing collected packages: Pillow Attempting uninstall: Pillow Found existing installation: Pillow 9.0.1 Uninstalling … -
SAML2 implementation for Django Application
Which library and identity provider is suitable for saml implementation in Django application. -
Django Export Excel -- Category based on count
I am using Django and want to export it in excel. How can you do count based on occurences of the category Accident Causation -- Severity Severity has three options: Severity 1, Severity 2, Severity 3 The excel should look like this Accident Causation | Severity 1| Severity 2 | Severity 3 Accident Causation1| 20 | 10 | 0 Accident Causation2| 0 | 5 | 0 Model user = models.ForeignKey(User, on_delete=models.CASCADE, editable=False, null=True, blank=True) user_report = models.OneToOneField(UserReport, on_delete=models.CASCADE) accident_factor = models.ForeignKey(AccidentCausation, on_delete=models.SET_NULL, blank=True, null=True) accident_subcategory = models.ForeignKey(AccidentCausationSub, on_delete=models.SET_NULL, blank=True, null=True) collision_type = models.ForeignKey(CollisionType, on_delete=models.SET_NULL, blank=True, null=True) collision_subcategory = models.ForeignKey(CollisionTypeSub, on_delete=models.SET_NULL, blank=True, null=True) crash_type = models.ForeignKey(CrashType, on_delete=models.SET_NULL, blank=True, null=True) weather = models.PositiveSmallIntegerField(choices=WEATHER, blank=True, null=True) light = models.PositiveSmallIntegerField(choices=LIGHT, blank=True, null=True) severity = models.PositiveSmallIntegerField(choices=SEVERITY, blank=True, null=True) movement_code = models.CharField(max_length=250, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Views def export_accidentcausation_xls(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="accident_causation.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Accident Causation') alignment = xlwt.Alignment() alignment.horz = xlwt.Alignment.HORZ_LEFT alignment.vert = xlwt.Alignment.VERT_TOP style = xlwt.XFStyle() # Create Style style.alignment = alignment # Add Alignment to Style # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True header_font = xlwt.Font() # Header font preferences header_font.name = 'Times New Roman' header_font.height … -
How to add only the necessary model in django to the second database?
I use two databases in django, one is marked as "default", the other is optional. I have this question: I have a file with models, all these models are in the main database, and there is also another file models.py , I want to make migrations to the second DB from it. It's just that if I make migrations to it, then all the models in the project are added there, and I don't need it that way. So how to make it so that 1 model.py = 1 migration to an additional database? -
Python class-based-view updateview not get saved
Hey guys I am new in programming I am trying to make a website for Todo by using Python-django. I am using Django Class Based Update View to make edit in datas. But while I am click on submit button its not get saved views.py class TaskUpdateView(UpdateView): model = Task fields = "__all__" template_name = 'update.html' context_object_name = 'task' success_url = reverse_lazy('cbvhome') urls.py path('update/<pk>',views.TaskUpdateView.as_view(),name='cbvupdate') update.html <form method="post" class=" justify-content-center align-items-center mb-4 ps" enctype="multipart/form-data"> {% csrf_token %} <div class="mb-3"> <label for="task-id" class="form-label me-5">Task</label> <input type="text" name="name" class="form-control" id="task-id" aria-describedby="emailHelp" style="width: 80%;" placeholder="Enter your Task Here" value="{{task.name}}"> </div> <div class="mb-3"> <label for="exampleFormControlTextarea1" class="form-label me-5">Enter the details</label> <textarea class="form-control" name="details" id="task-detail"rows="2" placeholder="Enter the task details" style="width: 80%;">{{task.details}}</textarea> </div> <div class="mb-3"> <label for="task-date" class="form-label me-5">Date set curerntly: {{task.date}}</label> <input type="date" name="date" class="form-control" id="task-date" style="width: 80%;" value="{{task.date}}"> </div> <div class="mb-3 mt-3"> <label for="task-prio" class="form-label me-5">Select the priority</label> <select class="form-select" name="priority" aria-label="Default select example" style="width: 80%;" id="task-prio" value="{{task.priority}}"> <option selected>{{task.priority}}</option> <option value="Very Urgent" class="text-danger">Very Urgent</option> <option value="Urgent" class="text-warning">Urgent</option> <option value="Important" class="text-primary">Important</option> </select> </div> <div class="submit pe-5" style="padding-left: 100px; padding-top: 10px;" > <input type="submit" class="btn btn-outline-success me-5" value="Save"> </div> </form>