Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create object in model having foreigkey relation
I want to create an entry in this Something model in python manage.py shell using this Someting.objects.create(discussion_title="General", user_username="admin", content="Hello") models example class Discussion(models.Model): title = models.CharField(max_length=255, unique=True, blank=False,) users = models.ManyToManyField(User, blank=True, ) class Something(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) discussion = models.ForeignKey(Discussion, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) content = models.TextField(unique=False, blank=False) I am getting this error TypeError: Something() got an unexpected keyword argument 'discussion_title' -
Django key value pair to template
I am new to Django, and learning it for a school project. Part of the project is to have a time scheduler. I tought it was best to do with a key - value database structure, so I did. Now I am struggeling with getting it in to my template. This is my models.py key-value model: class generalSetting(models.Model): key = models.CharField(max_length=200, unique=True, null=True) value = models.CharField(max_length=200, null=True) def __str__(self): return self.key views.py: def timetable(request): generalSettings = generalSetting.objects.all() return render(request, 'VulnManager/timetable.html', {'generalSettings':generalSettings}) Here is the table on which I want to have the data <table id="tablePreview" class="table table-borderless table-hover"> <!--Table head--> <thead> <tr> <th></th> <th>Monday</th> <th>Tuesday</th> <th>Wednesday</th> <th>Thursday</th> <th>Friday</th> <th>Saturday</th> <th>Sunday</th> </tr> </thead> <!--Table head--> <!--Table body--> <tbody> <tr> <th scope="row">Scan?</th> <td><select class="form-control" id="scanMonday" disabled="true"><option>Yes</option><option>No</option></select></td> <td><select class="form-control" id="scanTuesday" disabled="true"><option>Yes</option><option>No</option></select></td> <td><select class="form-control" id="scanWednesday" disabled="true"><option>Yes</option><option>No</option></select></td> <td><select class="form-control" id="scanThursday" disabled="true"><option>Yes</option><option>No</option></select></td> <td><select class="form-control" id="scanFriday" disabled="true"><option>Yes</option><option>No</option></select></td> <td><select class="form-control" id="scanSaturday" disabled="true"><option>Yes</option><option>No</option></select></td> <td><select class="form-control" id="scanSunday" disabled="true"><option>Yes</option><option>No</option></select></td> </tr> <tr> <th scope="row">Time begin</th> <td><input type="text" id="startMonday" onchange="validateHhMm(this);" value="{{generalSettings(key='startMonday')}}" readonly /></td> <td><input type="text" id="startTuesday" onchange="validateHhMm(this);" value="9:00" readonly /></td> <td><input type="text" id="startWednesday" onchange="validateHhMm(this);" value="9:00" readonly /></td> <td><input type="text" id="startThursday" onchange="validateHhMm(this);" value="9:00" readonly /></td> <td><input type="text" id="startFriday" onchange="validateHhMm(this);" value="9:00" readonly /></td> <td><input type="text" id="startSaturday" onchange="validateHhMm(this);" value="" readonly /></td> <td><input type="text" id="startSunday" onchange="validateHhMm(this);" value="" … -
how to call django url with javascript?
i am first time using javascript. i want to know how can i use django urls in javascript. i have a problem with using django url link in javascript. i want to render product-detail page and product-update page using django url in javascript. index.js const Story = document.getElementById('approvedList'); const url = 'http://localhost:8000/api/approved/'; getPosts = () => { axios.get(url) .then((res) => { Story.innerHTML = ''; res.data.map((object) => { document.getElementById(".detaillink").onclick = function () { var detailLink = document.attr('id') location.href = "{% url 'detail' pk=object.pk %}" }; document.getElementById(".updatelink").onclick = function () { var updatelLink = document.attr('id') location.href = "{% url 'update' pk=object.pk %}" }; Story.innerHTML += ` <tr> <td>${object.id}</td> <td><a href="#" class="detailLink">${object.title}</a></td> <td> <div class="table-btns"> <a href="" class="updatelink"> Update </a> </div> </td> </tr> `; }) }) .catch(error => console.log(error)) }; getPosts(); setInterval(getPosts, 3000) -
when do you use quotes in django [closed]
I’m learning django and am a little confused about the use of quotes. It seems that you can use double quotes inside of double quotes instead of the standard double quote single quote paradigm. Also, it seems that some references to urls get quoted and others do not. Can someone point me to the documentation on the use of quotes when coding in django? -
Store data in session for Anonymous User in Django
I need to store token in session for Anonymous User. In one view the data is stored and I can see it in request. But in another request session is empty, but keys are equal. I store data as it in docs: request.session['token'] = token Also session in request in view where data was added: {'_SessionBase__session_key': '6isiuup8xdq7nfr34cmog78t6lkc13p3', 'accessed': True, 'modified': True, 'serializer': <class 'django.core.signing.JSONSerializer'>, 'model': <class 'django.contrib.sessions.models.Session'>, '_session_cache': {'access_token': 'access-sandbox-1d05b2ac-81b4-4126-a57a-7c0ba916252e'}} After that, in another view: {'_SessionBase__session_key': '6isiuup8xdq7nfr34cmog78t6lkc13p3', 'accessed': False, 'modified': False, 'serializer': <class 'django.core.signing.JSONSerializer'>} In settings: INSTALLED_APPS = [ ... 'django.contrib.sessions', ... ] MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', ... ] I read all docs and still can't find the reason of such strange behavior. Or may be I don't understand smth. -
Django Ajax how would i delete the comment using ajax instead of a normal request?
I have code set up so that users can delete comments on an article. However currently, when they delete the comment it will refresh the page and take them back to the top. I'm trying to implement Ajax so that when they delete the comment it'll do it without a page refresh. This is the code I have currently for deleting a comment. index.py <form action="{% url 'add-delete-view' %}" method="POST" class="ui form"> {% csrf_token %} <input type="hidden" name="comment_id" value="{{c.id}}"> <button type="submit" onClick="deleteComment({{c.id}})" id= "{{c.id}}" class="ui primary button c_edit{{c.id}}" name="submit_d_form">delete</button> urls.py path('deleteComment/', views.delete_comment, name='add-delete-view') views.py @login_required def delete_comment(request): comment_obj = Comment.objects.get(id=request.POST.get('comment_id')) comment_obj.delete() return redirect('index') I've attempted to try and implement Ajax but I'm just feeling hopeless in trying to get it work. In index.py I've added function: function deleteComment(comment_id) { var action = confirm("Are you sure you want to delete this comment?"); var comment = $(this) if (action != false) { $.ajax({ method: 'DELETE', url: '{% url "add-delete-view" %}', success: function (data, textStatus, jqXHR) { comment.remove(); }, }); } } But I'm just not sure where to go next or if this will even work. Any help or code would be greatly appreciated. It feels like this simple concept is very … -
CKEditor custom config not working, And it has different options inside and outside of admin panel
based on customizing CKEditor editor I declared a custom config in settings.py: CKEDITOR_CONFIGS = { 'awesome_ckeditor': { 'toolbar': 'Basic', 'toolbar_CustomToolbarConfig': [ {'name': 'clipboard', 'items': ['Bold', '-', 'Undo', 'Redo']}, {'name': 'paragraph', 'items': ['NumberedList', 'BulletedList', '-', 'BidiLtr', 'BidiRtl', '-', 'spellchecker' ]}, ], }, } this config is used in models.py: description = RichTextField(config_name='awesome_ckeditor', blank=True) in html file I use ckeditor in this way: <form action="{% url 'contact' %}" method="POST"> {% csrf_token %} <div> <textarea name="message" id="message" class="form-control"></textarea> </div> </form> <script type="text/javascript" src="{% static "ckeditor/ckeditor-init.js" %}"></script> <script type="text/javascript" src="{% static "ckeditor/ckeditor/ckeditor.js" %}"></script> <script src="//cdn.ckeditor.com/4.15.0/full/ckeditor.js"></script> <script> CKEDITOR.replace( 'message'); CKEDITOR.config.allowedContent = true; CKEDITOR.config.removeFormatAttributes = ''; </script> this config is not working. how to load it? before declaring this config, I was getting different editor options inside admin panel and outside ot it: inside admin panel: and outside it: how to fix this config so all pages have same config? -
Django&React, "detail": "Authentication credentials were not provided. (CSRF)
] ------ react ------ csrftoken.js import axios from 'axios'; import React from 'react'; function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].replace(' ', ''); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } export const CSRFToken = () => { const csrftoken = getCookie('csrftoken'); console.log('token : ' + csrftoken); return( <input type="hidden" name="csrfmiddlewaretoken" value={csrftoken}/> ) }; export default CSRFToken; module.js const getplayerEpic = (action$, state$) => { return action$.pipe( ofType(GET_player), withLatestFrom(state$), mergeMap(([action, state]) => { console.log(state.CSRFToken.props.value) return ajax.get('/api/player/', {headers: {'X-CSRFToken': state.CSRFToken.props.value }} ).pipe( map(response => { const player = response.response; return getplayerSuccess({player}); }), catchError(error => of({ type: GET_player_FAILURE, payload: error, error: true, }) ) ); }) ); }; ------ django(python) ------ view.py class Listplayer(generics.ListCreateAPIView): permission_classes = [djangomodelpermissions, ] queryset = playerList.objects.all() serializer_class = playerListSerializer settting.py ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'post', 'rest_framework', 'polls.apps.PollsConfig', 'notes', 'knox', 'patientList', 'hospital', 'doctor', 'diagnosis', 'diagnosis.core', 'fundusList', 'users', ] REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 10, 'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication',), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ] … -
django urls exceptions NoReverseMatch
Good day, I have got a Django project where I want to link to order_detail but I get this error: django.urls.exceptions.NoReverseMatch: Reverse for 'orderdetail' with arguments '('',)' not found. 1 pattern(s) tried: ['orders/myorder/detail/(?P<order_id>[0-9]+)$'] models.py from datetime import timezone from django.contrib.auth.models import User # Create your models here. from django.db import models from django.forms import ModelForm from django.urls import reverse from shop.models import Product from decimal import Decimal from django.core.validators import MinValueValidator, MaxValueValidator from coupons.models import Coupon class Order(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() address = models.CharField(max_length=250) phone_number = models.CharField(max_length=20) city = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) braintree_id = models.CharField(max_length=150, blank=True) reference_id = models.DateTimeField(auto_now_add=True, blank=True) coupon = models.ForeignKey(Coupon, related_name='orders', null=True, blank=True, on_delete=models.SET_NULL) discount = models.IntegerField(default=0, validators=[ MinValueValidator(0), MaxValueValidator(100) ]) class Meta: ordering = ('-created',) def __str__(self): return self.first_name def get_absolute_url(self): return reverse('orders:orderdetail', args=[self.id]) def get_total_cost(self): total_cost = sum(item.get_cost() for item in self.items.all()) return total_cost - total_cost * (self.discount / Decimal(100)) def delivery_fee(self): fee = 500 return fee def get_total_after_delivery(self): total = self.get_total_cost() + self.delivery_fee() return total class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='order_items', on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) def __str__(self): … -
Cannot resolve keyword 'articles' into field.Choices are: Choices are: author, caption,id etc
I am trying to relate articles for the user.Here are my codes: Models.py class User(AbstractUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.CharField(max_length=255,unique=True) username =models.CharField(max_length=80,unique=True,default='SOME STRING') USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() class Meta: verbose_name = _('user') verbose_name_plural = _('users') class Article(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='articles') caption = models.CharField(max_length=250) Serializers.py class UserSerializer(serializers.ModelSerializer): articles_set = serializers.SerializerMethodField() def get_articles_set(self, user): return ArticleViewSerializer(Article.objects.filter(articles__author=user), many=True).data class Meta: model = User fields = ('id','email','username','articles_set') class ArticleViewSerializer(serializers.ModelSerializer): author = UserSerializer(required=False,read_only=True) class Meta: model = Article fields = ('id','author','caption') def create(self, validated_data): return Article.objects.create(**validated_data) Now the issue here is that whenever i try to relate article to a user,i face with this problem Cannot resolve keyword 'articles' into field. Choices are: author, author_id, caption, comments, id How can i solve this problem? -
Django + Ajax. Data submitted two times in database when I click on button at first time
I use django for backend. Data submitted two times when I click button at first time and data submit one time when I clicked button second time and send response two time also. I am not know more about Jquery or Ajax.I need only one time data submit in database. views.py: @require_POST def checkAns(request,pk,ans,user): if request.method == 'POST': question = Question.objects.get(pk=pk) if ans == question.answer_hidden: message = 'Correct' fetch_name = Register.objects.get(name=user) user_data = SubmitAnswer.objects.get_or_create(name=fetch_name) score_in = SubmitAnswer.objects.get(name=fetch_name) score_in.score += question.point score_in.save() else: message = "False" ctx = {'message': message} return HttpResponse(json.dumps(ctx), content_type='application/json') question.html: **Other stuff like question,radio button,etc** <button type="submit" class="btn btn-primary" id="b1" onclick="getans()">click</button> <p id="userans"></p> <script> $(document).ready(function () { $('#b1').on('click', function (e) { const id = document.getElementById('question_id').className const ans = document.getElementById('userans').innerText const user = document.getElementById('session').innerText $(".rb").show(); $(".rb").attr("disabled", true); $.ajax({ type: "POST", url: `http://127.0.0.1:8000/checkAns/${id}/${ans}/${user}/`, data: { 'csrfmiddlewaretoken': '{{ csrf_token }}' }, dataType: "json", success: function (response) { console.log(response) }, error: function (rs, e) { if(rs.status === 404){ alert("Please, Select Appropriate Option") } else{ alert("sorry, Something went wrong!!!") } } }) }); }); </script> <script type="text/javascript"> function getans(e){ document.getElementById("userans").innerHTML = ""; var e = document.getElementsByTagName("input"); for(i = 0; i<=e.length; i++){ if(e[i].type == 'radio') { if(e[i].checked){ document.getElementById("userans").innerHTML = e[i].value } } } … -
Invalid symlink "venv/bin/python3"
I'm trying to upload my Django code to Heroku but I am getting a build error.. === Fetching app code failed. =!= Invalid symlink "venv/bin/python3". Cannot point outside the working directory My Pipfile is name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] [packages] django = "~=3.1.0" whitenoise = "==5.1.0" gunicorn = "==19.9.0" psycopg2-binary = "==2.8.5" pillow = "==7.2.0" django-debug-toolbar = "==2.2" environs = {version = "==8.0.0", extras = ["django"]} django-storages = "*" boto3 = "*" [requires] python_version = "3.8" Is anyone able to help me please? -
How can I storage IP addresses any time someone logs in my app? Django
My goal si to storage Ip addresses and make an alert if in the next login the ip address of that person isn't the same. How can I do? -
Django tests are not working but views do
I'm trying to test to insert data into db to test if My views are working. What could i do to see what's happening inside the page? I've one error, when i try to assert if data that I've sent to My form exists. The stranger thing is that when i run My application with runserver, everything works fine, but when i'm in test, the view doesn't work. -
Return Full image Url in Django Rest Framework For Image
I am facing problem in returned image url, which is not proper. My return image URL is "/media/slider_image/image/slider_image_4ea48daf-477d-4f00-93cb-7ac87c6f4002.JPG", but actual URL expected from serializer is http://127.0.0.1:8000/media/slider_image/image/slider_image_4ea48daf-477d-4f00-93cb-7ac87c6f4002.JPG Here is my snippet of my Code that I have tried. class ListSliderSerializer(SliderSerializers): images = serializers.SerializerMethodField('get_images') def get_images(self, instance): return [slider_image.image.url for slider_image in instance.slider_image.all()] class Meta(SliderSerializers.Meta): fields = ( 'images', 'section', 'tag', ) what should i return in return [slider_image.image.url for slider_image in instance.slider_image.all()] to get full url for my image? -
docker-compose Vue Connection Reset Error
I am trying to start my Vue.js and Django Application with docker-compose. I can access the Django server, but the Vue frontend answers with Error: The connection was reset. Here are my Files: Dockerfile-django: FROM alpine:latest RUN apk add --update python3 py3-pip WORKDIR /app/backend COPY . . RUN pip3 install -r requirements.txt RUN python3 manage.py makemigrations RUN python3 manage.py migrate EXPOSE 8000 CMD [ "python3", "manage.py", "runserver", "0.0.0.0:8000" ] Dockerfile-vue: FROM alpine:latest RUN apk add --update nodejs npm WORKDIR /app/frontend COPY . . RUN npm install --save axios @vue/cli bootstrap-vue v-tooltip @popperjs/core jquery @vue/test-utils jest RUN npm audit fix RUN npm run build EXPOSE 8080 CMD [ "npm", "run", "dev" ] docker-compose.yml: version: "3.8" services: django-server: build: context: "./backend" dockerfile: "Dockerfile-django" ports: - "8000:8000" container_name: app-backend vue-ui: build: context: "./frontend" dockerfile: "Dockerfile-vue" ports: - "8080:8080" container_name: app-ui Both containers start fine and as I said, I can access the Django server just fine. Only the frontend seems to be the problem. -
Django reload current page using a button
Is there actually any way to simply reload the page in Django I'm currently viewing, preferably at the template with a button? Why do I need this: My website displays messages and I simply just want to give the user the ability to click on a button to make the message disappear. To make a message disappear I have to reload the current page ... Implementing this is JS is not an option! Thanks and kind regards -
TypeError at /cart/ 'Product' object is not subscriptable
I'm creating cart model in RESTful API project. For each product in request by using for statement I want to save each product, cauz in one request may appear more than one product in cart. Below is my serializers.py: from rest_framework import serializers from main.serializers import ProductDetailsSerializer from main.models import Cart, Product, CartProduct # создаем сериализатор orderproduct class CartProductSerializer(serializers.ModelSerializer): class Meta: model = CartProduct fields = ('product', 'count') class CartProductRepresentationSerializer(serializers.ModelSerializer): id = serializers.IntegerField(source='product.id') title = serializers.CharField(source='product.title') class Meta: model = CartProduct fields = ('id', 'title', 'price', 'count', 'product') class AddProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('id') class CartSerializer(serializers.ModelSerializer): items = CartProductSerializer(many=True, write_only=True) # здесь мы добавляем этот продукт заказа class Meta: model = Cart fields = ('count', 'items') # передаем все эти поля сюда def get_total_cost(self, obj): return obj.get_total_cost() # здесь мы добавляем total cost (def get_total_cost(self. obj)) def create(self, validated_data): request = self.context.get('request') items = validated_data.pop('items') cart = Cart.objects.create(**validated_data) if request.user.is_authenticated: cart.user = request.user cart.save() for product in items: product = product['product'] # print(product) product_id = request.GET.get('product') CartProduct.objects.create(cart=cart, product_id=product_id, price=product.price, count=product['count']) product.save() def to_representation(self, instance): representation = super().to_representation(instance) representation['user'] = instance.user representation['product'] = CartProductRepresentationSerializer(instance.products.all(), many=True, context=self.context).data return representation Here is the models. I create Cart and CartProduct … -
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?