Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin site 'int' has no len() error on model form submit
When trying to submit a model form (/add/) in the Django admin site, I get the following error: TypeError object of type 'int' has no len() Models.py: class Card(models.Model): visible = models.BooleanField(default=True, verbose_name="Visible to Customers?") software = models.ForeignKey(Software, default=1, on_delete=models.CASCADE) product = ChainedForeignKey( Product, chained_field="software", chained_model_field="software", auto_choose=True, show_all=False, sort=True, default=0,) utility = models.ForeignKey(Utility, verbose_name='Utilities', default=1, on_delete=models.CASCADE) function = ChainedForeignKey( Function, chained_field="utility", chained_model_field="utility", auto_choose=True, show_all=False, sort=True, default=0,) error_code = models.ForeignKey(ErrorCode, default=0, on_delete=models.CASCADE, help_text="Please only use for error codes, if no code, leave empty.") message = RichTextUploadingField(default="", help_text='Message can include markdown for styling.') tags = RichTextUploadingField(default="", blank=True, null=False, help_text='Add Text that can be used as tags for searching for this card.') encountered = models.ManyToManyField(Encountered, default=0, verbose_name='Encountered in', help_text='Version or Year. Select "N/A" if unknown.') resolved = models.ForeignKey(Resolved, default=0, on_delete=models.CASCADE, verbose_name='Resolved in', help_text='If not resolved, enter "N/A".') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) card_created_by = models.ForeignKey( 'auth.User', related_name='card_created_by', on_delete=models.CASCADE, verbose_name='Created by', null=True) last_edited_by = models.ForeignKey( 'auth.User', related_name='last_edited_by', on_delete=models.CASCADE, verbose_name='Last edited by', null=True) card_view_count = models.IntegerField(default=0) class Solution(models.Model): card = models.ForeignKey(Card, on_delete=models.CASCADE, null=True) cause = RichTextUploadingField(blank=False, help_text='Message can include markdown for styling.') cause_solution = RichTextUploadingField(blank=False, verbose_name='Solution', help_text='Message can include markdown for styling.') solution_edited_by = models.ForeignKey( 'auth.User', related_name='solution_edited_by', verbose_name='Last edited by', on_delete=models.CASCADE, blank=True, null=True ) … -
How to only accept date inputs of more than 18 years ago in Django
I have a form that allows users to update their birthday on their profile. I want it to only be valid if the user is at least 18 years of age. Here's what I've tried: models.py class Profile(models.Model): birthday = models.DateField() forms.py from django import forms from datetime import datetime from .models import Profile class ProfileUpdateForm(forms.ModelForm): birthday = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'})) def clean_birthday(self): dob = self.cleaned_data['birthday'] age = (datetime.now() - dob).days / 365 if age < 18: raise forms.ValidationError('You must be at least 18 years old') return dob class Meta: model = Profile fields = ('birthday',) Upon submit I am getting the TypeError unsupported operand type(s) for -: 'datetime.datetime' and 'datetime.date' Here is my view: @login_required def update_my_profile_view(request): profile = Profile.objects.get(user=request.user) form = ProfileUpdateForm(request.POST or None, instance=profile) if request.method == 'POST': if form.is_valid(): form.save() return redirect('users:my_profile') Can somebody please explain what I've done wrong? -
update django models column based on other column
I have a model like class tbl_payment(models.Model): document_id = models.ForeignKey(tbl_invoice, on_delete=models.CASCADE) client_id = models.ForeignKey(tbl_customer, on_delete=models.CASCADE) total_amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) paid_amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) balance = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) date = models.DateField(blank=True, null=True) status = models.CharField(max_length=50) Now what I want to do is whenever a new record is added, or an existing record changes, balance should be updated as the difference between total_amount and paid_amount (simple maths), and based on my balance column, I want to save status as Paid, Partial or Unpaid. I want to refrain from calculating the balance in my views and then saving in the database, instead, I want to handover this part to my models so that my models take care of the balance and I may avoid errors which I am subconsciously afraid of. I came to know that this is done something like this class tbl_payment(models.Model): document_id = models.ForeignKey(tbl_invoice, on_delete=models.CASCADE) client_id = models.ForeignKey(tbl_customer, on_delete=models.CASCADE) total_amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) paid_amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) balance = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) date = models.DateField(blank=True, null=True) status = models.CharField(max_length=50) @property def balance(self, value): return self.total_amount - paid_amount but what should I pass in place of value?? also when I … -
Why do I get: save() missing 1 required positional argument: 'self'
If I put to this endpoint, I get the following error: save() missing 1 required positional argument: 'self' Can anyone understand why? If any addiotional information is needed, please let me know. @api_view(['GET', 'PUT']) def qc_demux_detail(request, demux_qc_id): qc_demux_results = DemuxQCResult.objects.filter(demux_qc_id=demux_qc_id) if request.method == "GET": serializer = QCDemuxResultSerializer(qc_demux_results, many=True) return Response(serializer.data) if request.method == "PUT": serializer = QCDemuxResultSerializer(DemuxQCResult, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
string dictionary converted into json form
I have a textarea where input is in this format { "access_token": "#TOKEN_ACCESS_TOKEN", "tickets": [ { "hr_remarks": "#TOKEN_HR_REMARKS", "status": "#TOKEN_STATUS", "ticket_id": #TOKEN_TICKET_ID } , { "hr_remarks": "#TOKEN_HR_REMARKS", "status": "#TOKEN_STATUS", "ticket_id": #TOKEN_TICKET_ID } ] } I want to convert this data into json form. I try to use through json.load() it cause an error: Json decoder Error -
django check_password return false with correct password
i have this custom user with email backend and as you can see i'm using set_password before saving but its still not matching with correct password on this user.check_password(password) in emailbackend and i'm creating user with drf backend.py: 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: print('this is user right', user, password) if user.check_password(password): return user return None serializers.py: class CustomUserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=False) class Meta: model = CustomUser fields = ('id', 'first_name', 'last_name', 'email', 'mobile_number', 'password', 'is_active', 'user_type', 'otp') def create(self, validated_data): user = CustomUser( email=validated_data['email'], mobile_number=validated_data['mobile_number'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], user_type=validated_data['user_type'], ) user.set_password(validated_data['password']) user.save() return user -
How to use more than one _base.html file using django-two-factor-auth?
Django-two-factor-auth library requires one to use the two_factor/_base.html to customize the styling when integrating into your website. The base for my login page is however different to that for the dashboard of a logged in user. How can I use a different _base.html for the login page instead of using the same base for all the two factor pages? -
Django getattr by name for related field call query with select_related and prefetch_related
I have a class with multiple relations like this: class Object() -> class TT() -> -> class User() -> class Actor() -> -> class Type() -> class Type() Need to get Object attributes and relation attributes by dinamic names like "tt__name" / "tt__user__type" / "actor__type__date" and oth. For querying i'm using select_related and prefetch_related('xxxx',...), but when i use getattr like this: if '__' not in model_field: cell_value = getattr(qs_object, model_field, None) else: r_class, r_field = model_field.split('__', maxsplit=1) related_object = getattr(qs_object, r_class, None) while '__' in r_field: r_class, r_field = r_field.split('__', maxsplit=1) related_object = getattr(related_object, r_class, None) cell_value = getattr(related_object, r_field, None) Django call query for each getattr with relation. How to realize this another way or force Django to get attr from fetched values? Halp -
Create a django home page
How to create django home page , with base.html , I ask for a simple sample, and routing ? I have already tried , to chreate sample code for home how to continue Thankyou, -
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 %}