Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
User Creation Form Django - add RecaptchaField
I'm trying to add captcha field to Django UserCreationFrom and I can not solve it. I can not post everything what I tried because I'm trying modify this view about 2 hours. I have register form on my site made by Django UserCreationFrom - everything is ok but I decied to add Recaptcha. I have app name "accounts" and in this app I have view in which is this: from django.contrib.auth.forms import UserCreationForm, get_user_model from django.template.context_processors import request from django.urls import reverse_lazy from django.views import generic from captcha.fields import ReCaptchaField from captcha.widgets import ReCaptchaV2Checkbox class SignUpForm(UserCreationForm): class Meta: model = get_user_model() fields = ('first_name', "last_name", "username", "email", "password1", "password2") class Captcha(UserCreationForm): captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox) class SignUpView(generic.CreateView): form_class = SignUpForm success_url = reverse_lazy("login") template_name = 'accounts/signup.html' Signup.html looks like this: {% extends 'main.html' %} {% block title %} Přihlášení {% endblock %} {% block content %} <h2>Registrace</h2> <div class="box"> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit"> Registrovat </button> </form> </div> {% endblock %} I installed the django-recaptcha library - added it in settings. Also I have in settings my RECAPtCHA_PUBLIC and PRIVATE KEY and I'm registered in Google_recaptcha website. My URLS looks like this: from django.contrib import admin … -
Redirect user to previous page after submitting form in Django
I am trying to redirect the user to the previous page once a form is submitted. To make it clear this is what the process would look like User starts on Venue_id page and clicks on product id User is directed to Product_id page and find a form User completes form and submit on Product_id page user redirect to Venue_id page upon form submission I found a good source of inspiration on the forum, particularly on this page (How to redirect to previous page in Django after POST request) (I also found some posts using the history of the browser. But decided to stick to this method, as it seems using browser history doesn't always work) I used next as suggested in the code in the above post. But there is something I don't understand which is probably why I get this wrong. Here is the different codes in views I tried for next: next = request.POST.get('next','/') => this sends me to '/', which is not what i want. However it seemed to work for the person who posted the original question even though they were trying to NOT be redirect to '/'; next = request.POST.get('next','') => sends me to … -
Custom class for Error and Success Massages in Django Rest Framework
I wrote most of the codes and there are many return statements like this... except Comments.DoesNotExist: return Response({"response": False, "return_code": "comments_not_exist", "result": "Comment_Get_Failed", \ "message": errors["comments_DoesNotExist"]}, status=status.HTTP_400_BAD_REQUEST) ...... except Exception as error: return Response({"response": False, "return_code": "internal_code_error", "result": "Comment_Get_Failed", \ "message": str(error)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) ...... I was tired that. return_response.CustomException(detail={"your": "exception", "some_other": "key", "response": "key2", \ "result": "key3",}, status_code=status.HTTP_404_NOT_FOUND) but I don't think that's good practice. Looks like it's the same as return. I want to Implement a class that should contain all input shortcuts. Is there any better way to do that? Output should be like that. { "response": True / False, "return_code": "Success / Failed", "result": "..." "message": "Successfully Failed :)" } -
How to equate the field of a model with another field in the same model?
I would like the external_id field to always inherit the temporary_id values (for experimental purposes). I just want it to be equal to the temporary_id field. How do I do this? # External parts Lookup table class External(models.Model): temporary_id = models.CharField(max_length=32, unique=True) # Unique temporary external id actual_id = models.CharField(max_length=32, unique=True, blank=True) # Unique actual external id external_id = temporary_id # Display below in admin def __str__(self): return f"{self.external_id}" -
How to populate DB from Facebook response using python-social-auth
I have Django with python-social-auth installed. My custom user model: class User(AbstractUser): """Custom User model.""" username = None email = models.EmailField(blank=False, unique=True, verbose_name=_("Email")) facebook_link = models.URLField(blank=True, verbose_name=_("Facebook profile link")) contacts = models.CharField(blank=True, max_length=250, verbose_name=_("Contacts")) hometown = models.CharField(blank=True, max_length=250, verbose_name=_("Hometown")) start_coordinates = models.CharField(blank=True, max_length=100, verbose_name=_("Start coordinates")) avatar = ProcessedImageField( upload_to="avatar/", format="JPEG", options={"quality": 80}, default="avatar/default_avatar.jpg", verbose_name=_("Image"), ) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] I do succesfull authentication with Facebook with this code: SOCIAL_AUTH_USER_MODEL = 'accounts.User' SOCIAL_AUTH_USERNAME_IS_FULL_EMAIL = True SOCIAL_AUTH_LOGIN_REDIRECT_URL = 'home' SOCIAL_AUTH_LOGIN_URL = 'login' SOCIAL_AUTH_FACEBOOK_SCOPE = ['email', 'user_link', 'user_hometown'] SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'fields': 'id, name, email, picture.type(large), link, hometown' } SOCIAL_AUTH_FACEBOOK_EXTRA_DATA = [ ('name', 'name'), ('email', 'email'), ('picture', 'avatar'), ('link', 'facebook_link'), ('hometown', 'hometown'), ] As a result, I have a new user instance created in DB with the automatically populated fields: fist_name, last_name, email. How do I can populate the rest of fields (facebook_link, hometown) with data from response? -
How to get started building a web video conferencing site?
I started coding early this year and have done little projects here and there like a chat bot, to do list etc. I want to do a few advanced full stack projects in the span of a year that will give me a deep dive understanding. Basically, I want to build a big project and learn as I go. I don't really care how long that takes. One of these projects is a web conferencing app like google meet but specifically to conduct coding interviews. It will have all the usual web conferencing features with an added code playground. I know it is ambitious project. However, I am having a hard time figuring out what tech stack to use. I wanted to use Vue for any frontend elements (which I know are not much) but simply because I want to pick up the framework. I am mostly a python person so I was wondering if I could use django on the backend? I am okay with using express to but just prefer python. I also want to use third party frame works. I am yet to research deeply but maybe agora, webRTC or socket or something idk Any advice would … -
how to select data from an external database and put them in django's database?
hello I'm a beginner in Django/python I have a python program in root folder that fill a database created in the same folder I want to take these data and put them in my Django's database dB.sqlite3 how can I do this, please? -
How do you make a synced volume with Docker, Django and Gunicorn?
Google solutions does not help, I feel like the problem is in me using Gunicorn as local server. I just cant get my volume to sync and update with me changing local files, how do I do that? Force re-build volume ever ytime sounds like something highly inefficient Tried used Watchtower but had no luck as well compose.yml services: back: container_name: blog-django build: ./blog-master command: gunicorn blog.wsgi:application --bind 0.0.0.0:8000 expose: - 8000 links: - db volumes: - .:/app - blog-django:/usr/src/app/ - blog-static:/usr/src/app/static env_file: ./.env depends_on: db: condition: service_healthy nginx: container_name: blog-nginx build: ./nginx/ ports: - "1337:80" volumes: - blog-static:/usr/src/app/static links: - back depends_on: - back db: container_name: blog-db image: postgres:14 restart: always expose: - "5432" environment: - POSTGRES_DB=docker - POSTGRES_USER=docker - POSTGRES_PASSWORD=docker ports: - "5432:5432" volumes: - pgdata:/var/lib/postgresql/data/ healthcheck: test: ["CMD-SHELL", "pg_isready -U docker"] interval: 5s timeout: 5s retries: 5 mailhog: container_name: mailhog image: mailhog/mailhog #logging: # driver: 'none' # disable saving logs expose: - 1025 ports: - 1025:1025 # smtp server - 8025:8025 # web ui volumes: blog-django: blog-static: pgdata: Dockerfile FROM python:3.9.6-alpine WORKDIR /usr/src/app/ # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev … -
Where in Django Charfield() is max_length defined as compulsory?
I have a Django app and trying to understand the logic on how to read docs correctly in order to e.g. create a Charfield object. So here is my model: from django.db import models class Person(models.Model): f_name = models.CharField() . . . . . . If I run the app I get the error: Charfields must define a 'max_length' attribute I get that I need to do: f_name = models.CharField(max_length=40) But why? when I read the code for Charfield it's not there, so I read the code for its superclass Field but I don't see where max_length is set to be compulsory! Please assist (new to oop) Thank you :)