Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-ratelimit stack keys. Not the intended behaviour
I think my understanding of django-ratelimit is incorrect. I am using v3.0.0 but v2.0 produces the same results. Lets say I have this code: @ratelimit(key='post:username', rate='5/h', block=True) @ratelimit(key='post:tenant', rate='5/h', block=True) @csrf_exempt def index(request): print(request.POST["username"]) print(request.POST["tenant"]) print("") return HttpResponse('hallo', content_type='text/plain', status=200) Let's say tenant A submits username "Antwon" 6 times, then tenant A will be blocked for 1 hour, which is good. But, lets say tenant B also has a user "Antwon", then that user for tenant B will not be able to log in. I would assume that Antwon for tenant B should still be able to log in, otherwise tenant A can DOS other tenants? Is this intended behavior or is my implementation incorrect? -
Django Template: Csrf token invalid for multiple post request in the same form
Im working on a Django project and got stuck in a problem that involve csrf token. I have a form that i handle the submit with javascript function, because in the same form i need to perform 2 POST. Form is something like that: <form> {% csrf_token %} <input name="field_1" type="text"> .... .... <input name="file" type="file"> <button onclick="send_form()"> Send data </button> </form> the send_form() method performs two post request with axios. The first send the textfields and the second the file. I need to do this because the server two different api for manage the text data and the file. The problem is that the first post succeeds and then the second fail, giving 403 error and in the header i can see the error "CSRF Failed: CSRF token missing or incorrect." There is a way to do this in a single form? I read that someone apply the csrf to the entire body of the page but i can't figure out how to do it. Thank you for any answers. -
Django Database QuerySet
I'm trying to work with Databases using Django's ORM. I'm looking to retrieve a value from a specific column in a database and then convert it from a QuerySet type to a Int or String so I can then work with this data. So my question is, how can I convert a QuerySet to a usable data type? -
setting a django object column-field to None & how to access an object field's name
I'm trying to set a django object field/column to null using a function in my views.py. This is the model. class Myteam(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) QB = models.CharField(max_length=80, null=True) RB1 = models.CharField(max_length=80, null=True) WR = models.CharField(max_length=80, null=True) TE = models.CharField(max_length=80, null=True) D = models.CharField(max_length=80, null=True) K = models.CharField(max_length=80, null=True) this is the views.py. It's not actually a "delete" function as I've learned you can't delete object fields, but you can set them to None. def delete_player(request, id, col_name): player = Myteam.objects.get(id=id) setattr(player, col_name, None) player.save() return redirect('show') I'm looping through the object's fields and displaying them as html table rows, but to get this views.py function working, I need to get the "col_name" from the respective column/field. I understand that django will set a default field name but I can't find how to access it. Various sources say to use "field.name" but I've tried testing this out with a print statement and django gives me an attribute error/no such attribute as 'name' for example. team = Myteam.objects.all() for t in team: print(t.WR, t.id, t.name) So, how can you access/pass a field's name? I got some interesting advice on this earlier from another user -
How To Validate If A Conversation Object With Particular Partcipants (Many to Many Field) Exis or nott in Django Rest Framework?
Models.py from django.contrib.auth.models import User class Conversation(models.Model): participants = models.ManyToManyField(User, related_name="conversation") Urls.py path('api/conversations/', views.ConversationListView.as_view(), name='conversation-list'), Serializers.py class ConversationSerializer(serializers.ModelSerializer): participants = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(), many=True) class Meta: model = Conversation fields = ['id', 'participants'] Views.py class ConversationListView(APIView): def get(self, request, format=None): conversations = Conversation.objects.all() serializer = ConversationSerializer( conversations, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = ConversationSerializer(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) So I would like to make a POST request on "api/conversations/" with this object: {"participants": [2,3]} or {"participants": [3,2]} BUT I would like to check first whether a conversation with participants are both User(id=2) and User(id=3) exist or not. If exists, I need to raise an error. If not exist, create a new conversation. So there is only one conversation between User(id=2) and User(id=3). What I know so far is I have to make validate_participants(self, value) in the serializer. But I still can't figure out what is the logic to check it. I've tried using Conversation.objects.filter(participants__in=[2,3]) but I think it doesn't work because it does not return the conversation object that has both User(id=2) and User(id=3) as participants. -
Django mandatory Decimal field
i have some problem with django, i have a field that i need to convert to mandatory: slice_thickness = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True, default="" , help_text="Nominal slice thickness, in mm") when i try to set null=False, blank=False gives me this error: File "/usr/local/lib/python3.6/site-packages/django/db/models/fields/init.py", line 1559, in to_python params={'value': value}, django.core.exceptions.ValidationError: ["'' value must be a decimal number."] I also tried: slice_thickness = models.DecimalField(max_digits=5, decimal_places=2, null=False, blank=False, default=Decimal('0.00') , help_text="Nominal slice thickness, in mm") def slice_thickness_decimal(self): return str(Decimal(self.slice_thickness)) but it generates the same error. Thanks -
Issues with URLs in Django 3 when trying to view products detail page
New to Django and im trying to simply get to my products detail page using the following code in my URLs.py: urls.py: from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from products import views import carts from carts.views import CartView from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('products/', views.all, name='products'), path('s/', views.search, name='search'), path('products/<slug:slug>', views.single, name='single_product'), <----This is the page I want to get to path('cart/', carts.views.CartView, name='cart'), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And here is my view: def single(request, slug): try: product = Product.objects.get(slug=slug) images = ProductImage.objects.filter(product=product) context = {'product': product, "images": images} template = 'products/single.html' return render(request, template, context) except: raise Http404 But when trying to access this page I get the following 404 Error: Maybe a fresh pair of eyes can help me spot the mistake I'm making? If any additional info is needed please let me know, I'll be happy to provide. Thanks a million in advance! -
Approaches for adding multiple image on a post Django
I am working on a platform where I need to allow users to upload multiple images in one post. I want to keep it as simple as possible, so that a person wouldn't have to refresh the page to upload each image, or create and save a post before adding images. If a user could delete or reorder images it would be nice Can you give me advice on how to do it properly? I am using django , postgres and here's what I have done so far . On my models.py - class ImagePost(models.Model): user = models.ForeignKey("profiles.HNUsers", on_delete=models.DO_NOTHING) image = OptimizedImageField("Post Image", blank=True, null=True) timestamp = models.DateTimeField("Timestamp", blank=True, null=True, auto_now_add=True) text = models.TextField("Description text", blank=True) class Meta: verbose_name_plural = "Image Posts" It can take one image just fine . what should I change to make it multi upload post On my views.py this is what I have done so far - @api_view(['POST']) @permission_classes((permissions.AllowAny,)) def image_post(request): if request.method == 'POST': data = request.data print(data) serializer = ImagePostSerializer(data=data) if serializer.is_valid(): serializer.save() print("image object saved") try: image_post_object = ImagePost.objects.filter(user__id=data['user']).order_by('-timestamp')[0] print(image_post_object) try: post = Posts() post.user = HNUsers.objects.get(id=data['user']) post.image_url = image_post_object.image.url post.type = 'I' post.category = data['category'] post.created_on = image_post_object.timestamp post.text = image_post_object.text … -
Django project on elastic beanstalk throws 502 gateway error
I have configured and deployed a Django project on AWS elasticbeanstalk. I get a 502 Gateway error. mysite/.ebextensions/django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: mysite/mysite/wsgi.py Error Log https://pastebin.com/YziHrC9N Can someone point me in the right direction, please! -
django: group by extracting month and year from a date
im trying to get a list of invoicepositions where there hasn't been payed an payout to a person. Looking in the internet i came to this "Solution" src_invoice_month_year = InvoicePosition.objects.values_list("designer_id", ExtractYear('created_at'),ExtractMonth('created_at'))\ .filter(payoutposition__isnull=True, designer_id=designer.id).distinct() but the query, that comes out is: SELECT DISTINCT `accounting_invoiceposition`.`designer_id`, EXTRACT(YEAR FROM `accounting_invoiceposition`.`created_at`) AS `extractyear1`, EXTRACT(MONTH FROM `accounting_invoiceposition`.`created_at`) AS `extractmonth2`, `accounting_invoiceposition`.`created_at`, `accounting_invoiceposition`.`id` FROM `accounting_invoiceposition` LEFT OUTER JOIN `partners_payoutposition` ON (`accounting_invoiceposition`.`id` = `partners_payoutposition`.`invoiceposition_id`) WHERE (`accounting_invoiceposition`.`designer_id` = 3 AND `partners_payoutposition`.`id` IS NULL) ORDER BY `accounting_invoiceposition`.`created_at` DESC, `accounting_invoiceposition`.`id` DESC so he added "created_at" and the id from the invoiceposition model although i don't want that! (i'm running the query with designer_id 3) -
No Category matches the given query
I develop a small e-commerce site and when I add the product to the cart I always have this error: -
Footer in Django
How can I keep my footer at bottom in Django template In jinja format I have added content in blocks The following code: <div class="ui container"> {% block content %} {% endblock content %} </div> {% block scripts %} {% endblock scripts %} <script type="text/javascript" src={% static 'main.js' %}></script> <br> <br> {% include 'main/footer.html' %} </body> </html> I have created a different footer page whenever the content gets over footer appears therefore thefooter lies on top sometimes if small content is present. -
Page not found at /polls
I am a total beginner in "django" so I'm following some tutorials currently I' am watching https://youtu.be/JT80XhYJdBw Clever Programmer's tutorial which he follows django tutorial Everything was cool until making a polls url Code of views.py: from django.shortcuts import render from django.http import HttpResponse def index(request): HttpResponse("Hello World.You're at the polls index") Code of polls\urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] Code of Mypr\urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/',admin.site.urls), path('polls/',include('polls.urls')), ] I don't get it I did the same thing but I'm getting error not only polls.In one turtorial he decided to make blog,and again the same error Please my seniors help me. Note:I'm using the latest versions of django,windows and as editor I'm using Pycharm. -
How to reuse a for variable in django
I'm trying to display me df in a table to my webap (without using .tohtml because i need a dynamic table). It seems that I can't use the key/column variable from my loop : <table id='bdd_table'> <thead> <tr> {% for header in BDD_Data %} <th> {{header}} </th> {% endfor %} </tr> </thead> <tbody> {% for key in BDD_Data_size %} <tr> {% for column in BDD_Data %} <td> {{BDD_Data[column][key]}} </td> {% endfor %} </tr> {% endfor %} </tbody> </table> My error code :Html error png I think I've any problems with my data because if I write {{column}} / {{key}} instead of {{BDD_Data[column][key]}} it displays all the values from my dataframe. Thank you all for your help. -
Database design for flexible Pricing & Discounts of Student Courses
I have a Django project for managing my dance school. We have Courses of specific CourseTypes, that are held at a specific Locations. Students can enroll in Courses. Currently my Course model has a simple price attribute - I now want to move to a more flexible pricing design where I can have different prices and discounts based on different variables. I have come up with the below design, based on advice from "The Data Model Resource Book". A Course is priced by PriceComponents. Prices are made up of "base" components and "discount" components. For example, a Course might have a "base" price of $400, and multiple "discount" components (either a fixed amount discount or percent discount). I am not planning to normalize ComponentType, instead keep it as an attribute of the PriceComponent model as a ChoiceField. A PriceComponent can be restricted to different variables. For example, a PriceComponent can be for a specific Location, for Students who are members of a specific PriceGroup, for specific CourseTypes and so on. That lets me price Courses and apply discounts differently, depending on combinations of these variables. A PriceComponent will be of a PriceType. For example, a Course has a trial class … -
sql.js (sql-wasm.js) Not Working in Javascript Using Django
Output is here.. {% block js %} var baseUrl = "{% static 'js/sql.js/dist' %}"; require.config({ baseUrl: baseUrl }); require(['sql-wasm'], function success(initSqlJs) { alert(typeof initSqlJs); //output: 'function' var config = { locateFile: filename => '${baseUrl}/${filename}' // locateFile: filename=> "{% static '${baseUrl}/${filename}' %}" } initSqlJs(config).then(function (SQL) { var db = new SQL.Database(); db.run("CREATE TABLE test (id INT, name TEXT);"); db.run("INSERT INTO test VALUES(1, 'Jacob');"); var result = db.exec("SELECT * FROM test;"); document.getElementById("output").innerHTML = JSON.stringify(result); }); }); {% endblock %} -
'int' object has no attribute 'days'. DurationField Django
I am trying to set default value of duration field. I want to send request without this value and then program get default value. If I send value 0 by postman it's okey but if I set defualt value as 0 then program treat it like int and i have this problem: "'int' object has no attribute 'days'". Is there any idea how to cast default value to duration field type ? -
Deploy both django and react on cloud using nginx
I have a digitalocean server and I have already deployed my Django backend server using gunicorn and nginx. How do I deploy the React app on the same server? -
How to unrar files in a django web application
I am trying to unrar files uploaded by users in django web application. I have gone through different approaches but none of them are working for me. The below methods work fine in my local OS (Ubuntu 18.04), but n't working in the server. I am using Python 3.6. import rarfile - here 'rarfile' is imported from python3.6/site-packages/rarfile. It is giving this error - bsdtar: Error opening archive: Failed to open '--' Following the steps suggested here, I installed 'unrar'. from unrar import rarfile - here it's being imported from python3.6/site-packages/unrar/ But this gave the error - LookupError: Couldn't find path to unrar library. So to solve the issue, I followed the steps mentioned here, and created UnRaR executable, and also set the path in my environment. This works fine in local, but unable to understand how to do the same in 'production environment'. import patoolib - importing from patool I also tried implementing patool, which worked fine in local but not in production and I am getting this error - patoolib.util.PatoolError: could not find an executable program to extract format rar; candidates are (rar,unrar,7z), This has become a big blocker in my application, can anyone please explain how to … -
how to rename fieldname in django_filters
I have created a Django-based webpage and using the Primary key and displaying id field. Here I am using django_filter and want to rename id field as DSID. Can anyone know the way to do it? any help in this issue would be appreciated from .models import * import django_filters class ShiftChangeFilter(django_filters.FilterSet): class Meta: model = ShiftChange fields = ['ldap_id', 'EmailID','id',] -
how to display a dropdown field predefined in my model?
class ItemDetails(models.Model): STATUS = ( ('In-Stock', 'In-Stock'), ('Out-of-Stock', 'Out-of-Stock'), ('issued-to', 'issued-to') ) serial_no = models.CharField(max_length=50,null=True) rem_qty = models.IntegerField(default=0) status = models.CharField(max_length=30, default='in-stock', choices=STATUS) model_no=models.ForeignKey(Items,on_delete= models.CASCADE) issued_to =models.ForeignKey(Prosecutions,on_delete=models.CASCADE) employee_name=models.CharField(max_length=50,null=True) created = models.DateTimeField(default=datetime.now()) -
Loading media files from a network drive in Django with Apache
I have a django page where I am trying to add a banner images which is stored in a network drive. In Dev environment: setting.py : MEDIA_URL = '/media/' MEDIA_ROOT = PureWindowsPath('//shared drive/folder/').drive urls.py: urlpatterns = [ path('admin/', admin.site.urls), ...... ...... ] urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) models.py: class WelcomePage(models.Model): departmentname = models.CharField(max_length=100,blank=True,null=True) bannerimage = models.ImageField(upload_to='DjangoPortal/welcome/images/',blank=True) home.html: <div class="card border-secondary mb-3"> <div class="card-body" style="padding: 0px !important;"> <img src="{{ pagedata.bannerimage.url }}" width="100%" /> </div> </div> with the above settings the page works perfectly In Production: All the above settings remains the same. In settings.py DEBUG =False and ALLOWED_HOSTS=[prod server ip, localhost] In httpd.conf I added below Define MEDIAROOT "//shared drive/folder/" Alias /media "${MEDIAROOT}" <Directory "${MEDIAROOT}"> Require all granted </Directory> but the image is not loading. Am I doing anything wrong? The technology specification is Windows Server 2012 R2 + Python 3.9 + Django 3.0.1 + SQL Server+ Apachelounge 2.4 Please guide if you have worked on or aware of this kind of scenario. -
I want to create a uniqueID for cutomers when they signup my webapp
I'm creating a signup page for my web app using Django and I would like to create a unique ID for customers when they signup in sequential order. ex:- first customer ID= 5000001 second customer ID:- 5000002 and so on I don't want the customer ID visible to the users. The customer Id is just for my purpose to create one to many relations to connect with their details in the database It would be really helpful if I can get some good suggestions -
Switch from default python interpreter to ipython in elpy (Django command)
Elpy uses the default python interpreter (elpy-django-command shell), I wondered if it is possible to use Ipython instead. -
Django alternative project structure
I have a django app which has alot of parts of the app seperated into files and folders like the following. app/ models/ __init__.py //imports everything from all model files my_app.py next_app.py ... views/ __init__.py //imports everything from all view files my_app.py next_app.py ... admin/ __init__.py //imports everything from all admin files my_app.py next_app.py ... It's not only 2 files in each folder, I'm getting close to 20 and it's starting to feel a bit messy. So, I came up with an alternative (which I've tested a bit so I think it works atleast), but I'm not sure if it's a bad idea to structure my project like this. (best practices etc.) This is my alternative: app/ modules/ my_app/ models.py views.py admin.py next_app/ models.py views.py admin.py models/ __init__.py //imports everything from models.py in every module in modules/ views/ __init__.py //imports everything from views.py in every module in modules/ admin/ __init__.py //imports everything from admin.py in every module in modules/