Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django deployment, reopen a killed port in aws ubuntu server
For first time I am trying to deploy a django project to AWS - EC2 instance. It was almost showing the results, but to active HTTPS and deploy points, I added following lines to settings.py and then the browser couldn't open the project and remained in spin mode: DEBUG = FALSE ALLOWED_HOSTS = ['3.18.211.33'] # #HTTPS settings SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_SSL_REDIRECT = True #HSTS settings SECURE_HSTS_SECONDS = 31536000 # 1 year SECURE_HSTS_PRELOAD = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True even after that when I removed these lines, it remained like before in the way it's reading some cache. I tried to kill the port 8000, however after that it even does not tries to load(This site can’t be reached) my ip address which is like: https:///3.18.211.33:8000 I tried to add https to security group of EC2 like below: I am trying to active port 8000, at least to step back a bit. Any help would be greatly appreciated. -
django+gunicorn+nginx gives 404 while serving static files
django+gunicorn+nginx gives 404 while serving static files I am trying to deploy a Django project using nginx + gunicorn + postgresql. All the configuration is done, my admin panel project static file will serve , but other static files; it returns a 404 error.(iam use run python manage.py collectstatic) my error.log nginx :: "/blogpy/static/home/test.css" failed (2: No such file or directory)" Structure: blog -blog -config -nginx -nginx.conf -docker-compose.yml -Dockerfile -home -static -home -test.css(not working) - requirements -static -templates -.env -docker-compose.yml -Dockerfile setting.py: DEBUG = False ALLOWED_HOSTS = ['*'] STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'static' nginx configuration: ---- nginx.conf: user nginx; worker_processes 1; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; access_log /var/log/nginx/access.log; upstream blogpy{ server blogpy:8000; } server { listen 80; server_name localhost; charset utf-8; location / { proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; proxy_pass http://blogpy; } location /static/ { alias /blogpy/static/; } } } -
Docker: How to make Supervisor exit when there's an error
I have a Docker container running Supervisor with 2 processes: Celery Django I want Supervisor to exit when one of these processes returns an error. This is my configuration: [supervisord] nodaemon=true loglevel=debug logfile=/app/supervisord.log pidfile=/var/run/supervisord.pid childlogdir=/app [program:django] command=python manage.py runserver 0.0.0.0:8000 redirect_stderr=true stdout_logfile=/dev/fd/1 stdout_logfile_maxbytes=0 [program:celery] command=celery -A myapp worker --beat --scheduler django --loglevel=debug redirect_stderr=true stdout_logfile=/dev/fd/1 stdout_logfile_maxbytes=0 [eventlistener:processes] command=bash -c "printf 'SUPERVISORD READY' && while read line; do kill -SIGQUIT $PPID; done < /dev/stdin" events=PROCESS_STATE_STOPPED,PROCESS_STATE_EXITED,PROCESS_STATE_FATAL When I have a fatal error that should normally make Docker exit, Supervisor tries to launch Django again and again.. while the goal is to exit. What's missing here? I tried different other configurations but it's not working. -
How I can get the number of the user that follow me in Django
How I can get the number of the users that follow me, not whose I follow them This get the users that I follow them account = Account.objects.get(pk=user_id) view_account = account my_account = Account.objects.get(username=request.user) if view_account in my_account.following.all(): follow = True else: follow = False followers = view_account.following.all() number_of_followers = len(followers) How I can get the opposite, The numbers of users whose follow me The Account model class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField( verbose_name="date joined", auto_now_add=True ) following = models.ManyToManyField( settings.AUTH_USER_MODEL, blank=True, related_name="follow" ) -
How do I serve a generated file in Django via nginx as download?
I'm trying to serve a generated zip file in my media folder via nginx, but I got the following error: open() "/etc/nginx/htmltest.zip" failed (2: No such file or directory) Somehow nginx is looking for the file in a weirdly malformed "/etc/nginx/html", I don't get why. I'm using nginx via docker-compose, the code works just fine if I don't use nginx and just run Django in development mode. folder_path = os.path.join(settings.MEDIA_ROOT, str(uuid.uuid4())) os.mkdir(folder_path) shutil.make_archive(os.path.join(folder_path, "test"), 'zip', folder_path, "test") response = download(os.path.join(folder_path, f"{zip_name}.zip")) def download(path): if os.path.exists(path): with open(path, 'rb') as f: response = HttpResponse(f.read(), content_type="application/zip") response['Content-Disposition'] = 'inline;filename=' + os.path.basename(path) response['X-Accel-Redirect'] = os.path.basename(path) return response raise Http404 My nginx.conf: upstream django_app { server web:8000; } server { listen 80; location / { proxy_pass http://django_app; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; client_max_body_size 100M; } location /static/ { alias /code/static/; } location /media/ { alias /code/media/; } } MEDIA_ROOT in settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') -
how to add a messaging app in django rest framework
I am trying to add a messaging capability to my Django rest framework project but I can't find any tutorials for how to do it I have seen things like Django channels and asynchronous chatrooms in Django but I haven't seen any for Django rest framework. If anyone knows how to implement a chat functionality in Django rest framework, please let me know -
Django-Filter Package: Is There Any Way To Change To AND Filter Instead Of OR
The Django-Filter package works well as it allows for to form widgets to be used but it only seems to do OR filters which doesn't make sense for what i am doing. I don't see anything in the docs for this either and i would think this is a common problem as AND filters make more sense for filtering. is there any way to overide the way that it filters? I have tried to do this by passing a list of inputs to filter by but i am having errors so using Django-Filters would be much easier if it would do AND filtering. -
Django admin inline formset overwritten by importing bootstrap
I am using inline formset in django admin in this way: # admin.py class ChildInline(admin.TabularInline): model = Child form = ChildInlineForm class ParentAdmin(admin.ModelAdmin): inlines = [ChildInline] form = ParentAdminForm having this result which is correct: I imported bootstrap in admin area by overwriting base_site.html page in this way: {% extends "admin/base_site.html" %} {% block title %}Django with Bootstrap{% endblock %} {% block branding %}{% endblock %} {% block breadcrumbs %}{% endblock %} {% block bodyclass %}bg-light{% endblock %} {% block extrastyle %} {{ block.super }} {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.min.css' %}" /> {% endblock %} {% block bodyheader %} <div class="bg-white container"> <div class="row"> <h1 class="display-4">Django with Bootstrap</h1> </div> {% endblock %} {% block bodyfooter %} <div>Copyright</div> </div> <script src="{% static 'js/jquery-3.3.1.min.js' %}"></script> <script src="{% static 'js/bootstrap.min.js' %}"></script> {% endblock %} which generates this result on formset: probably because bootstrap overrides form-row class also contained in tr <tr class="form-row row1 dynamic-product_set" id="product_set-1"> --- <tr> How can I solve this issue? -
Is there any way to block user to access the urls not specified in urls.py in Django
I am trying to block the user access to the urls not specified in urls.py of django. We have media and static file in django project. If opened, the media and static files can be opened easily with the url. Like if an image named avatar.jpg is in http://127.0.0.1:8000/media/anime/images/ Here a user can access this file typing the url http://127.0.0.1:8000/media/anime/images/avatar.jpg Is there any way I can restrict all users to access the urls which are not specified in urls.py? In urls.py path('', views.index, name="AnimeHome"), path('about/', views.about, name="About"), path('watch/<int:animeId>', views.product, name="Watch"), path('search/', views.search, name="Search"), path('help/', views.help, name="Help"), path('feedback/', views.feedback, name="Feedback"), path('episode/<int:animeId>/<int:episodeNumber>',views.episode, name="Episode") -
Django - __str__ returned non-string (type tuple)
I am trying to open the template sem.html and year.html from my project, but it is showing an error unnecessarily. Earlier it will open the template smoothly but when I m trying with the foreign key it is giving an error that str returned a non-string value. I am joining my models.py file code where I created two models named sem and year and in forms.py I have created two forms semforms and yearforms with two fields. class semester(models.Model): sem_num = models.CharField(max_length=10,null=True) sem_courses = models.ManyToManyField(subjects,related_name='sem_courses') @property def get_courses(self): return self.sem_courses def __str__(self): return self.sem_num class Year(models.Model): year_name = models.CharField(max_length=50) courses = models.ManyToManyField(subjects,related_name='courses') @property def get_courses(self): return self.courses def __str__(self): return self.year_name forms.py class semforms(forms.ModelForm): class Meta: model = semester fields = ['sem_num','sem_courses'] class yearforms(forms.ModelForm): class Meta: model = Year fields = ['year_name','courses'] It is giving this error TypeError at /sem/ __str__ returned non-string (type tuple) Request Method: GET Request URL: http://127.0.0.1:8000/sem/ Django Version: 3.1.4 Exception Type: TypeError Exception Value: __str__ returned non-string (type tuple) Anyone can solve this, please help. -
Django & Pyrebase: How do I know if my email is verified or not in firebase
I am building a web app using Django as the framework and firebase as the database. I am using the pyrebase API. The API allows sending the verification email but I didn't find any way to find out if the user has verified their email or not. Please help! -
How to go to Homepage by clearing path in Django
I am trying to go to the homepage from A contact us page. subscribe Views.py:(subscribe is basically contact) from django.shortcuts import render # Create your views here. from bsdk.settings import EMAIL_HOST_USER from . import forms from django.core.mail import send_mail from django.shortcuts import render,redirect from django.contrib import messages from django.contrib.auth.models import User,auth # Create your views here. #DataFlair #Send Email def subscribe(request): sub = forms.Subscribe() if request.method == 'POST': sub = forms.Subscribe(request.POST) name=str(sub['name'].value()) subject = str(sub['name'].value()) message = str(sub['phone'].value())+ "\n" + str(sub['message'].value()) recepient = str(sub['Email'].value()) send_mail(subject, message, EMAIL_HOST_USER, [recepient], fail_silently = False) return render(request, 'contact.html', {'form':sub}) subscribe urls.py: from django.urls import path from . import views from django.urls import path,include from django.conf.urls import url from django.contrib import admin from ecom import views as ecom_views urlpatterns = [ path('subscribe', views.subscribe, name = 'subscribe'), ] How to redirect to homepage when home is pressed on site? even though i tried a couple of times i ended up going to homepage but with extra path http://127.0.0.1:8000/subscribe/home when actually i wanted to go to http://127.0.0.1:8000/ -
How to display the lines from a Formset in one html template?
I am trying to display the lines created from the formset in a table. What is the correct way to write the loop as {% for billline in line.formset.all %} doesn`t seem to work. views.py @login_required(login_url="/login/") class BillDetailView(DetailView): model = Bill template_name = 'accounting/bills/create_bill.html' models.py class Bill(models.Model): vendor = models.CharField(max_length=250, null=True, blank=True) bill_title = models.CharField(max_length=250, null=True, blank=True) reference = models.CharField(max_length=250, null=True, blank=True) class BillLine(models.Model): bill = models.ForeignKey(Bill,related_name="has_lines",on_delete=models.CASCADE, blank=True, null=True, unique=False) bill_item = models.CharField(max_length=100, verbose_name="Line") description = models.TextField(blank=True, null=True) forms.py class BillForm(forms.ModelForm): class Meta: model = Bill fields = ['bill_title','vendor','reference'] def __init__(self, *args, **kwargs): super(BillForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = True self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-md-3 create-label' self.helper.field_class = 'col-md-9' self.helper.layout = Layout( Div( Field('bill_title'), Field('vendor'), Fieldset('Add lines', Formset('lines')), Field('reference'), HTML("<br>"), ButtonHolder(Submit('submit', 'save')), ) ) class BillLineForm(forms.ModelForm): class Meta: model = BillLine exclude = () BillLineFormSet = inlineformset_factory( Bill, BillLine, form=BillLineForm, fields=['bill_item', 'description'], extra=1, can_delete=True ) custom_layout_object.py from crispy_forms.layout import LayoutObject, TEMPLATE_PACK from django.shortcuts import render from django.template.loader import render_to_string class Formset(LayoutObject): template = "accounting/bills/formset.html" def __init__(self, formset_name_in_context, template=None): self.formset_name_in_context = formset_name_in_context self.fields = [] if template: self.template = template def render(self, form, form_style, context, template_pack=TEMPLATE_PACK): formset = context[self.formset_name_in_context] return render_to_string(self.template, {'formset': formset}) urls.py path('bill/detail/', views.BillDetailView.as_view, name='bill_detail'), bill_detail.html … -
Django equivalent for pattern matching
What is the equivalent for this query in django title like 'Book %' Imagine I have those records in db: Book 1, Book 2, Book 3 and Books. currently I'm using djangos filter method for a queryset this way queryset.filter(title__startswith='Book') # which is title like 'Book%' and this returns all the above records from the db. I need only Book 1, Book 2 and Book 3 results, how could this be achieved django way? -
django serializer dropping field
I'm currently building a django app and I'm serializing my views, but when applying the serializer to the model is dropping the fields I wanna serialize: models.py class vehicles_model(models.Model): pk_idmodel = models.AutoField(db_column='PK_IdModel', primary_key=True) # Field name made lowercase. name = models.CharField(max_length=20, default=None) fk_idbrand= models.ForeignKey(vehicles_brand, on_delete= models.CASCADE, db_column='FK_IdVehicleBrand', related_name='Brand') class Meta: db_table = 'vehicles_model' verbose_name_plural = "Vehicle Models" serializers.py class brandSerializer(serializers.ModelSerializer): class Meta: model = vehicles_brand fields = ['name'] depth = 3 class modelSerializer(serializers.ModelSerializer): Brand = brandSerializer(many=True, read_only=True) class Meta: model = vehicles_model fields = ['name', 'Brand'] depth = 3 output: { "name": "Aveo" }, { "name": "Spark" }, Which is the model name, but the brand is dropped, I've been unable to fix it after checking other solutiones, thanks in advance for any hint or help. -
In django template how to retain Dropdown selected option after submit?
There is a dropdown to select country and then show results in the same page after submitting it. Here is the code for the dropdown: <form type="get" action="."> {% csrf_token %} <label class="m-12">Contry</label> <select name = "drop1" > <option value="England">England</option> <option value="USA">USA</option> <option value="Sweden">Sweden</option> <option value="Italy">Italy</option> </select> <input class="btn btn-side-bar" type = "submit" value="Submit"> </form> After pressing the button, it does query and return the result to the same page. The page is reloaded so the dropdown does not show the selected item but the default option. The url shows the selected option in it. http://127.0.0.1:8000/lookup/?searchfield=USA The dropdown should show the selected value but it does not. How this problem can be fixed? An idea is to get the value from the url. Or is there any better way to do it? -
Django and Celery "Connection Refuse" error when using RabbitMQ in Centos
I'm using Django and Celery with RabbitMQ as the message broker. While developing in Windows I installed RabbitMQ and configured Celery inside Django like this: celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'main.settings') app = Celery('DjangoExample') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() init.py from .celery import app as celery_app __all__ = ['celery_app'] When running Celery inside my development Windows machine everything works correctly and tasks are being executed as expected. Now I'm trying to deploy the app inside a Cento7 machine. I installed RabbitMQ and when running Celery with the following command: celery -A main worker -l INFO But I get a "connection refused" error: [2021-02-24 17:39:58,221: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. I don't have any special configuration for Celery inside my settings.py since it was working fine in Windows without it. Does anyone know why this is happening? How can I get Celery to work correctly with RabbitMQ inside of Centos7? Here is a screenshot of the celery error: And here is the status of my RabbitMQ Server that shows that it's currently installed and running. Many thanks in advance! -
Django migrate is trying to run migrations already in the django_migrations table
I am having a problem where django migrate is trying to apply migrations that have already been run and are already recorded in my django_migration table. Trying to upgrade a site from Django 1.9.7 to 3.0.12 output from manage.py migrate: Applying content.0005_auto_20170427_1222...System check identified some issues: but if I query my django_migrations table I already have that migration applied: +-----+---------+-------------------------+----------------------------+ | id | app | name | applied | +-----+---------+-------------------------+----------------------------+ | 462 | content | 0005_auto_20170427_1222 | 2017-04-27 12:22:40.987195 | +-----+---------+-------------------------+----------------------------+ -
django API Serializer : cannot update foreign key field : response is 400 Bad Request The request cannot be fulfilled due to bad syntax
i am new to django API framework and i am getting "response is 400 Bad Request The request cannot be fulfilled due to bad syntax." kindly suggest. please refer the code sample, **Models.py** class Color(models.Model): name = models.CharField(max_length=20) class Product(models.Model): name = models.CharField(max_length=20) price = models.DecimalField(max_digits=5, decimal_places=2) color = models.ForeignKey(Color, on_delete=models.CASCADE) class Customer(models.Model): # customer related field name = models.CharField(max_length=20) product = models.ForeignKey(Product, on_delete=models.CASCADE) **Serializer.py** class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('name', 'product','color' ) class CustomerSerializer(serializers.ModelSerializer): product = ProductSerializer(many=False) class Meta: model = User fields = ('name', 'product' ) **Views.py** class CustomerViewSet(viewsets.ModelViewSet): serializer_class = CustomerSerializer queryset = Customer.objects.all() Request data(POST Json) { "name": "test", "product": "1" } enter code here response is 400 Bad Request The request cannot be fulfilled due to bad syntax. -
Django queryset in view isn't returning anything to the html template
I want to show all posts of a specific user in their profile page but only their profile information is being displayed but not the posts. My initial code was simply trying to loop through the posts in the template like this: {% for post in user.posts.all %} {% endfor %} But it didn't work. So I tried this next. views.py user = get_object_or_404(User, username=username) post = Post.objects.filter(created_by=user.id) context = { 'user': user, 'post': post } return render(request, 'users/profile.html', context) profile.html <div class="user-profile"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> {{ user.username }} {{ user.email }} </div> <div class="user-post-model"> {% for post in posts %} <img class="rounded-circle post-img" src="{{ post.created_by.profile.image.url }}"> {{ post.title }} {{ post.content|safe }} {{post.tag}} {{ post.created_by }} {{ post.created_at|naturaltime}} {% endfor %} </div> It didn't work either I also tried using a ListView to post the posts. It worked but instead of showing the specific user's profile information it showed the logged in user's profile information but the specific user's posts. like this: def profile(request, username): user = get_object_or_404(User, username=username) context = { 'user': user } return render(request, 'users/profile.html', context) class UserPostListView(ListView): model = Post template_name = 'users/profile.html' context_object_name = 'posts' def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) … -
How can I make url in Django with foreignkey title?
In the urls I've wanted to make a url kinda like this <category_slug>/<article_slug>. The Artile models ForeignKey is Category, which has line slug. How to make url like that? -
How to get only one instance of a model in views
I am Building a BlogApp and I am stuck on a Problem. What i am trying to do I am trying to access all the data of only one Model instance in Function Based View. In Brief I am trying to show all the posts liked by a all the users in a particular page. What have i tried 1). post = Paintings.objects.filter(likes=pk) This didn't work because it only show the logged in user's posts. AND i want to get all the posts that are liked. 2). post = Paintings.objects.all() This also didn't work for me. models.py class Post(models.Model): post_owner = models.ForeignKey(User,default='',null=True,on_delete=models.CASCADE) likes = models.ManyToManyField(User, related_name='post_like', blank=True) views.py def featured_paintings(request,pk): post = Post.objects.filter(likes=pk) context = {'post':post} return render(request, 'mains/featured_posts.html', context) I don't know what to do. Any help would be appreciated. Thank You in Advance -
Django/Google Kubernetes Intermittent 111: Connection refused to upstream services
I've done quite a bit of searching and cannot seem to find anyone that shows a resolution to this problem. I'm getting intermittent 111 Connection refused errors on my kubernetes clusters. It seems that about 90% of my requests succeed and the other 10% fail. If you "refresh" the page, a previously failed request will then succeed. I have 2 different Kubernetes clusters with the same exact setup both showing the errors. Setup Kubernetes Cluster Version: 1.18.12-gke.1206 Django Version: 3.1.4 Helm to manage kubernetes charts Cluster Setup Kubernetes nginx ingress controller that serves web traffic into the cluster: https://kubernetes.github.io/ingress-nginx/deploy/#gce-gke From there I have 2 Ingresses defined that route traffic based on the referrer url. Stage Ingress Prod Ingress Ingress apiVersion: extensions/v1beta1 kind: Ingress metadata: name: potr-tms-ingress-{{ .Values.environment }} namespace: {{ .Values.environment }} labels: app: potr-tms-{{ .Values.environment }} annotations: kubernetes.io/ingress.class: "nginx" nginx.ingress.kubernetes.io/ssl-redirect: "true" nginx.ingress.kubernetes.io/from-to-www-redirect: "true" # this line below doesn't seem to have an effect # nginx.ingress.kubernetes.io/service-upstream: "true" nginx.ingress.kubernetes.io/proxy-body-size: "100M" cert-manager.io/cluster-issuer: "letsencrypt-{{ .Values.environment }}" spec: rules: - host: {{ .Values.ingress_host }} http: paths: - path: / backend: serviceName: potr-tms-service-{{ .Values.environment }} servicePort: 8000 tls: - hosts: - {{ .Values.ingress_host }} - www.{{ .Values.ingress_host }} secretName: potr-tms-{{ .Values.environment }}-tls These ingresses route … -
no such column: todoApp_todolist.category_id
from django.db import models Create your models here. from django.utils import timezone class Category((models.Model)): name=models.CharField(max_length=100) class Meta: verbose_name=("Category") verbose_name_plural=("Categories") def __str__(self): return self.name class TodoList(models.Model): title=models.CharField(max_length=250) content=models.TextField(blank=True) created=models.DateField(default=timezone.now().strftime("%y-%m-%d")) # due_date=models.DateField(default=timezone.now().strftime("%y-%m-%d")) category=models.ForeignKey(Category,on_delete=models.CASCADE) class Meta: ordering=["-created"] def __str__(self): return self.title -
Django delete function overrides pgtrigger
I have created several models using Django, for one of the models I would like to have a trigger that does not allow deletes. See the model code below. @pgtrigger.register( pgtrigger.Protect(name='protect_deletes',operation=pgtrigger.Delete) ) class NoDelete(models.Model): salary = models.PositiveIntegerField() id = models.PositiveIntegerField(primary_key=True) name = models.CharField(max_length=50) The application also has an website that allows you to interact with the database, when deleting a model of this type a function in views.py is called. def delete(request, id): temp = NoDelete.objects.get(pk=id) temp.delete() So it seems like the trigger does not function as I want it to since this delete removes the row from the database. When trying to delete the tuple directly from the database however the trigger is fired. Any ideas on how to get around this issue?