Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What's wrong with my Django app deployed with Heroku? Server error 500
I made a blog using Django. I deployed it with Heroku, but when I load the page, it said Server Error 500. It is not loading my templates. What could went wrong? Maybe my settings.py is not sat up correctly. I'm new in Django and Heroku, so if anyone can help me, I would be thankful. Here is my file tree: Here is my settings.py: Here is a Heroku log: » Warning: heroku update available from 7.53.0 to 8.0.2. 2023-03-25T21:45:52.759511+00:00 app[web.1]: [2023-03-25 21:45:52 +0000] [2] [INFO] Starting gunicorn 20.1.0 2023-03-25T21:45:52.759842+00:00 app[web.1]: [2023-03-25 21:45:52 +0000] [2] [INFO] Listening at: http://0.0.0.0:32581 (2) 2023-03-25T21:45:52.759886+00:00 app[web.1]: [2023-03-25 21:45:52 +0000] [2] [INFO] Using worker: sync 2023-03-25T21:45:52.762814+00:00 app[web.1]: [2023-03-25 21:45:52 +0000] [7] [INFO] Booting worker with pid: 7 2023-03-25T21:45:52.816818+00:00 app[web.1]: [2023-03-25 21:45:52 +0000] [8] [INFO] Booting worker with pid: 8 2023-03-25T21:45:53.000000+00:00 app[api]: Build succeeded 2023-03-25T21:45:53.195760+00:00 heroku[web.1]: State changed from starting to up 2023-03-25T21:46:07.408261+00:00 app[web.1]: 2023-03-25 21:46:07 [8] [ERROR] pathname=/app/.heroku/python/lib/python3.11/site-packages/django/utils/log.py lineno=224 funcname=log_response Internal Server Error: /accounts/login/ 2023-03-25T21:46:07.408275+00:00 app[web.1]: Traceback (most recent call last): 2023-03-25T21:46:07.408276+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.11/site-packages/django/core/handlers/exception.py", line 47, in inner 2023-03-25T21:46:07.408276+00:00 app[web.1]: response = get_response(request) 2023-03-25T21:46:07.408276+00:00 app[web.1]: ^^^^^^^^^^^^^^^^^^^^^ 2023-03-25T21:46:07.408277+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.11/site-packages/django/core/handlers/base.py", line 181, in _get_response 2023-03-25T21:46:07.408278+00:00 app[web.1]: response = wrapped_callback(request, *callback_args, **callback_kwargs) 2023-03-25T21:46:07.408278+00:00 app[web.1]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ … -
Some files "rollback magically" to previous versions, probably related to DST - Daytime saving light (Also could be Django-related issue)
I'll try to give as much details as possible, as this problem is very strange to me (I've never seen this in +10 years of production servers maintenance), and I couldn't fully understand what happened, and how to prevent this to happen in the future. I'd love to hear your feedbacks. Chapter 1: The context and the problem I've got this one Django server production (running with Gunicorn), where a few instances of Django run (3, to be exact). For your information, this server runs on CentOS 7.5.1804. This morning, one of my Django instance (the most important one) was out of service (classic HTTP 502). First clue, I've got the message warning mydjangoinstance.service changed on disk. run 'systemctl daemon-reload' to reload units when I attempt to restart the service (my Django instances run with systemctl daemon). I don't really pay attention - know I should have tho - since we didn't make any recent changes to the .service file... After a small investigation, I notice that some critical files of my Django installation of this instance has changed, for no apparent reasons, they "rollback" to a far previous version. If you're familiar with Django architecture, it concerns files such … -
Nested forloop counter in django template
I created one django template, there i have nested 3 for loop there. i need to make forloop counter: {% for i in myloop1 %} {% for j in i.loop2 %} {% for k in j.func %} {{forloop.parentloop.counter}}_{{ forloop.counter }} {% endfor %} {% endfor %} {% endfor %} -
How to fix nested DRF serializer API response value is being inside list?
I have a problem with nested serializer. I'm using class absed validators, and raise custom Validation error that returns dictionary with key value paris that looks like this { "details": "Some error details", "summary": f"Field has error" } but when I'm raising error from nested serializer it has dufferent format, where value is an list instead of string "tags": [ { "details": [ "'My field' should not contain spaces" ], "summary": [ "Field Tag 'One more filed' should not contain spaces" ] } ] expected response "tags": [ { "details": "'My field' should not contain spaces", "summary": "Field Tag 'One more filed' should not contain spaces" } ] serializers.py class PostSerializer(serializers.ModelSerializer): user = serializers.SlugRelatedField(slug_field="name", read_only=True) title = serializers.CharField(required=True, validators=[TitleValidator()]) content = serializers.CharField(required=True) tags = TagSerializer(many=True, required=False) tag serializer module class TagSerializer(serializers.ModelSerializer): tag = serializers.CharField(min_length=3) class Meta: model = Tags fields = ["tag"] validators=[TagValidator()] class TagValidator: def __call__(self, tags: OrderedDict): tag = list(tags.values())[0] errors = [] if " " in tag: errors.append(f"'{tag}' should not contain spaces") if len(errors) > 0: raise PostException.validation_error( errors, "Tag", ) return tags erros.py file class PostException(Exception): @staticmethod def validation_error(error, field, **kwargs) -> ValidationError: data = { "details": error, "summary": f"Field {field} {error[0]}" } return ValidationError(data) When … -
EC2 Django instance ERR_ADDRESS_UNREACHABLE from outside
I have an EC2 instance working with NGinx and Gunicorn. Nginx is running fine. Gunicorn is running fine. Django app is running fine. When i curl -v 127.0.0.1:80 on the machine, i receive the home page. OK. But when i curl -v public_ip_address:80 or curl -v public_dns_address:80 i got unreachable error. So i simplify my nginx configuration with server { listen 80; server_name my_public_dns my_public_ip; return 200; } to reduce errors to the minimum. It's still the same error. My iptable : sudo iptables -vnL Chain INPUT (policy ACCEPT 0 packets, 0 bytes) pkts bytes target prot opt in out source destination 6 340 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:80 flags:0x17/0x02 ctstate NEW 2 120 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:8080 flags:0x17/0x02 ctstate NEW 80 port is obviously open in EC2 instance's security group. Firewall is ok. sudo ufw status verbose Status: inactive So it doesn't seem to be some of firewall, port, nginx, gunicorn error. I'm stuggling on it for few days ago. -
inner loop in button group django
I have two loops one iterates over the users and one to delete the users. Problem is the code is showing users next to each other and the button with svg icon next to each other, how can I append the user buttons with their svg icons? my Template: <div class="btn-group me-2 mb-2"> {% for user in usecase_assigned %} <button type="button" class="btn btn-outline-danger">{{user|join:', '}}</button> {% endfor %} {% for unassign in user_assigned %} <form action="{% url 'unassign_emp' eid=unassign.0 ucid=result.usecase_id %}" method="POST"> {% csrf_token %} <button type="submit" class="btn btn-danger" name="unassign_emp"> <svg xmlns=http://www.w3.org/2000/svg width="16" height="16" fill="currentColor" class="bi bi-file-x-fill" viewBox="0 0 16 16"> <path d="M12 0H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2zM6.854 6.146 8 7.293l1.146-1.147a.5.5 0 1 1 .708.708L8.707 8l1.147 1.146a.5.5 0 0 1-.708.708L8 8.707 6.854 9.854a.5.5 0 0 1-.708-.708L7.293 8 6.146 6.854a.5.5 0 1 1 .708-.708z"></path> </svg> </button> </form> {% endfor %} </div> what I'm getting: -
How to step forward queryset items to their foreignkey item in another model
class User(AbstractUser): id = models.BigAutoField(primary_key=True) class Follow(models.Model): id = models.IntegerField(primary_key=True) userPointer = models.ForeignKey(User, on_delete=models.CASCADE, related_name="follower") userTarget = models.ForeignKey(User, on_delete=models.CASCADE, related_name="followed", null=True) A users id passes to views, I want return followers queryset. I have tried:↓ test = User.objects.get(pk=request.user.id).follower.all() Now a qureryset of Follow model is generated. But I need each item be translate to it's appropriated userTarget foreignkey. test = User.objects.get(pk=request.user.id).follower.all().userTarget This not work! -
Django cannot compare string
I get data from 2 table by search key_id in Data table and find key_name in Key table like this. data=Data.objects.filter(username=username) key=Key.objects.filter(key_id__in=data.values_list('key_id')) data = {'data':data, 'key':key} return render(request,'form.html', data) In html I want to show data key_name which key_name is in table Key . So, I have to use for loop like this code. {% for data in data %} {% for key in key %} {% if data.key_id == key.key_id %} {{ key.key_name }} {% endif %} {% endfor %} {% endfor %} The output not show anything If I run this code outside if tag. {{ key.key_id }} It show output like this. 001 002 001 002 And if I run this code outside if tag. {{ data.key_id }} It show output like this. 001 001 002 002 Why when I compare it not show anything. How to fix it? -
Hat jemand lust gemeinsam ein Python Webprojekt zu starten?
Ich würde gerne ein Python webprojekt mit z.B. Django zu ertsellen, wenn jemnad Interesse hat gerne Kommentar oder PN. Ich würde gerne ein Python webprojekt mit z.B. Django zu ertsellen, wenn jemnad Interesse hat gerne Kommentar oder PN. -
manage.py migrate causes 'staticmethod' object is not callable
I'm trying to do python manage.py migrate on a cPanel but I keep getting TypeError: 'staticmethod' object is not callable. makemigations and collectstatic work fine. I've attempted to fix this by installing WhiteNoise but it didn't work. In base.py I have: STATICFILES_DIRS = [ os.path.join(PROJECT_DIR, "static"), ] STATICFILES_STORAGE = "django.contrib.staticfiles.storage.ManifestStaticFilesStorage" STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_URL = "/static/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") MEDIA_URL = "/media/" in urls.py I have: urlpatterns = [ re_path(r'^images/([^/]*)/(\d*)/([^/]*)/[^/]*$', ServeView.as_view(), name='wagtailimages_serve'), path('tz_detect/', include('tz_detect.urls')), # path("django-admin/", admin.site.urls), path("admin/", include(wagtailadmin_urls)), path("documents/", include(wagtaildocs_urls)), path(r'sitemap.xml', sitemap), path('robots.txt', RobotsView.as_view()) ] if settings.DEBUG: from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns # Serve static and media files from development server urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns = urlpatterns + [ path('__debug__/', include('debug_toolbar.urls')), path("", include(wagtail_urls)), ] I printed them in production (in the cPanel) and path to each looks correct. -
Can I send a csrf cookie-token from javascript to a Django api?
I have a SAP (written in the Svelte framework) and presented by Netlify. The business logic and data is handled by a Django app. So far I have only used GET and everything works well. But now I want to upload a file's content and use POST. When I try to POST to the Django app I get a 403 error, specifically: WARNING:django.security.csrf:Forbidden (Origin checking failed - http://localhost:8888 does not match any trusted origins.): /test-put/ I think I have overcome any CORS issues (see this question). The call to the Djnago API is javascript async function sendDataToAPI(payload) { let endpoint = 'http://192.168.4.28:8000/test-put/' const form_data = new FormData(); form_data.append("payload", payload); await fetch(endpoint, { credentials: "same-origin", method: "POST", body: JSON.stringify({ data: payload, }), headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', "X-CSRFToken": getCookie("csrftoken"), }, }) .then((response) => response.json()) .then((result) => { console.log("Success:", result); }) .catch((error) => { console.error("Error:", error); }); } function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { … -
Django how to get data from table of ForeignKey
I create Table DeviceKey and UserKey which api_key is ForeignKey to api_key in DeviceKey. class DeviceKey(models.Model): api_key=models.CharField(max_length=100,unique=True) api_key_name=models.CharField(max_length=100) def __str__(self): return self.api_key class UserKey(models.Model): username = models.CharField(max_length=100) api_key=models.ForeignKey(DeviceKey,on_delete=models.CASCADE) def __str__(self): return self.username I want to show api_key_name by using api_key in table UserKey. So, I use api_key=data.api_key like this code views.py username = request.user.username data=UserKey.objects.filter(username=username) device=DeviceKey.objects.filter(api_key=data.api_key) data = {'userkey':data, 'device':device} return render(request,'userkey_form.html', data) I create html file like this. {% for userkey in userkey %} {{ device.api_key_name }} {% endfor %} When I run it show error like this. 'QuerySet' object has no attribute 'api_key' It error at this line. How to fix it? device=DeviceKey.objects.filter(api_key=data.api_key) -
How to use Postgres mode() function in Django
How can I use Postgres' mode() WITHIN GROUP function in Django aggregations? -
My Html page is showing the {% extends "/tasks/layout.html" % } statement in the page preview, I am using Django how do i solve this problem??
this is my layout.html <!DOCTYPE html> <html lang="en"> <head> <title>Tasks</title> </head> <body> {% block content %} {%endblock%} </body> </html> this is my index.html {% extends "/tasks/layout.html" % } {% block body%} <h1> VIEW BLOCK</h1> <ul> {% for task in tasks%} <li>{{task}}</li> {%endfor%} </ul> <a href="{% url 'tasks:add' %}">Add a new Task</a> {%endblock%} How do i remove this exteneng statement from my HTML page i want to remove the extnend from the HTML page can anyone help -
Trying to create record in django results in some fields being ignored
I have a form where I collect information, but some more processing needs to be done before I save the data, so rather than using form.save I am trying to create the record directly. However when the record is created manually, no matter what approach I use, only one field is being saved (the 'message' field). I have a pretty simple model, with just 4 fields: class PaymentReceived(models.Model): name = models.CharField(verbose_name='First name', max_length=50, blank=True), pay_amount = models.IntegerField(null=False, blank=False), date = models.DateTimeField(auto_now_add=True), message = models.TextField(max_length=500, blank=True) I've tried 3 different methods to create a new record: 1: new_payment = PaymentReceived(name=request.session['name'],message=request.session['message'],pay_amount=request.session['pay_amount']) new_donaton.save() 2: new_payment = PaymentReceived.objects.create(name=request.session['name'],message=request.session['message'],pay_amount=request.session['pay_amount']) 3: new_payment = PaymentReceived() new_payment.name= request.session['name'] new_payment.message = request.session['message'] new_payment.pay_amount = request.session['pay_amount'] new_payment.save() Each of the values I am pulling from the sessions all have data in them, none are blank (confirmed several times), and when the message field is saved, it contains the data it should, just the name and pay_amount fields are not being saved for some reason. When I try to use the second method in particular, I get the error that: PaymentReceived() got unexpected keyword arguments: 'name', 'pay_amount' With those same fields not showing up in the saved record if I use … -
Django forms out as UL and not DIV
Just upgraded my Django app from version 3.2 to version 4.1. When I now render a form with multiple choices it renders each item as a div and not li. Sample code as follows: from django import forms CHOICES = [] for i in range(1, 20): CHOICES.append((str(i),str(i))) class ChoicesForm(forms.Form): choices = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple(), choices=CHOICES) form = ChoicesForm() print(form) The output(shortened) of the print(form) is <tr> <th><label>Choices:</label></th> <td> <div id="id_choices"><div> <label for="id_choices_0"><input type="checkbox" name="choices" value="1" id="id_choices_0"> 1</label> </div><div> <label for="id_choices_1"><input type="checkbox" name="choices" value="2" id="id_choices_1"> 2</label> </div><div> <label for="id_choices_2"><input type="checkbox" name="choices" value="3" id="id_choices_2"> 3</label> </div><div> <label for="id_choices_3"><input type="checkbox" name="choices" value="4" id="id_choices_3"> 4</label> But what I was getting in my earlier code was <tr><th><label>Choices:</label></th><td><ul id="id_choices"> <li><label for="id_choices_0"><input type="checkbox" name="choices" value="1" id="id_choices_0"> 1</label> </li> <li><label for="id_choices_1"><input type="checkbox" name="choices" value="2" id="id_choices_1"> 2</label> </li> <li><label for="id_choices_2"><input type="checkbox" name="choices" value="3" id="id_choices_2"> 3</label> </li> <li><label for="id_choices_3"><input type="checkbox" name="choices" value="4" id="id_choices_3"> 4</label> I can't find any reference to why this would change. Nor can I figure out how to create my form output as a list and not Is this expected or is there something else I am missing ? What I ultimately want to achieve is to format the output as rows of items and not a column … -
Exception inside application: No route found for path 'ws/chat/room/2/'
Problem with Django channels. Please help. my routing.py websocket_urlpatterns = [ url(r'ws/chat/room/(?P<room_id>\d+)/$', ChatConsumer.as_asgi()), ] my room.html var chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/room/{{ room.id }}/' ); my settings.py path('chat/', include('chat.urls', namespace='chat')), my chat_urls.py path('room/<int:room_id>/', views.room, name='room'), path('room/<int:room_id>/send_message/', views.send_message, name='send_message'), websocket.url = ws://127.0.0.1:8000/ws/chat/room/2/ changed re_path a lot of times, asked chatgpt to write new html template (I'm more into Django then in JS). -
I connected a MySQL database to Django, but the user information is not being retrieved
class Review(models.Model): review_id = models.BigAutoField(primary_key=True) review_content = models.CharField(max_length=255, blank=True, null=True) review_grade = models.FloatField() user_id = models.BigIntegerField() book_isbn = models.CharField(max_length=32) created_date = models.DateTimeField(blank=True, null=True) modified_date = models.DateTimeField(blank=True, null=True) class Meta: db_table = 'review' class User(models.Model): user_id = models.BigAutoField(primary_key=True) created_at = models.DateTimeField() email = models.CharField(unique=True, max_length=64) username = models.CharField(unique=True, max_length=32) nickname = models.CharField(unique=True, max_length=32) password = models.CharField(max_length=128) user_type = models.IntegerField(blank=True, null=True) user_role = models.IntegerField(blank=True, null=True) age = models.IntegerField() sex = models.IntegerField() prefer_score = models.IntegerField(blank=True, null=True) class Meta: managed = True db_table = 'user' "This is the code written in models.py." >>> User.objects.all() <QuerySet []> >>> Review.objects.all() <QuerySet [<Review: Review object (1)>, <Review: Review object (2)>, <Review: Review object (3)>, <Review: Review object (4)>]> "This is what I tried in the Django shell_plus. Although there is data in the database, I can't figure out why the User data returns an empty queryset. Please help me." "I ran python manage.py makemigrations and python manage.py migrate. I also tried to find information about Django custom user model, but I couldn't solve the issue." -
how to pass the url into the view context in django?
page_title.html <!-- page title --> ... <ul class="list-inline custom-breadcrumb mb-2"> <li class="list-inline-item"><a class="h2 text-primary font-secondary" href="{% url 'teacher-list' %}">{{list_title}}</a></li> ... <!-- /page title --> views.py class TeacherDetailView(DetailView): model = Teacher context_object_name = "teacher" template_name = "users/teacher_detail.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['list_title'] = "Our Teachers" return context So currently have a teacher_detail page, on that page there is a page_title section (which is being included inside other templates) which has a url that allows you to go to the list view version of it, in this case it is the teacher_list page. The problem is that i have multiple pages with similar design, i know how that i can pass in the list_view variable as a part of the view context which makes it dynamically displayed depending on the page. I wonder how i can also pass in the url as a dynamic variable into the view context like: context['list_url'] = "{% url 'teacher-list %}" so that i don't have to repeat it and also will be able to reuse the page_title sub template? -
Choosing framework for streaming video for better performance
I have a task to create an API for streaming images that my backend gets through a GRPC connection. The question is: what python framework is best suited for this job? I'd like to know if there is any framework that support having a single streaming response for multiple clients. I mainly use Django, but I've heard that it would be a bad choice for this kind of task since it'd allocate a separate process for every new connection, and that would result in bad performance. I've looked into websocket implementations with Django, but I'm still not sure what the best decision is for this kind of task. -
D3 bar chart returning height of "NaN"
I'm attempting to display a basic animated line-chart using D3 (v7) to my web page. This is being done from within a Django project and so my chart is being fed data from my views.py file. However, the chart only partially displays on the page. The x and y axis lines are displayed, along with the axis labels. Here is my error message: Error: <rect> attribute height: Expected length, "NaN". Here is the relevant part of my html template: <div id="chart-container"></div> <script src="https://d3js.org/d3.v7.min.js"></script> <script type="text/javascript"> const data = JSON.parse('{{ assign_levels|safe }}'); const margin = {top: 10, right: 30, bottom: 140, left: 60}; const width = 400 - margin.left - margin.right; const height = 500 - margin.top - margin.bottom; const svg = d3.select("#chart-container") .append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); const x = d3.scaleBand() .range([0, width]) .domain(data.map(d => d.level_assign)) .padding(0.3); const y = d3.scaleLinear() .range([height, 0]) .domain([0, d3.max(data, d => d.count)]); svg.append("g") .call(d3.axisLeft(y)); svg.selectAll(".bar") .data(data) .enter() .append("rect") .attr("class", "bar") .attr("x", d => x(d.level_assign)) .attr("width", x.bandwidth()) .attr("y", height) .attr("height", 0) .attr("fill", "#5F9EA0") .transition() .duration(1000) .delay((d, i) => i * 100) .attr("y", d => y(d.count)) .attr("height", d => height - y(d.count)); svg.append("g") .attr("transform", … -
I removed all firewalls but still can not access my webpage via vpn
I am just got my first Raspberry Pi and decided to host little website project using Django. Everything was running smoothly until the firewall part. I was not sure why externally other can not access my webpage, I do not see any errors on host. I completely removed all firewalls on my host (by default Raspberry Pi had: iptables), also changed django project settings and allowed all hosts. But still can not access webpage through mobile internet, vpn or though friends phone. Not sure what is going on. Website is accessible through devices that are connected to my wifi. But I though removing all firewalls will allow access to any device. This is how I deleted iptable from my host I also noticed message mentioning about replacing iptable with nftable. Just in case I also removed nftable, which should leave my webpage totally naked and without firewall protection. But still can not access it 😔 In case you missed I am using: Raspberry Pi Zero W OS: Linux raspberrypi 6.1.19+ #1637 Tue Mar 14 11:01:56 GMT 2023 armv6l GNU/Linux Project: Django 2.2.19 Note: Nginx and Gunicorn works perfectly fine. My website is accessible and working through my wifi. I know … -
I want to grab all my data from my forms and save to the DB
I wanna grab those fields and save to my db. But i get this error. 'User() got unexpected keyword arguments: speciality, start_year.... etc etc' I have two types of user Student and Teacher. So i have a custom user model. i have almost 3 months learning Django. I hope you can help me, thank you. #My forms. class StudentSignupForm(forms.Form): email = forms.EmailField( widget=forms.EmailInput( attrs={ "class": "form-control", "placeholder": "Email", } ) ) username = forms.CharField( min_length=3, max_length=20, widget=forms.TextInput( attrs={"class": "form-control", "placeholder": "Username"} ), ) first_name = forms.CharField( min_length=5, max_length=50, widget=forms.TextInput( attrs={"class": "form-control", "placeholder": "First name"} ), ) last_name = forms.CharField( min_length=5, max_length=50, widget=forms.TextInput( attrs={"class": "form-control", "placeholder": "Last name"} ), ) nation = forms.ChoiceField(choices=NATIONALITY_CHOICES, required=False) sex = forms.ChoiceField(choices=SEX_CHOICES, required=False) phone = forms.CharField( min_length=5, max_length=50, widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "Phone"}), ) address = forms.CharField( min_length=5, max_length=50, widget=forms.TextInput( attrs={"class": "form-control", "placeholder": "Address"} ), ) department = forms.ChoiceField(choices=DEPARTMENT_CHOICES, required=False) speciality = forms.ChoiceField(choices=SPECIALITY_CHOICES, required=False) shift = forms.ChoiceField(choices=SHIFT_CHOICES, required=False) plan = forms.ChoiceField(choices=TYPE_CHOICES, required=False) medical_notes = forms.Textarea() campus = forms.ChoiceField(choices=CAMPUS_CHOICES, required=False) password = forms.CharField( label="password", widget=forms.PasswordInput( attrs={ "class": "form-control", "placeholder": " Insert a password", "id": "password", "required": "required", } ), ) password_confirmation = forms.CharField( label="password", widget=forms.PasswordInput( attrs={ "class": "form-control", "placeholder": " Confirm your password", "id": "password_confirmation", "required": "required", } … -
docker environment with django and postgres not loading the database container
I'm trying to learn how docker works, and trying to set up a react/Django image with Postgres, but I can't seem to connect to the database: This is my docker-compose.yml version: "3" services: database: image: postgres:12.7-alpine volumes: - ./backup_data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres backend: build: ./mash_backend volumes: - ./backend:/app depends_on: - database frontend: build: ./mash_frontend volumes: - ./frontend:/app depends_on: - backend ports: - 80:80 nginx_backend_server: build: ./nginx_backend_server ports: - 8000:8000 depends_on: - backend and on my seetings.py, I placed the host as database since this is the name of my container, not sure if this is correct DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'database', 'PORT': 5432, } } this is my Dockerfile on my backend: FROM python:3.8 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY . /app WORKDIR /app RUN pip3 install -r req.txt RUN python manage.py makemigrations RUN python manage.py migrate CMD gunicorn -b 0.0.0.0:8000 --worker-class=gevent --worker-connections=1000 --workers=5 backend.wsgi whenever I run a docker-compose up I got this error during the migrate psycopg2.OperationalError: could not translate host name "database" to address: Name or service not known what I'm missing here? -
Better way of checking query string parmeter in Django
I have quite some integer query string params that I convert this way. Is there built in better way ? current_page = request.GET.get('page') current_page = 0 if current_page is None else int(current_page)