Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django Procfile for heroku deployment using gunicorn
According to this documentation, the Procfile format is <process type>: <command> For example: web: gunicorn djforms.wsgi --log-file - However, I found a Django project where the Procfile was missing : after web. i.e. web gunicorn djforms.wsgi --log-file - It also worked correctly when I tried to deploy to heroku. Any Idea on why it works or issues it may cause? Any help will be appreciated! -
Django - How to add extra fields to User model?
I need to add new fields to the " real Django User model ". Why? Because I have two forms in my template with post methods in two different pages. And I created two models, each one saves the corresponding form data in the database. In my views I had to write two different functions for the forms pages. The 1st one: when there is a post request, it saves the data in the 1st Model. The 2nd one: Does the same as 1st but it saves the data in the 2nd Model. I tried to create another new model3 which contains model1 + model2 fields (Didn't delete the previous models)! But when I submit the 1st form it saves data in an object, and when I submit the 2nd form data in another new object of model3 ! So I canceled this method and now I have to try another way to do the task, So I saved the 1st form data ( which are a login info ( email, pass ) and when a user submits the form, it creates a new user with user = User.objects.create_user(request.POST.get("email"),request.POST.get("email"),password) That worked fine, and now I can modify the credentials in … -
django-taggit get number of posts that use a particular tag
What I want to do is to get the number of posts for a particular tag, kind of like how Instagram and Twitter do, I found some solutions this and this. I want to clarify if this is the only way to achieve what I want. Wouldn't it be bad to calculate the number of posts every time someone tries to access a tag? So, I created a custom tag by following these instructions, and have added a num_posts field. class Hashtag(TagBase): num_posts = models.IntegerField(default=0, blank=False, null=False) class Meta: verbose_name = _("Tag") verbose_name_plural = _("Tags") So, how do I increase the num_posts value whenever a new post uses this tag? Or when a post creates a new tag, automatically assign the value of 1 to num_posts. I tried to look into the source code of django-taggit, specifically the TaggableManager, to see if I can override something there and get the intended results. So far I was not able to do anything. Can someone please give me some assistance? -
Chart.js- Dates not displaying correctly on chart and axis labels not showing
I'm trying to label my axes on my chart. I'm using chart.js v3.9.1 and I believe I've followed the documentation, however the labels aren't showing up (see below): health_hub_tracker.html: {% extends 'base.html' %} {% load static %} {% block content %} <h1>Weight Tracker</h1> <canvas id="myChart" width="400" height="200"></canvas> <script> const ctx = document.getElementById('myChart').getContext('2d'); const myChart = new Chart(ctx, { type: 'line', data: { labels: [{%for stat in date%}{{stat}},{%endfor%}], datasets: [{ label: 'Weight (lbs)', data: [{%for stat in weight%}{{stat}},{%endfor%}], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { x: { title: { display: true, Text: 'Date' } }, y: { beginAtZero: true, title: { display: true, Text: 'Weight (lbs)' } } } } }); </script> {% endblock content %} views.py: def health_hub_tracker(request): serialized_weight = [] serialized_date = [] for stats in HealthStats.objects.filter(user=request.user): serialized_weight.append(int( stats.weight, )) date_only = stats.date.date() serialized_date.append(str( date_only )) print(serialized_weight) print(serialized_date) context = { "weight": serialized_weight, "date": … -
Trying to deploy Django app on Elastic Beanstalk: "process docker is not registered"
Trying to deploy a Django app to Elastic Beanstalk. I'm using the "Docker running on 64bit Amazon Linux 2" platform and the EB CLI. My configuration is: Dockerfile docker-compose.yml, configuring both the Django app and the NGinx server When I run eb deploy, the process runs and the environment health check is green, but nothing is actually deployed. So, when I go see the eb-engine logs, this is the error I see: [INFO] Running command /bin/sh -c systemctl show -p PartOf docker.service [ERROR] An error occurred during execution of command [env-launch] - [Start Docker]. Stop running the command. Error: startProcess Failure: process "docker" is not registered I searched online for a few hours but was unable to find a hint as to what might be wrong 😟 Files The Dockerfile is in charge of compiling static assets: # Dockerfile ARG PYTHON_VERSION=3.10-slim-buster # STAGE 1: Compile static assets # ---------------------------- FROM node:17-slim as client-builder ARG APP_HOME=/code WORKDIR ${APP_HOME} COPY . ${APP_HOME} RUN npm install && npm cache clean --force # STAGE 2: Add python dependencies # ---------------------------- FROM python:${PYTHON_VERSION} as python-build-stage ARG APP_HOME=/code \ USERNAME=pages ENV PYTHONDONTWRITEBYTECODE=1 \ PYTHONUNBUFFERED=1 \ POETRY_NO_INTERACTION=1 \ POETRY_VIRTUALENVS_CREATE=false \ POETRY_CACHE_DIR="/var/cache/pypoetry" \ POETRY_HOME="/usr/local" RUN mkdir ${APP_HOME} && … -
Django Admin: Extra field added in model form can't be displayed for view permission
I have a problem about displaying an extra field (added from forms) for a model. When a user with all permissions on a model said Foo, the user can see the initial value for the extra field in admin page. But when a user has only view permission on the Foo model, he can't see the values of the extra field. @admin.register(models.Foo) class FooAdmin(ModelAdmin): fieldsets = (('Foo', {'fields': ('extra_field'})) form = forms.FooForm And in the forms: class FooForm(forms.ModelForm): extra_field = forms.CharField() class Meta: model = models.Foo def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['extra_field'].initial = 'extra_field' If a user has all permissions on the Foo model, we can see in admin page: But if the user has only view permission on Foo model, he can't see nothing in this extra field: In my case, I would like to see in Extra field the value: extra_field. Can someone helps me please? -
Django remote user authenticate: value too long for type character varying(30)
I followed this guide to integrate Auth0 into my existing django rest project. I'm using Postman to send the necessary data provided on the "Test" tab for my Auth0 Custom API. Post works and I get an access token back. But when I try to use that token in my authorization header to access the following view: @api_view(['GET']) def private(request): return JsonResponse({'message': 'Hello from a private endpoint! You need to be authenticated to see this.'}) I get the following error: django.db.utils.DataError: value too long for type character varying(30) When I scroll through the entire error log, the problem seems to originate from the following code: def jwt_get_username_from_payload_handler(payload): username = payload.get('sub').replace('|', '.') authenticate(remote_user=username) return username Django seems to not be able to fit the username it gets back from Auth0 into the RemoteUser table when trying to authenticate. If you need to see the code, you can take a look at the link since I didn't really change a lot except for the issuer & audience obviously. I have a custom User model, so if you think that's relevant in this case, I'll happily add it to the code. -
Django built-in templates tags gets unformatted when I save my html file in VS-code
I'm using django built-in templates tags which are {% load static %} {% extends 'base.html' %} etc. so whenever I'm saving my document by pressing ctrl+s the formatting which should be gets disturbed which causes errors: Unclosed tag on line 1: 'block'. Looking for one of: endblock. before saving the document the editor looks something like this: but as soon as I save my document it becomes like this which results in the above mentioned error any solution for that? maybe add or remove some formatting extensions? -
Add extra context to a Django Flatpages template
The flatpage() view in Django's Flatpages app passes a single context item to templates, flatpage. I'd like to add more data to the context and the only way I can think of is to copy both the flatpage() and render_flatpage() functions from the original views.py into a new app. And then in my urls.py where I have this: from django.contrib.flatpages import views from django.urls import path urlpatterns = [ path("about/", views.flatpage, {"url": "/about/"}, name="about"), ] instead import from myapp import views to use my new custom view. Both of my copies of the functions would be exactly the same as originals, except render_flatpage() would add more context data. This seems over the top, copying so much code unchanged. But I don't have a better idea. I don't want to create a custom context_processor for this, because this context is specific to each Flatpage, and should not be used on on other pages. -
uWSGI always returns index.html if it can't find appropriate route in the app
I have and Django application deployed with uWSGI from which i'm also serving static files that contain index.html, javascript files built by Angular and bunch of other assets that are most images. When i did some light penetration testing, i observed some weird responses. Request like: GET /api/users/123/ returned success without any problem and i got the JSON with the specific user. Request like: GET /api/users/&document.vulnerable=true;/ returned 200 OK, and the result was just the index.html page. From my light inspecting by now, it seems if the values that are being inserted in the fuzzing process in the place /api/users/$fuzz_insert$/ contain any combinations of dots (.) or slashes (/), it cannot match it against any route in the application, and it just returns the index.html page. When i'm testing this exact same request with Django locally, i get the 404 error and page where it says that the specific url cannot be matched, even when dots and slashes are properly encoded. So i assume at first that Django has something against dots and slashes in the URL. But more confusing to me is that when deployed with uWSGI, it seems that if the 404 error in the same manner on … -
Django UpdateView FileField not dispalayed in form
model.py class Payments(models.Model): STATUS_CHOICES = ( ('', 'Нажмите на поле, чтобы выбрать статус оплаты'), ('true', 'да'), ('false', 'нет'), ) CHOICES_NAME_SERVICE = (('','Нажмите на поле, чтобы выбрать вид услуги'), ('Коммунальная услуга','Коммунальная услуга'), ('Капитальный ремонт','Капитальный ремонт'),) flats=models.ForeignKey(Flat,on_delete=models.PROTECT) name_flat=models.CharField(max_length=60, ) name_service=models.CharField(max_length=30,choices=CHOICES_NAME_SERVICE) slug=models.SlugField(max_length=60) amount_of_bill=models.DecimalField(max_digits=10,decimal_places=2) amount_of_real=models.DecimalField(max_digits=10,decimal_places=2) date_of_bill=models.DateField() date_of_payment=models.DateField(auto_now_add=True) status_payment=models.CharField(max_length=5,choices=STATUS_CHOICES,) comments=models.TextField(blank=True) bill_save_pdf=models.FileField(upload_to='Bill_pdf/%d/%m/%Y/') def __str__(self) -> str: return f'{self.name_flat}' class Meta: ordering=['name_flat'] def save(self, *args, **kwargs): self.slug = slugify(self.name_service) super().save(*args, **kwargs) def delete(self, *args, **kwargs): self.bill_save_pdf.delete() super().delete(*args, **kwargs) view.py class UpdatePayments(UpdateView): model=Payments form_class=PaymentsForm template_name='myflat/add_payment.html' context_object_name='name_flat' def get_success_url(self): print(self.object.pk) return reverse('HistoryPamentsByService' ,kwargs= {'slug':self.object.slug,'flats_id': self.object.flats_id}) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) payment=Payments.objects.get(pk=self.kwargs['pk']) context['form']=PaymentsForm(instance=payment) print(self.request.POST) return context forms.py class PaymentsForm(forms.ModelForm): class Meta: model=Payments fields=['name_service','amount_of_bill','amount_of_real', 'date_of_bill','status_payment', 'comments','bill_save_pdf'] labels = { 'name_service': ('Название услуги'), 'amount_of_bill': ('Сумма счета'), 'amount_of_real': ('Оплачено'), 'date_of_bill': ('Дата счета'), 'status_payment': ('Статус оплаты'), 'comments': ('Комментарий'), 'bill_save_pdf': ('Счет'), } widgets={ 'name_service':forms.Select(attrs={"class":"form-control"}), 'amount_of_bill':forms.NumberInput( attrs={"class":"form-control",'placeholder':'Сумма счета 0.00руб'}), 'amount_of_real':forms.NumberInput( attrs={"class":"form-control",'placeholder':'Оплачено 0.00руб'}), 'date_of_bill':forms.DateInput(format=('%Y-%m-%d'), attrs={"class":"form-control",'placeholder':'Дата счета','type':'date'}), 'status_payment':forms.Select(choices=(('','None'),), attrs={"class":"form-control"},), 'comments':forms.Textarea( attrs={"class":"form-control",'placeholder':'Комментарий...','rows':2}), 'bill_save_pdf':forms.FileInput( attrs={"class":"form-control",'placeholder':'Счет'}), } urls.py urlpatterns = [ path('',CreateNewFlat.as_view(),name='CreateFlat'), path('list_flats',ListCreatedFlats.as_view(),name='ListCreatedFlats'), path('add_payment/<int:pk>/',AddPayment.as_view(),name='AddPayment'), path('group_payments/',GroupPayments.as_view(),name='GroupPayments'), path('history_by_service/<slug:slug>/<int:flats_id>/', HistoryPamentsByService.as_view(),name='HistoryPamentsByService'), path('UpdatePayments/<int:pk>/',UpdatePayments.as_view(),name='UpdatePayments'), path('DelPayment/<int:pk>/',DelPayment.as_view(),name='DelPayment'), ] history_by_service.html {% extends "base.html" %} {% block title %} История платежей по видам услуг {% endblock title %} {% block sidebar %} <table class="table table-lg table-hover"> <thead> <tr> <th scope="col">#</th> <th scope="col">Название квартиры</th> <th scope="col">Услуга</th> <th scope="col">Сумма по счету</th> <th … -
Is there a way to get a list of Factory Boy subfactory objects from with the correct Django object type?
I have a factory boy factory that uses Django. I need to access a list of the generated objects from a SubFactory. However, whenever I attempt to get that list, I receive TypeErrors that say that my generated objects are "SubFactory" instead of the type of the object I actually need. Any idea what I'm missing? # factories.py class PartNoRelationFactory(factory.django.DjangoModelFactory): class Meta: model = PartNoRelation id = factory.Sequence(lambda n: n + 1) parent_part_no = factory.SubFactory(PART_NO_FACTORY) child_part_no = factory.SubFactory(PART_NO_FACTORY) # test_factories.py def mock_child_part_nos(arg_1: PartNo) -> 'list[PartNo]': mock_part_no_relation_one = PartNoRelationFactory() mock_part_no_relation_two = PartNoRelationFactory() mock_part_no_relation_three = PartNoRelationFactory() return [ mock_part_no_relation_one.child_part_no, mock_part_no_relation_two.child_part_no, mock_part_no_relation_three.child_part_no ] # error: "Expression of type "list[SubFactory]" cannot be assigned to return type "list[PartNo]" -
H13 (Connection closed without response) errors on Heroku scale down
I am running Django app in Docker image with uWSGI, supervisor and nginx on Heroku. I am often getting H13 (Connection closed without response) errors when the app is scaling down: This problem generates following log events: 2022-10-12T09:35:13.231318+00:00 heroku web.3 - - State changed from up to down 2022-10-12T09:35:13.774228+00:00 heroku web.3 - - Stopping all processes with SIGTERM 2022-10-12T09:35:14.028602+00:00 heroku router - - at=error code=H13 desc="Connection closed without response" method=GET path="/comments/api/assets-uuidasset/xxxx-xxxx-xxxx-xxxx-xxxxx/count/?_=1665564563" I expect the problem lies in either the socket not closing on SIGTERM signal or nginx not closing with the right signal or something similar. The first case is described in this article regarding Puma and Ruby: https://www.schneems.com/2019/07/12/puma-4-hammering-out-h13sa-debugging-story/ The second case is described here: https://canonical.com/blog/avoiding-dropped-connections-in-nginx-containers-with-stopsignal-sigquit -
Error Deploy Django Project to Heroku "heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" "?
Error : 2022-10-12T15:20:31.186252+00:00 app[web.1]: [2022-10-12 15:20:31 +0000] [4] [WARNING] Worker with pid 10 was terminated due to signal 15 2022-10-12T15:20:31.284067+00:00 app[web.1]: [2022-10-12 15:20:31 +0000] [4] [INFO] Shutting down: Master 2022-10-12T15:20:31.284096+00:00 app[web.1]: [2022-10-12 15:20:31 +0000] [4] [INFO] Reason: Worker failed to boot. 2022-10-12T15:20:31.457411+00:00 heroku[web.1]: Process exited with status 3 2022-10-12T15:20:31.847763+00:00 heroku[web.1]: State changed from up to crashed 2022-10-12T15:20:35.000000+00:00 app[api]: Build succeeded 2022-10-12T15:22:25.882709+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=dataimprovement.herokuapp.com request_id=bcbbfbfa-aae2-416d-bfbe-1c972b39dd77 fwd="180.252.117.170" dyno= connect= service= status=503 bytes= protocol=https (venv) D:\project upload\dataimprovement>heroku logs --dyno router 2022-10-12T15:06:42.844541+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=dataimprovement.herokuapp.com request_id=e6128a90-7896-4662-b9fd-812b0304a02e fwd="180.252.117.170" dyno= connect= service= status=503 bytes= protocol=https 2022-10-12T15:06:43.900566+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=dataimprovement.herokuapp.com request_id=4475ddaf-1fd0-4bb2-a744-b26e35ec130f fwd="180.252.117.170" dyno= connect= service= status=503 bytes= protocol=https 2022-10-12T15:22:25.882709+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=dataimprovement.herokuapp.com request_id=bcbbfbfa-aae2-416d-bfbe-1c972b39dd77 fwd="180.252.117.170" dyno= connect= service= status=503 bytes= protocol=https This is my structure project: [enter image description here][1] 1. Then This is my app #layanan : [enter image description here][2] 2. Then this is my app #Items : [enter image description here][3] Can you guys tell me what wrong with my code when I deploy to heroku hosting ?, Because I was looking this error more than 2 days and I don't know how to … -
Python Integration the Payment System of Bank
I am trying to integrate the Bank's payment system on my Django-based website. As it said in documentation, I need to send parameters to their server (and then the new window should appear and the client should fill his card credentials there). Documentation (part 1): Documentation (part 2): Documentation (part 3): I am new in integration such services (payment) and need some help or broad explanation what to do, why do to that, and how. Additionally, I was pretty sure that the following code wouldn't work fine but why. import requests def send_request(): url = 'https://ecomm.pashabank.az:18443/ecomm2/MerchantHandler/?command=v&amount=5&currency=932&client_ip_addr=167.184.1.132&msg_type=SMS' response = requests.post(url) print(response) def main(): send_request() if __name__ == '__main__': main() causes raise SSLError(e, request=request) requests.exceptions.SSLError: HTTPSConnectionPool(host='ecomm.pashabank.az', port=18443): Max retries exceeded with url: /ecomm2/MerchantHandler/?command=v&amount=5&currency=932&client_ip_addr=167.172.184.123&msg_type=SMS (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1123)'))) Overall, I need help of everything happening behind the scenes. Huge thanks in advance guys! Note: I have also received some certifications from bank (I assume to assure the connection safety). But how I use it and when? -
How to get integer ID of Django Factory Boy object?
I have a factory boy factory that uses Django that I need to access the ID of the generated objects. However, whenever I attempt to get that ID, I receive TypeErrors. Any idea what I am missing? # factories.py class PartNoFactory(factory.django.DjangoModelFactory): class Meta: model = PartNo id = factory.fuzzy.FuzzyInteger(1, 1000000, step=1) # have also tried id = factory.Sequence(lambda n: n + 1) # have also tried id = int(factory.Sequence(lambda n: n + 1)), which results in error "type Sequence cannot be assigned to paramater "_x" # test_factories.py def mock_child_part_nos(arg_1: PartNo) -> 'list[int]': mock_part_no_one = PartNoFactory() mock_part_no_two = PartNoFactory() mock_part_no_three = PartNoFactory() return [mock_part_no_one.id, mock_part_no_two.id, mock_part_no_three.id] # if using FuzzyInteger: "Expression of type "list[FuzzyInteger]" cannot be assigned to return type "list[int]" # if using Sequence: "Expression of type "list[Sequence]" cannot be assigned to return type "list[int]" -
ModuleNotFoundError: No module named 'aspose-words'
I have installed aspose.words using the following command pip install aspose-words But when I add this to my installed app it showing the following error INSTALLED_APPS = [ # Core Extensions 'aspose-words' ] ModuleNotFoundError: No module named 'aspose-words' -
poker five card draw with Django Rest Framework
I Have this code Written with Python. The logic of the Code is to shuffle a deck of Cards, deal one single hand to the player and after Evaluate the Highest rank of the Player's hand and return an appropriate message to the player like. (Ex: Your Hand : 5K 8H 2S 3D 9S Your Rank : Flush) I want to use Django framework to create an API that will return an HttpResponse to mimic this (Ex: Your Hand : 5K 8H 2S 3D 9S Your Rank : Flush) as a Json Object. I would like to know how would about writing API and which design consideration i should have in mind. Which part of the code should go into the view to return the appropriate endpoint exemple : the hand of the player the shuffling of the deck, and the rank of the user. from constants import Constant class Card(Constant): def __init__(self, suit, val): # initialize the card object self.suit = suit self.value = val # get the rank of the card by indexing the RANKS dictionary self.rank = self.RANKS[val] def get_rank(self): # return the rank of the card if self.rank: return self.rank else: raise Exception('No rank') def get_suit(self): … -
SQL request for a model
models.py class Country(models.Model): name = models.CharField(max_length=50, validators=[validate_name, ]) class Meta: managed = False db_table = 'countries' def __str__(self): return self.name 0001_initial.py class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Country', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50, validators=[countries.validators.validate_name])), ], options={ 'db_table': 'countries', 'managed': False, }, ), ] sql (venv) michael@michael:~/Documents/PyCharmProjects/db/db$ python manage.py sqlmigrate countries 0001_initial BEGIN; -- -- Create model Country -- -- (no-op) COMMIT; Could you tell me whether this sql reflects the model or not? If not, how can it happen? And will it produce in the database? -
Django: Create a temporary custom user
I am currently working on a project with Django. I would like to allow a user to register only with his username. Additionally this user should be able to participate in chats with other users. After research I think that I need to create a SQL table for this. Should I rather create a custom user, which I then extend? Or should I create an independent model. Additionally, I am wondering how to design the authentication process. Should I store the PK and/or the password of the model in the user's session? In addition, I want to delete the user after some time. What is the best way to do this? Do I store the session key in the model and search the session database once a day for expired users? Also, if there is theoretically a way to solve the problem without making a database entry, I would be open to it. -
Hardcoded things in migrations
Could you tell me why Django hardcodes the business logic into migrations? We can formulate the question the other way. Let's have a look at valitadors and upload_to. These all is hardcoded into migrations. But if we show SQL that a migration produces, no validators or upload_to will be there. So, why are they hardcoded? Validators and upload_to are already mentioned in models. DRY principle is violated. Any change in the code ruins migrations. For example renaming of upload_to will result in the project's blowing up. Validators and upload_to are just examples. There are more things of the kind. Anyway, they don't influence the database. So, why do we need them in migrations? Could you comment? -
Django Crispy Form filter by is_staff
I have a form to upload article posts but how would I filter the author so it just shows users who have the is_staff role, I also need it to show authors as usernames rather than email adresses Here is my forms.py class ArticleForm(forms.ModelForm): tags = TagField(required=False, widget=LabelWidget) class Meta: model = Article fields = ('article_name', 'author', 'content', 'tags', 'status') Here is my views.py class ArticleCreateView(LoginRequiredMixin, CreateView): model = Article form_class = ArticleForm template_name = 'main_website/new_article.html' # <app>/<model>_<viewtype>.html def form_valid(self, form): form.instance.author = self.request.user form.save() return super().form_valid(form) def get_context_data(self, **kwargs): articles = Article.objects.filter(status=1).order_by('-date_posted')[:2] context = super().get_context_data(**kwargs) context['articles'] = articles context['title'] = 'New Article' return context Here is my models.py class Article(models.Model): class Status(models.IntegerChoices): Draft = 0 Published = 1 article_name = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='news_updates') updated_on = models.DateTimeField(auto_now=True) content = models.TextField() tags = TaggableManager() date_posted = models.DateTimeField(default=timezone.now) status = models.IntegerField(choices=Status.choices, default=Status.Draft, help_text=_('Decide whether you want to Publish the news article or save it as a Draft')) class Meta: ordering = ['-date_posted'] def __str__(self): return self.article_name def get_absolute_url(self): return reverse("main_website_article_detail", args=[str(self.slug)]) def save(self, *args, **kwargs): self.slug = slugify(self.article_name) super(Article, self).save(*args, **kwargs) -
Dockerized Django app and MySQL with docker-compose using .env
I would to run my Django project into a Docker container with its Database on another Docker container inside a Bebian When i run my docker container, I have some errors. Like : Lost connection to MySQL server during query ([Errno 104] Connection reset by peer). This command mysql > SET GLOBAL log_bin_trust_function_creators = 1 is very important because database's Django user create trigger. Morever, I use a .env file used same for create DB image to store DB user and password. This path is settings/.env. My code: docker-compose.yml: version: '3.3' services: db: image: mysql:8.0.29 container_name: db_mysql_container environment: MYSQL_DATABASE: $DB_NAME MYSQL_USER: $DB_USER MYSQL_PASSWORD: $DB_PASSWORD MYSQL_ROOT_PASSWORD: $DB_ROOT_PASSWORD command: ["--log_bin_trust_function_creators=1"] ports: - '3306:3306' expose: - '3306' api: build: . container_name: django_container command: bash -c "pip install -q -r requirements.txt && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/app ports: - '8000:8000' depends_on: - db Dockerfile : # syntax=docker/dockerfile:1 FROM python:3.9.14-buster ENV PYTHONUNBUFFERED=1 RUN mkdir /app WORKDIR /app COPY requirements.txt /app/ RUN pip install -r requirements.txt ADD . /app/ How to start my Django project ? Is possible to start only the DB container ? What command i need execute and what changes i need to make, I'm novice with … -
Can we select which object to return from serializer[many=true] based on condition
Lets suppose i have a model Post with field such as Model Post - Name : TextField - Body : TextField - isPrivate : Boolean Now the query post_obj = Post.objects.all() return 10 objects which is passed to getPostDataSerializer() class getPostDataSerializer(serializers.ModelSerializer): class Meta: model = Galaxy fields = ("Name","Body") we have post_data = getPostDataSerializer(post_obj,many=True).data which returns name and body of all 10 objects but i want to receive data of only those posts whose isPrivate field is false Please help -
Staticfiles Folder not Being Created Elastic Beanstalk
I'm trying to deploy a django application to Elastic Beanstalk but am having some difficulty serving static files. I've added the following to my .ebextensions container_commands: --- 04_collect_static: command: "cd /var/app/current && source ../venv/staging-LQM1lest/bin/activate && python manage.py collectstatic --noinput" leader_only: true --- option_settings: aws:elasticbeanstalk:environment:proxy:staticfiles: "/static/": "myapp/static/" In the EB instance's logs, I can see 0 static files copied to '/var/app/current/myapp/static', 163 unmodified. which implies that the files have successfully been copied. However, when I ssh into my instance and navigate to that directory, no "static" folder exists and the files are not being successfully served to the client (404 error).