Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django looks for media files in wrong directory with DEBUG = False and Nginx
My 2 Django apps are running with Nginx and Gunicorn on mysite.com and mysite.com/app2. App1's media files are working just fine. And for the app2 with DEBUG=False I get 404 when trying to download a media file, though the url it makes for the file is correct (it matches the directory on the server). From nginx error log I found that it is probably looking for it in the media directory of app1. How can I make app2 look for media in the correct directory? Nginx log error: *2020/06/09 13:24:51 [error] 9378#9378: 1 open() "/home/user/app1/media/attach_1/attach.pdf" failed (2: No such file or directory), client: 134.94.7.210, server: mysite.com, request: "GET /media/attach_1/attach.pdf HTTP/1.1", host: "mysite.com", referrer: "mysite.com/app2/" Nginx conf: server { listen 80; server_name server_domain; location = /favicon.ico { access_log off; log_not_found off; } location = /static/ { root /home/user/app1; } location = /app2/static/ { root /home/user/app2; } location = /media/ { root /home/user/app1; } location = /app2/media/ { root /home/user/app2; } location / { include proxy_params; proxy_pass http://unix:/run/app1.sock; } location /secondapp/ { include proxy_params; proxy_pass http://unix:/run/app2.sock:/; } } app2.settings: STATIC_URL = '/static/' PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = 'media/' … -
Serving Django-NGINX content from private subnet to AWS application Load Balancer
We have hosted Django application on NGINX in EC2 private subnet, we are not able to access it via AWS application load balancer end point. Below is the configuration file from location /etc/nginx/sites-enabled/myserver.conf We are getting 504 Gateway timeout using port 80 in configuration file and 502 bad Gateway using 443 in configuration file. upstream my_server { #server 0.0.0.0:80; server unix:/home/ubuntu/Desktop/star/star.sock fail_timeout=0; } server { listen 443; # default_server server_name 0.0.0.0; client_max_body_size 4G; access_log /home/ubuntu/Desktop/star/logs/nginx-access.log; error_log /home/ubuntu/Desktop/star/logs/nginx-error.log; location /static/ { root /home/ubuntu/Desktop/star/dashboard/static/; } location / { proxy_hide_header X-Frame-Options; include proxy_params; proxy_pass http://unix:/home/ubuntu/Desktop/star/star.sock; } # Error pages error_page 500 502 503 504 /500.html; location = /500.html { root /home/ubuntu/Desktop/star/dashboard/static/; } location ^~ /(css|js) { root /home/ubuntu/Desktop/star/dashboard/static/; } } server { if ($host = 0.0.0.0) { return 301 https://$host$request_uri; } if ($host = 0.0.0.0) { return 301 https://$host$request_uri; } listen 443; server_name 0.0.0.0; return 404; } -
how fix NoReverseMatch at x?
I am getting the error NoReverseMatch at /post/(post number) when I am trying to enter post_detail.html the error is Reverse for 'post_remove' not found. 'post_remove' is not a valid view function or pattern name. I guess I should change url of post_remove in urls.py but I don't know how It is views.py from django.shortcuts import render, get_object_or_404, redirect from django.utils import timezone from django.views import generic from django.views.generic.edit import DeleteView from .models import Post from .forms import PostForm # Create your views here. def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/post_list.html', {'posts': posts}) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': post}) def post_new(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm() return render(request, 'blog/post_edit.html', {'form': form}) def post_edit(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = PostForm(request.POST, instance=post) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm(instance=post) return render(request, 'blog/post_edit.html', {'form': form}) def post_draft_list(request): posts = Post.objects.filter(published_date__isnull=True).order_by('created_date') return render(request, 'blog/post_draft_list.html', {'posts': posts}) def post_publish(request, pk): post = get_object_or_404(Post, pk=pk) post.publish() return redirect('post_detail', pk=pk) def post_remove(request, pk): post = get_object_or_404(Post, pk=pk) post.delete() … -
How to put optional parameters in url using django
I need to put only optional paramaters using django, here my code : urlpatterns = [ url(r'^getdoclist/(?P<creationdate>[^/]+)/(?P<modificationdate>[^/]+)$',Get_DocumentList.as_view()) "creadtiondate" and "modificationdate" are my parameters -
How can I set min_length to django charfield?
I want to create a social media and for example person's username must be longer than 5charecters and shorter than 30 char's -
Django on IIS into production
Does anyboby have (present- actual) documentation about how to configure DJango o IIS. I have tried some tutorials on youtube but they are old and some things have changed. THanks you very much -
Django signals - how do I send what was saved in the model using post_save?
Triying to use signals to send through websockets the last record that was saved using .save(). What do I put in data? #models.py from django.db import models from django.db.models.signals import post_save from channels.layers import get_channel_layer from asgiref.sync import async_to_sync class DataModel(models.Model): time = models.DateTimeField() value = models.FloatField() def __str__(self): return str(self.time) def save_post(sender, instance, **kwargs): channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( "echo_group", {"type": "on.message", "data": data}, ) post_save.connect(save_post, sender=DataModel) -
Many to Many with extra field in Django ModelForms
I'm on Django 2.2 and here are my simplified models: class Course(CustomModelClass): name = models.CharField(max_length=200, null=False, unique=True) components = models.ManyToManyField('Component', through='CourseComponent') class Component(CustomModelClass): name = models.CharField(max_length=200, null=False, unique=True) class CourseComponent(CustomModelClass): course = models.ForeignKey(Course, on_delete=models.CASCADE) component = models.ForeignKey(Component, on_delete=models.CASCADE) quantity = models.IntegerField(default=0, null=False) My relationships work well no problem on that. Now arrive the moment I do a ModelForm to manage that. Here is my form for now: class CourseForm(ModelForm): class Meta: fields = ['name', 'group', 'components'] model = Course And same it works quite well if my quantity has a null=True parameter but of course when I put it at False, it obviously doesn't work anymore. What I wanted to do is to have in my form a way to select components and set a quantity. I don't really care how it looks like it can be a chackbox with the name of the component and a numberfield or many select list to select the component and a number field, it's not the important part. My problem right now is that of course I have no access to the quantities in the form. Any idea? -
How to update database on successful payment in django through paytm
https://dev.to/iiits-iota/paytm-payment-gateway-integration-in-django-1657 I referred this to setup my payment gateway -
Verify OAuth 2.0 token
I have a token from Microsoft OAuth 2.0 with PKCE that in is sent to my Django server from a front-end. How can I verify the integrity of this token? I want to allow users to sign in with their Microsoft accounts. -
How to limit ForeignKey users in custom groups in django
How to limit number of ForeignKey users in custom groups in django ? for example to 3? class Group(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) choice = models.ForeignKey(Choice, on_delete=models.CASCADE) -
Comparison in Django template using request.GET and choices is not properly evaluated
I have this in my models: class Task(Record): class Status(models.IntegerChoices): OPEN = 1, "Open" COMPLETED = 2, "Completed" status = models.IntegerField(choices=Status.choices, db_index=True, default=1) Then in my template I want to show all the statuses, so I do this in views.py: context = { "statuses": Task.Status.choices, } And in my template I loop through it: {% for label,name in statuses %} {{ label }}: {{ name }} {% endfor %} This leads to: 1: Open 2: Completed So far, so good. But now if I use a GET parameter, I can't get things to work as I want. Say I open ?id=2 and then I run: {% for label,name in statuses %} {{ label }}: {{ name }} {% if label == request.GET.id %} YES {% else %} Sorry, not equal to {{ request.GET.id }} {% endif %} {% endfor %} Then I expect this to show YES for the first item. But it doesn't! Somehow this evaluates to: 1: Open Sorry, not equal to 1 2: Completed Sorry, not equal to 1 I do not understand why the first item does not evaluate to true. -
Slow query using Django and PostgreSQL with > 40 million rows
I'm working with a model (table) with more than 40 million rows and queries are very slow (> 2 min), using PostgreSQL. The models: class ModelA(...): source = models.ForeignKey(ModelB, related_name='source', ...) target = models.ForeignKey(ModelB, related_name='target', ...) class ModelB(...): c = models.ForeignKey(ModelC, ...) ... The Django filter: ModelA.objects.filter(source__isnull=True, target__c=my_c) The query: SELECT "model_a"."id", ... FROM "model_a" INNER JOIN "model_b" T3 ON ("model_a"."target_id" = T3."id") WHERE ("model_a"."removed" = False AND "model_a"."source_id" IS NULL AND T3."c_id" = 389) How can I optimize it? I am having optimization problems and I would like to know different solutions, etc. -
Channels - how do I send data through websocket when signal is received?
I want to stream data from a database through websocket. Basically a new record is being inserted into DataModel at every second and I want to send this new record through websocket as soon as it's inserted. Someone recommended me to use signal when the model's save() method is called. So to my models.py I just added this: def save_post(sender, instance, **kwargs): print('signal') post_save.connect(save_post, sender=DataModel) What to I put inside of save_post and also on my consumers.py so that the data goes through? -
how can i define User Groups and permissions on django to control a news model?
i have News model. i want to manage news by users who belongs from these Groups? class News(models.Model): title = models.CharField(max_length=255, help_text="Short title of news") content = models.TextField(blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) status = models.BooleanField(default=True) how can i define these user permissions? Users Groups Permissions Reporters # create a news CopyEditors # read and update Poducers # read, update, aprove and revoke Rundown # list of aproved articles Anchors # read only aproved articles -
Why can't I filter on one new field in Django Rest Framework?
So I'm editing an existing codebase using Django Rest Framework, and I added a new field to a model: class MyModel(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=150, null=True) the_new_field = models.IntegerField(null=True, default=None) I've got a serializer, which is fairly basic: class MyModelSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = MyModel fields = ( 'id', 'name', ) So to the serializer I simply added the new field: class MyModelSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = MyModel fields = ( 'id', 'name', 'the_new_field', ) I can call the endpoint using name using ?name=awesomename, which actually filters based on awesomename, but when I call the endpoint using ?the_new_field=123456 it simply returns all the records in the database. What am I missing here? How can I make it filter based on this new field? -
Django / Wagtail: trying to add new children content to present on template
CandlePage and CandleIndexPage. the CandlePage is defined to describe the candle details the CandleIndexPage should present a list of Candles (CandlePage objects). i need to add to the CandleIndexPage template a 'label' property for each CandlePage object. i tough that it can be done with overriding the get_context method, but i was not able to do it on the 'children's level'. happy to get any advice. -
I got a KeyError when i try to use request.META['CSRF_COOKIE']
I want to use the mako template in django2, but when I set up the render function of mako and tried to set the template to bring the csrf token, I found that I could not get the CSRF__COOKIE in request.META #coding:utf-8 from mako.lookup import TemplateLookup from django.template import RequestContext from django.conf import settings from django.template.context import Context from django.http import HttpResponse def render_to_response(request, template, data=None): context_instance = RequestContext(request) path = settings.TEMPLATES[0]['DIRS'][0] lookup = TemplateLookup( directories=[path], output_encoding='utf-8', input_encoding='utf-8' ) mako_template = lookup.get_template(template) if not data: data = {} if context_instance: context_instance.update(data) else: context_instance = Context(data) result = {} for d in context_instance: result.update(d) result['csrf_token'] = '<input type="hidden" name="csrfmiddlewaretoken" value="{0}" />'.format(request.META['CSRF_COOKIE']) return HttpResponse(mako_template.render(**result)) django reports error: KeyError "CSRF_COOKIE", what shoud i do? -
Product image loads on all products page, but not on individual product page (Django)
For a little bit of context, when you add a new product to my website, you are required to add an image as well. I can get the product images to load just fine when viewing the main products page, but when you try to view an individual product on a new product details page, the image won't load. The product image is pulled in via the following code: <div class="product" style="background-image: url('{{ MEDIA_URL }}{{ product.image }}')"></div> Here is the HTML used on the main products page: <div class="album"> <div class="container"> <div class="product-row"> {% for product in products %} <div class="col-xl-4 col-md-6"> <div class="card mb-4 shadow-sm"> <div class="product" style="background-image: url('{{ MEDIA_URL }}{{ product.image }}')"></div> <div class="product-card-body"> <p class="product-title">{{ product.name }}</p> <p class="text-muted">{{ product.category }}</p> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <form method="post" action="{% url 'add_to_cart' product.id %}"> {% csrf_token %} <div class="text-center"> <span class="input-group-btn"> <button class="product-btns btn-success" type="submit">Add to Cart</button> </span> </div> </form> <form class="ml-2" method="post" action="{% url 'product_details' product.id %}"> {% csrf_token %} <div class="text-center"> <span class="input-group-btn"> <button class="product-btns btn-info" type="submit">Find out more</button> </span> </div> </form> </div> <p class="product-price">£{{ product.price }}</p> </div> </div> </div> </div> {% endfor %} </div> </div> </div> Here is the HTML used on the product … -
Uploaded image is not showing in django Admin using class based views?
I am using Class Based Views for uploading images but none of the images are getting uploaded i.e. the images are not shown in Django Admin Site. This is simple blog project where in only superuser can upload blogs/posts. Here are my major files of the project: models.py class Post(models.Model): author=models.ForeignKey('auth.User',on_delete=models.CASCADE) title=models.CharField(max_length=256) text=models.TextField() create_date=models.DateTimeField(default=timezone.now()) published_date=models.DateTimeField(blank=True,null=True) blog_pic=models.ImageField(upload_to='blog_pics/',blank=True)#the field for uploading image forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ('author','title', 'text','blog_pic') views.py class CreatePostView(LoginRequiredMixin,CreateView): login_url='/login/' redirect_field_name='basic_app/post_detail.html' form_class=PostForm model=Post settings.py MEDIA_DIR=os.path.join(BASE_DIR,'media') STATIC_URL = '/static/' STATIC_ROOT=os.path.join(BASE_DIR,'static') MEDIA_ROOT=MEDIA_DIR MEDIA_URL='/media/' I also made the changes in the urls.py which is mentioned in docs but that didn't solved my problem. urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Please help me rectify the error due to which the image is not being uploaded. -
Null Value error inspite of passing value in Serializer
I have a model in my app like this: class Bid(models.Model): supplier = models.ForeignKey(User, on_delete=models.CASCADE) order = models.ForeignKey(Orders, on_delete=models.CASCADE) comments = models.CharField(max_length=255, blank=True, null=True) bid_amount = models.CharField(max_length=255, default=0) date = models.DateTimeField(auto_now_add=True) is_confirmed = models.BooleanField(default=False) I am trying to save data in this model but keep getting the error: django.db.utils.IntegrityError: null value in column "order_id" violates not-null constraint DETAIL: Failing row contains (28, null, 800, 2020-06-09 12:43:14.697672+00, f, null, 5). Views.py class BidCreateAPIView(APIView): permission_classes = (permissions.IsAuthenticated,) def post (self, request, pk, format=None): supplier = request.user.pk d = request.data.copy() print("pk", pk) d['order'] = pk d['supplier'] = supplier print("d is", d) serializer = BidSerializer(data=d) if serializer.is_valid(): serializer.save() print("Serializer data", serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializer.py class BidSerializer(serializers.ModelSerializer): order = OrderSerializer(many=True, read_only=True, required=False) class Meta: model = Bid fields = "__all__" I have set required=False in order serializer then why does it throws the error ? -
Cannot edit data from a table in django
I keep on getting this error and I don't know why. Can anyone help me with it? NoReverseMatch at /item Reverse for 'edit_supplier' with arguments '('lll111',)' not found. 1 pattern(s) tried: ['supplier/edit_item/(?P\d+)/$'] models.py class item_status(models.Model): item_code=models.CharField(max_length=30,unique=True,primary_key=True,blank=False) item_name=models.CharField(max_length=50,blank=True) type= models.CharField(max_length=100,blank=True) price=models.IntegerField() choices =({'AVAILABLE','Item ready to be purchased'},{'SOLD','Item Sold'},{'RESTOCKING','Item restocking in few days'}) status=models.CharField(max_length=50,choices=choices,default="AVAILABLE") #Available,Sold, Restocking item_quantity_available=models.IntegerField() issues=models.CharField(max_length=100,default="No issues") views.py def edit_item(request, pk, model, cls): item = get_object_or_404(model, pk=pk) if request.method == "POST": form = cls(request.POST, instance=item) if form.is_valid(): form.save() return redirect('index') else: form = cls(instance=item) return render(request, 'inv/edit_item.html', {'form': form}) def edit_item_status(request, pk): return edit_item(request, pk, item_status, item_statusForm) forms.py class item_statusForm(forms.ModelForm): class Meta: model = item_status fields = ('item_code', 'item_name', 'type', 'price','status','item_quantity_available','issues',) urls.py url(r'^item/edit_item/(?P<pk>\d+)$', edit_item_status, name="edit_item_status"), index.html {% for item in items1%} <tr> <td>{{ item.item_code }}</td> <td>{{ item.item_name }}</td> <td>{{ item.type }}</td> <td>{{ item.price}}</td> <td>{{ item.status}}</td> <td>{{ item.item_quantity_available}}</td> <td>{{ item.issues}}</td> <td> <a href="{% url 'edit_supplier' item.item_code %}" class="btn btn-warning btn-sm" role="button" aria-pressed="true" > Edit</a> <a href="{% url 'delete_supplier' item.item_code %}" class="btn btn-danger btn-sm" role="button" aria-pressed="true" > x</a> </td> </tr> {% endfor %} This code however works fine for my other classes that use integer primary key. I don't know why and I am totally lost now. -
django-tables2 accessing computed data
I am creating set(t)s as accumulation of parts and I want to display their total price according similar to this post: models.py: class PartBase(models.Model): name = models.CharField('Name', max_length=120) price = models.DecimalField("Price", decimal_places=2, max_digits=8) class Sett(models.Model): name = models.CharField('Name', max_length=120) class PartRelation(models.Model): part = models.ForeignKey(PartBase, on_delete=models.CASCADE) qty = models.PositiveIntegerField("Quantity") sett = models.ForeignKey(Sett, related_name='setts', on_delete=models.SET_NULL, null=True) def get_position_price(self): return self.qty * self.part.price tables.py: class SetTable(django_tables2.Table): total_price = django_tables2.Column(accessor="total_price", verbose_name="total") class Meta: model = Sett sequence = ("name", "total_price") exclude = ("id",) views.py: class SetListView(SingleTableView): model = Sett context_object_name = "setts" table_class = SetTable def get_context_data(self, **kwargs): context = super(SetListView, self).get_context_data(**kwargs) for s in context["setts"]: pr = PartRelation.objects.filter(sett=s) s.total_price = 0 for p in pr: s.total_price += p.get_position_price() return context def total_price(self): pos = PartRelation.objects.filter(sett_id=self.kwargs["pk"]) total_price = 0 for p in pos: total_price += p.get_position_price() return total_price I tried accessing the data via get_context and also via a custom method total_price, but neither worked. Where did I take the wrong turn? -
Pip package install in both globally and in virtualenv
I have a problem with installing my pip packages. I have created a virtualenv and when I try to install packages through pip, it gets install both globally and inside my virtualenv. Does anyone have any solution why this is happening? I want to solution to be for windows. -
How to do unitetesting for unmanaged apps in django.? [closed]
I have an application where I am using 3 tables from legacy db and one resides within the application db. I have tried the solution https://dev.to/vergeev/testing-against-unmanaged-models-in-django ,https://blog.birdhouse.org/2015/03/25/django-unit-tests-against-unmanaged-databases/ ,https://dev.to/vergeev/testing-against-unmanaged-models-in-django. But nothing seems to work. I run my scripts as follows: python manage.py test --settings=myapp.test_settings myapp.tests.Testclass Can anyone help.