Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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> -
In django-rest-framework, I want to output the childdb in the same parentdb by putting the parentdb name in the url parameter
There is a model that binds the user with a foreignkey. What I want to do is set the url parameter to I'm writing an api that prints the items of children with the same parent when I put as_view/int:parentpk, but I can't implement it due to my lack of skills. Please help Here is a model.py that accepts a user as a foreignkey class TestingTasks(models.Model): Taskname = models.CharField(max_length=100, unique=True) dateofuse = models.DateTimeField(auto_now_add=True) Compressing = models.TextField() Path = models.FileField(null=True) parent_id = models.ForeignKey(User,related_name='users', on_delete=models.CASCADE,default=1) And here is views.py class TestingAPI(APIView): permission_classes = [AllowAny] def get(self, request, company_id): instance = TestingTasks.objects.filter(parent_id=id) serializer_class = TestingSerializer(instance) return Response(serializer_class.data) Here is urls.py path("Testing/<int:parent_id>",views.TestingAPI.as_view()) I need to implement a total of three get, put, and delete, but I can't do the rest because I can't get. I'd appreciate it if you could give me a direction on how to do it. Have a nice day. -
Task overlap in Django-Q
I have a task that I want to run every minute so the data is as fresh as possible. However depending on the size of the update it can take longer than one minute to finish. Django-Q creates new task and queues it every minute though so there is some overlap synchronizing the same data pretty much. Is it possible to not schedule the task that is already in progress? -
how can i call two functions from views.py in url.py?
I would like to call two functions from views.py i.e 'Register' and 'Login'. Both functions are returning the following render: return render(request, 'dashboard.html') Now, what do I have to write in url.py for calling both functions under one URL? Basically, registration and login are not two separate HTML pages. They are pop-ups on my home page that appear when you click on the register or login button. views.py def Register(request): global fn,ln,s,em,pwd if request.method == 'POST': m=sql.connect(host="localhost",user="root",passwd="12345",database="website") cursor = m.cursor() d = request.POST for key, value in d.items(): if key == "first_name": fn = value if key == "last_name": ln = value if key == "sex": s = value if key == "email": em = value if key == "password": pwd = value c = "insert into users Values('{}','{}','{}','{}','{}')".format(fn,ln,s,em,pwd) cursor.execute(c) m.commit() return render(request, 'dashboard.html') def Login(request): global em,pwd if request.method=="POST": m=sql.connect(host="localhost",user="root",passwd="12345",database='website') cursor=m.cursor() d=request.POST for key,value in d.items(): if key=="email": em=value if key=="password": pwd=value c="select * from users where email='{}' and password='{}'".format(em,pwd) cursor.execute(c) t=tuple(cursor.fetchall()) if t==(): return render(request,'error.html') else: return render(request,"welcome.html") return render(request,'dashboard.html') -
How to write activity history in Django, when we have more than one ManyToMany fields in the model?
We are using 'actstream' library and its not updating the actual many2many field id values into history table. Always its updating as an empty list instead of list of ids. class Parent(): name = models.CharField(max_length=255) tags = TaggableManager(blank=True) def __str__(self): return self.name class Table1(): name = models.CharField(max_length=255, null=True) type = models.CharField(max_length=255, null=True) parent_id = models.ManyToManyField(ParentTable, blank=True, related_name='%(class)s_parent_id') tags = TaggableManager(blank=True) def __str__(self): return self.name 'id' is auto incremented value in Django table. Once we call a save() method, then post_save signal will execute for logging additional information in the actstream table.tags and parent_id is updating as [] instead of user sending values in the actstream_action table.we are using @receiver(post_save) annotation and executing action.send() accordingly @receiver(post_save) def capture_models_post_save(sender, instance, created, **kwargs): userInfo = get_current_user() action.send(userInfo, verb='created',description='created',action_object=instance, modification=model_to_dict(instance)) -
Using the URLconf defined in learning_log.urls, Django tried these URL patterns, in this order:
Below are my url patterns from learning logs from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('learning_logs/', include('learning_logs.urls')), ] And below is the url I'm adding """Defines URL patterns for learning_logs""" from django.urls import path from . import views app_name = 'learning_logs' urlpatterns = { # Home page path('', views.index, name='index'), # Show all topics path('topics', views.topics, name='topics'), # Detail page for a single topic path(r'^topics/(?P<topic_id>\d+)/$', views.topic, name='topic', ), # Page for adding a new topic path('new_topic', views.new_topic, name='new_topic'), } Below is the error I'm getting from my browser Using the URLconf defined in learning_log.urls, Django tried these URL patterns, in this order: admin/ learning_logs/ new_topic [name='new_topic'] learning_logs/ ^topics/(?P<topic_id>\d+)/$ [name='topic'] learning_logs/ topics [name='topics'] learning_logs/ [name='index'] The current path, learning_logs/topics/(?P1\d+)/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. My Python version environments are Python 3.10 Django 4.1.1 IDE-PyCharm -
django.db.utils.OperationalError: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory
When I am running the command python3 manage.py runserver its running successfully but same command is run through docker run command then its throwing this error django.db.utils.OperationalError: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket? -
Django proper way to model a one-to-one relationship
I'm looking for proper way to model such statements in Django: 1. "A Condition has exactly 2 Blocks: leftBlock and rightBlock" 2. "LeftBlock and RightBlock have the same fields in common" 3. "Blocks must be different in a Condition" 4. "A Block only belongs to 1 Condition" Here my reasoning: I identified 2 models: Condition and Block. To express 1, Condition must have 2 fields named like "left_block" "right_block" To express 2, it is enough one model called Block instead of 2 that are redundant. As for 3, this may be done with DJango CheckConstraint but I'm not sure. As for 4, I believe that we have one-to-one relationship between Condition and Block. Finally, my models: class Condition(models.Model): condition_id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, unique=True) left_block = models.OneToOneField(Block, on_delete=models.CASCADE, null=True, related_name='left_block') right_block = models.OneToOneField(Block, on_delete=models.CASCADE, null=True, related_name='right_block') class Block(models.Model): block_id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, unique=True) name = models.CharField(max_length=16) So, is this correct? If not, how can I handle such situation?