Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Template extends base.html but doesn't get the content of the sidebar
I have base_planner.html that contains a navbar and a sidebar. When I extend this base in any other template, both the navbar and sidebar are inherited, but the sidebar doesn't have any content that must be there. And I'm not getting any errors. The only template that has the sidebar content is the home page, which is merely a ListView html page (projectsmodel_list.html) containing one row: {% extends 'app_planner\base_planner.html' %} Here is my views.py (I want TestView to inherit the sidebar content): class ProjectListView(LoginRequiredMixin, generic.edit.FormMixin, generic.ListView): context_object_name = 'project_list' model = ProjectsModel form_class = ProjectsForm success_url = reverse_lazy('app_planner:planner_home') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['create_project_form'] = ProjectsForm() return context def form_valid(self, form): project_name = form.cleaned_data['project_name'] project_author = self.request.user create_project_form_item = ProjectsModel(project_name=project_name, project_author=project_author) create_project_form_item.save() return super().form_valid(form) def form_invalid(self, form): return super().form_invalid(form) def post(self, request, *args, **kwargs): self.object_list = self.get_queryset() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) class TestView(generic.TemplateView): template_name = 'app_planner/test.html' Here is my urls.py: app_name = 'app_planner' urlpatterns = [ path('', views.ProjectListView.as_view(), name='planner_home'), path('test/', views.TestView.as_view(), name='test'), ] Here is the body of my base_planner.html: {% if user.is_authenticated %} <nav id='navbar' class="navbar navbar-expand-lg bg-white"> <div class="container-fluid"> <a id='logo' class="navbar-brand" href="{% url 'app_planner:planner_home' %}"><h3><b><span style="color:#FC5E5E;">Savvy</span> Planner</b></h3></a> <button class="navbar-toggler" type="button" … -
Insert multiple list in database using python django
Im confused on how can I insert multiple list bycolumn using a loop, let say the output what I want in database is something like this name percentage is_fixed_amount PWD 20 0 Senior 20 0 OPD 6 0 Corporators 20 0 Special 1 What I've tried but it's insert multiple data and it didn't reflect the actual data in database, Can somebody knows the solution? I appreciate any reply. discount = ['PWD','Senior Citizen','OPD','Corporators','Special'] discount_percentage = ['20','20','6','20',''] fixed_amount = [False,False,False,False,True] for dis in discount: for per in discount_percentage: for fix in fixed_amount: discount_val = Discounts(name=dis,percentage = per,is_fixed_amount =fix) discount_val.save() -
Dealing with circular dependencies on API endpoints
I am writing a new Django app with Django Ninja, to build an API. There is an app of "users" that contains an Organization model and a User model (that belongs to an organization). There is another app of "posts" that, for now, only has a Post model, that belongs to a user and an organization. So the "posts" API router is mounted on "/api/v1/organizations/{organization_id}/posts", and I can perform a complete CRUD over this. The problem comes when I want to retrieve the posts of an user. Suppose someone enters to a profile page, and then you want to get all data: user data, organization, posts count, all posts, etc. The more intuitive response would be like: "/api/v1/organizations/{organization_id}/users/xxxx" that returns all of this. But this means that the "users" app should know about "posts". And it introduces a circular dependency. What do you think? Have you been through the same problem? The above answer says it! -
Why I am not saving a wav file but .336Z file in the database after sending audio blob to server Django?
I am currently making a recording application with Recorder.js with Django. After pressing the 'Upload' button, it will send the audio blob to the server side, that is Django, and save in the database. I am trying to save an audio file with wav format into database in Django but it saves a .336Z file in the database. Why I can't save in wav file? function createDownloadLink(blob) { var url = URL.createObjectURL(blob); var au = document.createElement('audio'); var li = document.createElement('li'); var link = document.createElement('a'); //name of .wav file to use during upload and download (without extendion) var filename = new Date().toISOString(); //add controls to the <audio> element au.controls = true; au.src = url; //save to disk link link.href = url; link.download = filename+".wav"; //download forces the browser to donwload the file using the filename link.innerHTML = "Save to disk"; //add the new audio element to li li.appendChild(au); //add the filename to the li li.appendChild(document.createTextNode(filename+".wav ")) //add the save to disk link to li li.appendChild(link); //upload link var upload = document.createElement('a'); upload.href="#"; upload.innerHTML = "Upload"; upload.addEventListener("click", function(event){ var xhr=new XMLHttpRequest(); xhr.onload=function(e) { if(this.readyState === 4) { console.log("Server returned: ",e.target.responseText); } }; var fd=new FormData(); fd.append("audio_data",blob, filename.wav); xhr.open("POST","/save-audio/",true); xhr.send(fd); }) li.appendChild(document.createTextNode (" … -
Is there a way to skip over table when it hasn't been filled with value
I'm still learning Django python and trying to create webapp that display students scores each semester. And I got this error that says Grades2 matching query does not exist.. Because I create separate class for each semester, and for this student I intentionally left second semester's score empty because in they haven't reach that semester yet. with this models: from django.db import models # Create your models here. class Students(models.Model): clas = models.CharField(max_length=6, default='no data') nim = models.IntegerField(primary_key=True) name = models.CharField(max_length=50) year = models.IntegerField() def __str__(self): return f"{self.nim} in class {self.clas}" class Grades1(models.Model): nim = models.ForeignKey(Students, on_delete=models.CASCADE) biology = models.IntegerField(default=0) math = models.IntegerField(default=0) history = models.IntegerField(default=0) def __str__(self): return f"{self.nim.name} with scores \n biology = {self.biology} \n math = {self.math} \n history = {self.history}" class Grades2(models.Model): nim = models.ForeignKey(Students, on_delete=models.CASCADE) biology = models.IntegerField(default=0) math = models.IntegerField(default=0) history = models.IntegerField(default=0) def __str__(self): return f"{self.nim.name} with scores \n biology = {self.biology} \n math = {self.math} \n history = {self.history}" class Achievement(models.Model): nim = models.ForeignKey(Students, on_delete=models.CASCADE) ach = models.CharField(max_length=50) scales = [ ('INT', 'INTERNATIONAL'), ('NA', 'NATIONAL'), ('RE', 'REGIONAL'), ('LO', 'LOCAL'), ('DE', 'DEED') ] scale = models.CharField( max_length=3, choices=scales, default='DE' ) def __str__(self): if self.ach is not None: return f"{self.nim.name} has achieve {self.ach}" else … -
Error: This field is required. React Form Post To Django Rest Framework API with React RTK Query
I have tried many ways to POST data to my backend which is Django Rest Framework. I kept receiving the error that "This field is required." although my console shows that all the fields are populated. Snippets of my code are below: import React, { useEffect, useState } from "react"; import { useNavigate } from "react-router-dom"; import { money } from "../data"; import { CustomButton, FormField, Loader } from "../components"; import { useCreateCampaignMutation } from "../utils/userAuthApi"; import { getToken } from "../utils/index"; const CreateCampaign = () => { const navigate = useNavigate(); const { access_token } = getToken(); const [createCampaign, { isLoading }] = useCreateCampaignMutation(); const [form, setForm] = useState({ title: "", description: "", target: "", deadline: "", }); const handleFormFieldChange = (fieldName, e) => { setForm({ ...form, [fieldName]: e.target.value }); console.log(form); }; const handleSubmit = async (e) => { e.preventDefault(); console.log({ form, access_token }); const res = await createCampaign({ form, access_token }); if (res.data) { console.log(res.data); } else { console.log(res.error.data.errors); } }; return ( <div className="bg-[#1c1c24] flex justify-center items-center flex-col rounded-[10px] sm:p-10 p-4"> {isLoading && <Loader />} <div className="flex justify-center items-center p-[16px] sm:min-w-[380px] bg-[#3a3a43] rounded-[10px]"> <h1 className="font-epilogue font-bold sm:text-[25px] text-[18px] leading-[38px] text-white"> Start a Campaign </h1> </div> <form onSubmit={handleSubmit} … -
Problems with {% extends 'base.html' %} command in Django
I have been bothering so long with this problem. I don't where I have made a mistake. Been sitting over this for 1h.... Someone, please help. It's home.html file: {% extends 'base.html' %} {% block head %} Home {% endblock %} {% block body %} <h1>HomeHome</h1> {% endblock %} And it's base.html : <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-aFq/bzH65dt+w6FI2ooMVUpc+21e0SRygnTpmBvdBgSdnuTN7QbdgL+OapgHtvPp" crossorigin="anonymous"> {% block head %} Base {% endblock %} {% block body %} <h1>BaseBase</h1> {% endblock %} </body> My page shows base.html with no changes - it doesn't use {% extends 'base.html' %} thank you :) -
Gmail removing hyperlinks from email. Why?
My application is expected to send email verification link to user. When I open such an email in Gmail, the links are not shown, Gmail removes them. If I select [Show original] option, I can see that the links are there. Why is it so? How can I fix this ? Note: I'm on development server. Displayed Email: Hi from Team! You just subscribed to our newsletter. Please click the link below in order to confirm: Thank You! Team Original Email: Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Hi from Team! You just subscribed to our newsletter. Please click the link below in order to confirm: http://127.0.0.1:8000/newsletter/verify_email/MTQ/bmq8o8-15cab7bf32186aab16c2c086e9beaec3/ Thank You! Team Thanks! -
Why django form is submitted but the valued is null in the database?
We have a model called Column, and we want user to be able to create Table model based on Column model fields he created, we successfully do that using the method below: def create_table(request): columns = Column.objects.filter(user=request.user) fields = {} for column in columns: if column.field_type.data_type == 'number': fields[column.name] = forms.IntegerField() elif column.field_type.data_type == 'character': fields[column.name] = forms.CharField(max_length=20) elif column.field_type.data_type == 'decimal': fields[column.name] = forms.DecimalField(max_digits=20, decimal_places=10) elif column.field_type.data_type == 'image': fields[column.name] = forms.ImageField() elif column.field_type.data_type == 'boolean': fields[column.name] = forms.BooleanField() elif column.field_type.data_type == 'date': fields[column.name] = forms.DateField() TableForm = type('TableForm', (forms.Form,), fields) if request.method == 'POST': form = TableForm(request.POST, request.FILES) if form.is_valid(): table = Table() table.user = user=request.user for column in columns: setattr(table, column.name, form.cleaned_data[column.name]) table.save() return redirect('Table') else: form = TableForm() return render (request, 'create_table.html', {'form':form}) As you can see our view, our users can create Table model based on a Column model fields they created, but when the form is submitted, the value created from TableForm is null in the database, instead of showing us the object of the Table model created by a user, it is shown nothing, how can we solve this problem? the models: class Column(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) list_of_album = models.ForeignKey(Album, on_delete=models.CASCADE) name … -
My cpanel doesn’t have the “setup python app”
I want to deploy my Django application using cpanel, but my problem is that my cpanel does not have the setup python application option in its software section, please help me, this is my first project, I don't want to fail in this project. -
Django cannot query data from another table by using OneToOneField
I create django model like this which api_key of Setting table is OneToOneField to Key table. class Key(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 Setting(models.Model): api_key=models.OneToOneField(DeviceKey,on_delete=models.CASCADE) field_en=models.BooleanField(default=False) def __str__(self): return str(self.api_key) I add data to table Key like this. api_key="abc1" api_key_name="test" In views.py I use key to query like this code. def keyForm(request): key="abc1" data, created = Setting.objects.get_or_create(api_key__api_key=key) key = Key.objects.get(api_key=key) data = {'setting':data, 'key':key} return render(request,'key_form.html', data) Data in table Key It show error like this. How to fix it? MySQLdb._exceptions.OperationalError: (1048, "Column 'api_key_id' cannot be null") IntegrityError at /keyForm (1048, "Column 'api_key_id' cannot be null") -
Missing 1 positional argument request
from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend class EmailBackend(ModelBackend): def authenticate(self ,request, username=None, password=None, **kwargs): UserModel = get_user_model() try: user = UserModel.objects.get(email=username) except UserModel.DoesNotExist: return None else: if user.check_password(password): return user 1. ALLOWED_HOSTS = [] Application definition INSTALLED_APPS = [ 'FirstApp.apps.HomeConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Main', ] MIDDLEWARE = [ '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', ] ROOT_URLCONF = 'Main.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / "templates"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Main.wsgi.application' Database https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } Password validation https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] Internationalization https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True Static files (CSS, JavaScript, Images) https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' #added manually STATICFILES_DIRS = [ BASE_DIR / "static", ] AUTHENTICATE_BACKEND = ['django.contrib.auth.backends.ModelBackend', 'FirstApp.authentication.EmailBackend'] Default primary key field type https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' -
DRF ManyToMany Field getting an error when creating object
I have a Rant model with Category linked to it using ManyToManyField. I've serialized it but the problem is this error: { "categories": [ "Expected a list of items but got type \"str\"." ] } These are my serializers: class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = "__all__" class RantSerializer(serializers.ModelSerializer): categories = serializers.PrimaryKeyRelatedField(queryset=Category.objects.all(), many=True) class Meta: model = Rant fields = ('rant', 'slug', 'categories') My post method is this: def post(self, request, format=None): serializer = RantSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) What did I do wrong here? -
Django error Server Error (500) when upload new .html file to project
I use FTP to upload new html file to Django server. I upload every file to server unless settings.py. The settings.py set DEBUG = False. It have no problem with DEBUG = True in my PC and it also have no problem with another html template in server. It show error 500 only new template. "POST /showData HTTP/1.1" 500 145 I change chmod 755 to every file in project. I migrate model and use python manage.py collectstatic I add whitenoise MIDDLEWARE = [ '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', 'whitenoise.middleware.WhiteNoiseMiddleware', #add whitenoise ] it show error 500. How to fix it? -
pycharm cookiecutter docker django project Django support not working
I have a project that I have created with cookieecutter django (docker). I'm setting up Interpreter via docker-compose via Pycharm. Interpreter works fine. Django support is not working even though I have Django Support enabled. However, when I use Interpreter in another project in this project, django support works.But I can't use it because it's a different Interpreter for different project. even the .filter() function from one of my models does not come as a suggestion enter image description here enter image description here When I use the docker compose Interpreter of another project for this project in pycharm, django support works. But I couldn't understand, I created the project with cookiecutter, I didn't change anything. Why django support is not working. -
docker react+django, Access to XMLHttpRequest at 'http://localhost:8000' from origin 'http://localhost' has been blocked by CORS policy
I have a docker running with a service on the backend with Django and DRF, and another at the frontend with react I'm trying to make an API call from my react to my Django server const getRealItems = () => { axios.get(`http://localhost:8000/item`).then( (response) => { console.log("realItems = ", response) } ) } this endpoint works normally on a browser or through insomnia and returns a 200 with the data, I have also tried to replace the endpoint on my method to the pokemon API and received a 200 with the data, so the method is fine the issue is hitting the endpoint on my server This is my settings.py ... # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ ... 'rest_framework', 'restaurant', 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOWED_ORIGINS = [ "http://localhost", "http://localhost:80", ] CORS_ORIGIN_ALLOW_ALL = True ... and I added this on my viewset.py class MenuItemViewSet(ModelViewSet): queryset = MenuItem.objects.all() serializer_class = MenuItemSerializer #GET def list(self, request, *args, **kwargs): return super().list(request, *args, **kwargs) def finalize_response(self, request, response, *args, **kwargs): response["Access-Control-Allow-Origin"] = "*" return super().finalize_response(request, response, *args, **kwargs) … -
I have an aplication build with django for the backend, and for the front end i used tailwind css and flowbite ui, the problem is deploying on heroku
I have an aplication build with django for the backend, and for the front end i used tailwind css and flowbite ui (installed with npm), the problem is deploying on heroku, i can't get the css working on host, on production it uses ca cache css (i will provide a picture),i dont know why, i installed the django compressor (flowbite ui requierment).enter image description here I have tried almost everything, and i want a guide or video resolv this problem -
How to reference a varaible inside a template syntax in Django?
I have code as below: {% for entry in qs %} {% for field_name in field_names %} <span>{{entry.field_name}}</span> {%endfor%} {%endfor%} But nothing will show up inside span tag. Then I change back to {{entry.name}} which "name" is a property of every entry. Then the correct value shows up. Why is that? Thanks... -
I want to improve my queryset performance, I am using Pagination to return paginated response in django but its taking so much time
here is my pagination code over a queryset. query_end_time = time.time() - start print(query_end_time, "query_end_time") total_rows = query_set.count() number_of_pages = 0 paginator = Paginator(query_set, number_of_rows) number_of_pages = paginator.num_pages page_number = request.GET.get("page_number") order_item = list(paginator.get_page(page_number)) pagination_end_time = time.time() - start print(pagination_end_time, "pagination_end_time") query time and pagination time tried django pagination document but not landed to any conclusion -
Django not stop send line notify
I use django send line notify like this code in views.py . def lineAlert(token, msg): url = 'https://notify-api.line.me/api/notify' token = token headers = { 'content-type': 'application/x-www-form-urlencoded', 'Authorization':'Bearer '+token } while True: msg = msg r = requests.post(url, headers=headers , data = {'message':msg}) print(r.text) def Test(request): lineAlert('xxxxxxxxxxxxxxxxxxxxxxxx', "test") I want to send line notify 1 time only but it continue send message line notify like this. How to fix it? Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. {"status":200,"message":"ok"} {"status":200,"message":"ok"} {"status":200,"message":"ok"} {"status":200,"message":"ok"} {"status":200,"message":"ok"} {"status":200,"message":"ok"} {"status":200,"message":"ok"} {"status":200,"message":"ok"} {"status":200,"message":"ok"} {"status":200,"message":"ok"} {"status":200,"message":"ok"} {"status":200,"message":"ok"} {"status":200,"message":"ok"} {"status":200,"message":"ok"} {"status":200,"message":"ok"} {"status":200,"message":"ok"} {"status":200,"message":"ok"} -
django not receiving correct response? in front
overview When you press the 'like!' button, there is processing to feed back to the front screen via server processing (create or delete). No error when creating. Feedback is fine too. I get an error when deleting and the feedback doesn't work. The content of the error seems to be that json cannot be received correctly. The creation process and deletion process are almost the same, and the records are also registered and deleted in the database. So the processing is exactly the same. What's causing this? It seems so simple, but... detail # model class Articles(models.Model): title = models.CharField(max_length=200) note = models.TextField() user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) objects = ArticlesQuerySet.as_manager() @staticmethod def with_state(user_id: int) -> QuerySet: return Articles.objects.annotate( likes_cnt=Count('likes'), liked_by_me=Case( When(id__in=Likes.objects.filter(user_id=user_id).values('articles_id'), then=1), default=0, output_field=IntegerField() ) ) class Likes(models.Model): articles = models.ForeignKey('Articles', on_delete=models.CASCADE) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) class Meta: constraints = [ models.UniqueConstraint( fields=['articles_id', 'user_id'], name='articles_user_unique' ) ] # views.py class LikesCreateView(LoginRequiredMixin, CreateView): def post(self, request, *args, **kwargs): return_value = None try: Likes.objects.create(user_id=kwargs['user_id'], articles_id=kwargs['article_id']) article = Articles.with_state(kwargs['user_id']).get(pk=kwargs['article_id']) return_value = json.dumps({'likes_cnt': article.likes_cnt, 'liked_by_me': article.liked_by_me}) print(f'LikesCreateView return_value[{type(return_value)}]: ', return_value) except User.DoesNotExist: logging.critical('There was an access from an unauthorized user account') except Articles.DoesNotExist: logging.critical('An unauthorized article was accessed') … -
AmazonLinux2 Welcome Page shows over Nginx Installation
So, I'm setting up a backend api on Amazon Linux 2 and I have installed Nginx, set up a service systemd file that uses Gunicorn to run the django instance and create a sock file at /home/ec2-user/backend/testsite.sock. That file is getting created properly. Loading that file into the Nginx /etc/nginx/conf.d/testsite.com server block. The Issue: testsite.com Nginx file: server { server_name api.testsite.com; listen 80; location = /favicon.ico { access_log off; log_not_found off; } location / { include proxy_params; error_log logs/error.log warn; proxy_pass http://unix:/home/ec2-user/backend/testsite.sock; } } I've set up the security group to allow HTTP on port 80 and when I visit http://api.testsite.com, I'm seeing this page still: Thank you for using Amazon Linux 2. Now that you have it installed, find announcements and discussion in the AWS Discussion Forums. Also try AWS documentation. Nginx status output: (venv) [ec2-user@testsite conf.d]$ sudo systemctl status nginx.service ● nginx.service - The nginx HTTP and reverse proxy server Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled) Active: active (running) since Sun 2023-04-02 05:33:49 UTC; 39min ago Process: 3395 ExecStart=/usr/sbin/nginx (code=exited, status=0/SUCCESS) Process: 3391 ExecStartPre=/usr/sbin/nginx -t (code=exited, status=0/SUCCESS) Process: 3389 ExecStartPre=/usr/bin/rm -f /run/nginx.pid (code=exited, status=0/SUCCESS) Main PID: 3397 (nginx) CGroup: /system.slice/nginx.service ├─3397 nginx: master process /usr/sbin/nginx └─3398 nginx: … -
Django ORM & Django REST Framework: How to make "grouped" arrays?
Currently, my Django server can return the JSON below: [ { "id": 1, "customerId": 1, "description1": "...", "description2": "...", "description3": "...", "description4": "..." }, { "id": 2, "customerId": 1, "description1": "...", "description2": "...", "description3": "...", "description4": "..." }, { "id": 3, "customerId": 1, "description1": "...", "description2": "...", "description3": "...", "description4": "..." }, { "id": 4, "customerId": 2, "description1": "...", "description2": "...", "description3": "...", "description4": "..." }, { "id": 5, "customerId": 2, "description1": "...", "description2": "...", "description3": "...", "description4": "..." } ] I want to rewrite it and make some groups based on customerId(customer_id in Django), e.g. [ { "customerId": 1, "data": [ { "id": 1, "description1": "...", "description2": "...", "description3": "...", "description4": "..." }, { "id": 2, "description1": "...", "description2": "...", "description3": "...", "description4": "..." }, { "id": 3, "description1": "...", "description2": "...", "description3": "...", "description4": "..." } ] }, { "customerId": 2, "data": [ { "id": 4, "description1": "...", "description2": "...", "description3": "...", "description4": "..." }, { "id": 5, "description1": "...", "description2": "...", "description3": "...", "description4": "..." } ] } ] But I don't know how to make this using Django's views and serializers. How can I get such JSON? -
How to implement dynamic filtering in Django ListView based on user input?
I'm working on a Django project where I need to display a list of items and allow users to filter the items based on various criteria. I'm using Django's generic ListView for displaying the items, but I'm not sure how to implement the dynamic filtering based on the user's input. Here's my current setup: models class Item(models.Model): name = models.CharField(max_length=100) category = models.CharField(max_length=50, choices=CATEGORY_CHOICES) price = models.DecimalField(max_digits=6, decimal_places=2) available = models.BooleanField(default=True) views: class ItemListView(ListView): model = Item template_name = "items/item_list.html" item_list.html {% for item in object_list %} <div class="item"> <h2>{{ item.name }}</h2> <p>Category: {{ item.category }}</p> <p>Price: {{ item.price }}</p> </div> {% endfor %} I'd like to allow users to filter the items by category, price range, and availability. What's the best way to implement this functionality in a Django ListView? Any guidance or examples would be much appreciated! -
Custimizing Django Admin (multiple registraion to a model)
I have a Django app with a master model that has a lot on detailed models. the detaled models are related to the master with foreign keys in each. I registered my master model in django admin and included all my detail models as "TabularInline" layout. My models.py looks like: # models.py file # class MasterModel(models.Model): # master model fields ... class DetailModel_01(models.Model): # detail model fields class DetailModel_02(models.Model): # detail model fields class DetailModel_03(models.Model): # detail model fields class DetailModel_04(models.Model): # detail model fields My admin.py looks like: class Detail_01_Inline(admin.TabularInline): model = Detail_01 class Detail_02_Inline(admin.TabularInline): model = Detail_02 class Detail_03_Inline(admin.TabularInline): model = Detail_03 class Detail_04_Inline(admin.TabularInline): model = Detail_04 @admin.register(MasterModel) class MasterModelAdmin(admin.ModelAdmin): inlines = [ Detail_01_Inline, Detail_02_Inline, Detail_03_Inline, Detail_04_Inline, ] The master model has too many fields, and too many inlines. therefore, not convienient to the users. I need to splet the inlines. can i register the master model more than one time in Django admin, and include part of the inlines each time ?? your ideas are so appreciated. Suhail