Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to prevent end users from editing a hidden input value in a Django social website
In a website having a "Comment" and "reply to a comment" system. After each comment in the template, There's a "Add a reply" form which have a hidden input to carry the comment pk on its value attribute. How to prevent the end user from editing that hidden input value ? And If this is not possible, What would be the correct approach ? -
button 'pay now!' not working for redirect to payment-done view in payment-braintree and django
I am writing an online store based on the Django 3 By Example 3rd Edition book. I encountered a problem with the book's codes in the payment section, I searched the internet and updated some of the codes, but I still have a problem! After filling out the debit card form, when I click on the "pay now!" button, I am not redirected to the Don page! Thank you for your guidance. process.html {% extends "shop/base.html" %} {% block title %} Pay by credit card {% endblock %} {% block sidenavigation %} {% endblock %} {% block content %} Pay by credit card <form method="post" autocomplete="off"> {% if braintree_error %} <div class="alert alert-danger fade in"> <button class="close" data-dismiss="alert">&times;</button> {{ braintree_error|safe }} </div> {% endif %} <div class="braintree-notifications"></div> <div id="braintree-dropin"></div> <input style="background-color: #0783ca" id="submit-button" class="btn btn-success btn-lg btn-block" type="button" value="Pay now!"/> </form> <script> var braintree_client_token = "{{ client_token}}"; var button = document.querySelector('#submit-button'); braintree.dropin.create({ authorization: "{{client_token}}", container: '#braintree-dropin', card: { cardholderName: { required: false } } }, function (createErr, instance) { button.addEventListener('click', function () { instance.requestPaymentMethod(function (err, payload) { $.ajax({ type: 'POST', url: '{% url "payment:process" %}', data: { 'paymentMethodNonce': payload.nonce, 'csrfmiddlewaretoken': '{{ csrf_token }}' } }).done(function (result) { //do accordingly }); … -
Update user profile with user uuid
I want to update user profile passing user uuid as kwarg. Here is the url: path("profile/update/<uuid:pk>", UpdateProfile.as_view(), name="update_profile"), However, after I try to update my profile, it gives me an error. Here is my view: class UpdateProfile(LoginRequiredMixin, UpdateView): model = Profile user_type_fields = { "Buyer": ["photo", "first_name", "last_name", "city"], "Celler": ["photo", "name", "city", "address"], } def get(self, request, *args, **kwargs): print(kwargs) self.fields = self.user_type_fields[get_user_model().objects.get(pk=kwargs["pk"]).type] return super().get(request, *args, **kwargs) And here is the error itself: Page not found (404) No profile found matching the query As I understand, django tries to find profile with uuid as in url, doesn't find it and returns me this error. However, if I change model in my view to user, it wouldn't be able to find fields as they belong to profile model. The only working option was to pass profile id as kwarg, but I don`t find it preferrable due to security reasons. Could someone give me an advice on how to update profile with user uuid in kwargs? Thanks in advance! -
Authenticate serverless API against Django user pool
I would like to move an API from Django server on ec2 to serverless (AWS API gateway + Lambda) because of better scalability. I need authentication/authorization for this API against my Django user pool, but that would mean polling Django server because of auth.. and I am back where I was regarding scalability. What would be my option to deal with it in a scalable (lambda like scalable) way? I was thinking about creating Cognito user pool and duplicate users from Django there. Is there a better option? -
Django IntegrityError: UNIQUE constraint failed: pu_limity.zakazka_id
I am getting following error, when I try to import csv file and save data to database: IntegrityError at /limity/limity_csv_import UNIQUE constraint failed: pu_limity.zakazka_id models.py class Limity(models.Model): zakazka = models.ForeignKey(Zakazky, on_delete=models.CASCADE) p_el = models.DecimalField("E/L", decimal_places=2, max_digits=4, null=True, blank=True) p_ml = models.DecimalField("M/L", max_digits=6, decimal_places=4, null=True, blank=True) p_prispevek = models.DecimalField("Příspěvek", max_digits=10, decimal_places=2, null=True, blank=True) p_pu = models.DecimalField("PU", max_digits=10, decimal_places=2, null=True, blank=True) aktualizace = models.DateTimeField(auto_now=True, null=True) @classmethod def create_from_csv_line(cls, line): l = Limity() try: l.zakazka = Zakazky.objects.get(kod=line["Zakazka"]) except Zakazky.DoesNotExist: print(line["Zakazka"]) l.zakazka, _ = Zakazky.objects.get_or_create(kod=line["Zakazka"]) except: print(line["Zakazka"]) l.p_el = line["EL"] l.p_ml = line["ML"] l.p_prispevek = line["Prispevek"] l.p_pu = line["PU"] l.save() views.py class LimityCSVImportView(LoginRequiredMixin, SuccessMessageMixin, FormView): template_name = "limity/limity_csv_import.html" form_class = LimityCSVForm def test_func(self): return self.request.user.is_superuser def post(self, request, *args, **kwargs): form: LimityCSVForm = LimityCSVForm(request.POST, request.FILES) if form.is_valid(): csv_file = form.cleaned_data["uploaded_file"] decoded_file = csv_file.read().decode('utf-8-sig') io_string = io.StringIO(decoded_file) reader = csv.DictReader(io_string, delimiter=",", skipinitialspace=True) record_count = 0 for line in reader: Limity.create_from_csv_line(line=line) record_count += 1 context = self.get_context_data() my_text = ' nových limitů vloženo.' messages.success(request, str(record_count) + my_text) return render(request, self.template_name, context) else: return self.form_invalid(form) Error arises when data from form saved at line l.save() I red some answers for this error and I tried in @classmethod: el = (line["EL"]) if not el: l.p_el = 0 else: … -
Enabling browser link for django in visual studio 2022
Is it possible to enable browser link for django website in VS2022 ? Im using default template for building Django website in vs and its kinda annoying for every change to stop and start the project again and again. i know i can do this if i use the console and run "Python manage.py runserver" but i want to use VS2022 debug engines too. if i use Python manage.py runserver and change the code it will refresh browser for me. -
Can't authenticate a user in Django rest framework
im trying to get data of an authenticated user using token, im using postman to send a get request and get the data i need but im reciveing a response "detail": "Authentication credentials were not provided." this is the view ` class ReceiveMessagesView(viewsets.ModelViewSet): serializer_class = MessageSerializer permission_classes = [permissions.IsAuthenticated] http_method_names = ['get', 'post'] def get_queryset(self): user = self.request.user queryset = Message.objects.filter(receiver=user) return queryset` settings REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } In the postman request im sending in Authorizaion the key as "Token" and value as the user i want data about's token tried to send an authorized get request and recived authorized user's data -
pytest parametrize I am getting TypeError: missing required positional arguments
I'm trying to use pytest.mark.parametrize import pytest from rest_framework.test import APITransactionTestCase class TestBulkImport(APITransactionTestCase) @pytest.mark.parametrize('data, expected_response', [ ( {'body': 'data;to;validate'}, {'body': ['error response']} ), ]) def test_bulk_import_validations(self, data, expected_response): response = self.client.post(reverse('path:to:url'), data=data) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual(response.json(), expected_response) I'm running the testcase using following command: pytest path/to/test/file::TestBulkImport::test_bulk_import_validations I'm getting following error: def _callTestMethod(self, method): > method() E TypeError: test_bulk_import_validations() missing 2 required positional arguments: 'data' and 'expected_response' -
developer of django
i am a developer . #inclue.life i am a developer . #inclue.life -
django project ,runserver wsgi working but asgi server configure but still not wroking
setting.py setting.py asgi.py routing.py consumers.py runserver asgi not show django project asgi server not work pls tell me how to solution this problem -
Django Rest how to save current user when creating an new blog?
When I am creating an blog post I also want to automatically save the current user without selecting the user manually as a blog author. here is my code: models.py: class Blog(models.Model): author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) blog_title = models.CharField(max_length=200, unique=True) serializers.py class BlogSerializer(serializers.ModelSerializer): class Meta: model = Blog views.py class BlogViewSet(viewsets.ModelViewSet): queryset = Blog.objects.all().order_by('-id') serializer_class = BlogSerializer pagination_class = BlogPagination lookup_field = 'blog_slug' def get_permissions(self): if self.action == 'retrieve': permission_classes = [IsOwnerOrReadOnly] elif self.action == 'list': permission_classes = [IsOwnerOrReadOnly] else: permission_classes = [IsOwnerOrReadOnly & IsAuthorGroup] return [permission() for permission in permission_classes] -
Point of Sales System Using python
Point of Sales System Using python. Guys, I need your experience to develop my POS system. These are my question. Please share your opinion about this question. This is my basic idea about this POS system. I am trying to create a POS system for a shop with various items such as supermarkets and electronic items. It means that has multiple types of products in this shop. I need to add stock management also this software not only that it is necessary to add expiration dates to some categories of products as well (My idea is to send an alert to shop owners about expired that products). Among these features, I need to add a thermal printer and a barcode reader as well. And also I need to generate some sales reports as well with the net profit. These are my questions. I decided to use python to create my POS system. Is that language ok for that software? If it is ok, If I try to implement it as a stand-alone application, which is the most suitable GUI builder for that? (Ex: PyQt, Tkinter, Kivy). Is that ok to use Django for this ? Based on my basic idea … -
How to safely add an additional fee for additional services in an online store?
I have an online car rental store built on Python Flask. My problem is that: When choosing a car, the customer goes to the checkout page, where he can choose additional services, for example: GPS navigator, child seats and other services. The cost of some services depends on the number of rental days, for example, for a Gps navigator, the cost of 1 day is $ 5. The question is, how can I safely get the cost of these additional services from the FrontEnd and add to the cost of the car received from the BackEnd side I am trying to safely connect the cost of renting a car with the cost of additional services, some of which depend on the number of rental days.My task is to implement this system as safely as possible, but I do not know how it can be done -
ValueError: The view **** didn't return an HttpResponse object. It returned None instead
I'm using Django forms to handle user input for some point on my Django app .. but it keeps showing this error whenever the user tries to submit the form ValueError: The view *my view name goes here* didn't return an HttpResponse object. It returned None instead here is my code : Forms.py class sendBreachForm(forms.Form): """ Form for sending messages to users. """ text = forms.CharField(max_length=100) image = forms.FileField() cords = forms.CharField(widget=forms.TextInput( attrs={"type":"hidden"} )) views.py @login_required def web_app(request): if request.user.is_staff or request.user.is_superuser: return redirect('/ar/system/') else: if request.method == "POST": form = sendBreachForm(request.POST) print("AAAAAAAAa in a post request") if form.is_valid(): print("AAAAAAAAa form is valid") text = form.cleaned_data['text'] image = form.cleaned_data['image'] cords = form.cleaned_data['cords'] try: new_breach = Breach.object.create(text=text,image=image) add_form_cords_to_breach(request,new_breach,cords) print("AAAAAAAA added breach") return render(request,"web_app.html",context) except : print("AAAAAAAA error ") return render(request,"web_app.html",context) # raise Http404('wrong data') else: form = sendBreachForm() context = {} context['form']=form context['all_elements'] = WaterElement.objects.all() current_site = Site.objects.get_current() the_domain = current_site.domain context['domain'] = the_domain all_layers = MapLayers.objects.all() context['all_layers']=all_layers return render(request,"web_app.html",context) HTML <form method ='post'> {% csrf_token %} {{form.text}} <label for="text">وصف المعاينة</label> {{form.image}} <label for="image">صورة المعاينة</label> {{form.cords}} <input type="submit" value = "إرسال المعاينة"> </form> -
JSONDecodeError - request.body returns empty string Django
I am trying to access some JSON data from my views.py page but it seems i'm sending empty strings? My JS code document.querySelector('#compose-form').onsubmit = () => { const recipients = document.querySelector('#compose-recipients').value const subject = document.querySelector('#compose-subject').value const body = document.querySelector('#compose-body').value fetch('/emails', { method: 'POST', body: JSON.stringify({ recipients: String(recipients), subject: String(subject), body: String(body) }) }) .then(response => response.json()) .then(result => { load_mailbox('sent'); console.log(result); }); return false; }; What i was trying to replicate: fetch('/emails', { method: 'POST', body: JSON.stringify({ recipients: 'baz@example.com', subject: 'Meeting time', body: 'How about we meet tomorrow at 3pm?' }) }) .then(response => response.json()) .then(result => { // Print result console.log(result); }); recipient, subject, and body are expected to be strings, given that i am grabbing mine from a form and have them in a variable i thought to convert them to strings **Template ** <form id="compose-form" action="{% url 'compose' %}" method="POST"> <div class="form-group"> From: <input disabled class="form-control" value="{{ request.user.email }}"> </div> <div class="form-group"> To: <input id="compose-recipients" class="form-control"> </div> <div class="form-group"> <input class="form-control" id="compose-subject" placeholder="Subject"> </div> <textarea class="form-control" id="compose-body" placeholder="Body"></textarea> <input type="submit" class="btn btn-primary" id="compose-submit"/> </form> URL path("emails/", views.compose, name="compose"), Views.py data_unicode = request.body.decode('utf-8') data = json.loads(data_unicode) when i debug this is what i get: (return) body: b' ' … -
Vue3 frontend, Django back end. Key error for validated data in serializer
I have a Vue front end that collects data (and files) from a user and POST it to a Django Rest Framework end point using Axios. Here is the code for that function: import { ref } from "vue"; import axios from "axios"; const fields = ref({ audience: "", cancomment: "", category: "", body: "", errors: [], previews: [], images: [], video: [], user: user, }); function submitPost() { const formData = { 'category': fields.value.category.index, 'body': fields.value.body, 'can_view': fields.value.audience, 'can_comment': fields.value.cancomment, 'video': fields.value.video, 'uploaded_images': fields.value.images, 'user': store.userId }; console.log(formData['uploaded_images']) axios .post('api/v1/posts/create/', formData, { headers: { "Content-Type": "multipart/form-data", "X-CSRFToken": "{{csrf-token}}" } }) .then((response) => { if(response.status == 201){ store.messages.push("Post created successfully") } }) .catch((error) => { messages.value.items.push(error.message) }) } When I post data the response I see on the server side is: uploaded_data = validated_data.pop('uploaded_images') KeyError: 'uploaded_images' that comes from this serializer: class PostImageSerializer(serializers.ModelSerializer): class Meta: model = PostImage fields = ['image', 'post'] class PostSerializer(serializers.ModelSerializer): images = PostImageSerializer(many=True, read_only=True, required=False) uploaded_images = serializers.ListField(required=False, child=serializers.FileField(max_length=1000000, allow_empty_file=False, use_url=False),write_only=True) class Meta: model = Post fields = [ "category", "body", "images", "uploaded_images", "video", "can_view", "can_comment", "user", "published", "pinned", "created_at", "updated_at", ] def create(self, validated_data): uploaded_data = validated_data.pop('uploaded_images') new_post = Post.objects.create(**validated_data) try: for uploaded_item in uploaded_data: … -
Problem : Can't parse 'center'. Sequence item with index 0 has a wrong type
TypeError at /mark_your_attendance Can't parse 'center'. Sequence item with index 0 has a wrong type Hello guys! i am working related with attendance system using Face Recognition, i have trained the captured images once want to mark the attendance it gives me following error, i have used django at backend. def mark_your_attendance(request): detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor( 'face_recognition_data/shape_predictor_68_face_landmarks.dat') # Add path to the shape predictor ######CHANGE TO RELATIVE PATH LATER svc_save_path = "face_recognition_data/svc.sav" with open(svc_save_path, 'rb') as f: svc = pickle.load(f) fa = FaceAligner(predictor, desiredFaceWidth=96) encoder = LabelEncoder() encoder.classes_ = np.load('face_recognition_data/classes.npy') faces_encodings = np.zeros((1, 128)) no_of_faces = len(svc.predict_proba(faces_encodings)[0]) count = dict() present = dict() log_time = dict() start = dict() for i in range(no_of_faces): count[encoder.inverse_transform([i])[0]] = 0 present[encoder.inverse_transform([i])[0]] = False vs = VideoStream(src=0).start() sampleNum = 0 while(True): frame = vs.read() frame = imutils.resize(frame, width=800) gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = detector(gray_frame, 0) for face in faces: print("INFO : inside for loop") (x, y, w, h) = face_utils.rect_to_bb(face) face_aligned = fa.align(frame, gray_frame, face) cv2.rectangle(frame, (int(x, y)), (int(x+w, y+h)), (0, 255, 0), 1) (pred, prob) = predict(face_aligned, svc) if(pred != [-1]): person_name = encoder.inverse_transform(np.ravel([pred]))[0] pred = person_name if count[pred] == 0: start[pred] = time.time() count[pred] = count.get(pred, 0) + 1 if … -
Django, how to display separate html blocks, which can then be edited in one place
I need to display the navbar, footer, main, base, title - in separate blocks, which can then be edited in one place, and the changes will occur everywhere Сan you give me an idea how to do it, I have no idea just I thought to do it with this function {% extends "..{directory}/{the name of html page}.html" %} But I think this won't work -
Send a welcome email after the user has confirmed his account in django
I'm trying to figure out how I can send welcome emails in Django after the user confirms their account. The welcome email should be sent only to users who have their emails confirmed (active users after signing up) and should be sent after the confirmation email. Any help in solving this will be highly appreciated models from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email_confirmed = models.BooleanField(default=False) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() views from django.contrib.auth import login from django.contrib.auth.models import User from django.utils.encoding import force_text from django.utils.http import urlsafe_base64_decode from core.tokens import account_activation_token # Sign Up View class SignUpView(View): form_class = SignUpForm template_name = 'commons/signup.html' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False # Deactivate account till it is confirmed user.save() current_site = get_current_site(request) subject = 'Activate Your MySite Account' message = render_to_string('emails/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) messages.success(request, ('Please Confirm your email to complete registration.')) return redirect('login') return render(request, self.template_name, {'form': … -
django rest framework what is login as the definition
Let me say in advance that thank you for reading my question. The problem I'm facing is related to login and permission from frontend. For example, log in as a user from the browser(like hit localhost:8080/admin in the search engine), and then you can see the user name on the right upper side of the screen which indicates the user is logged in. How Django identify the user login is that when you log in csrftoken is created and set in the cookies, so if you delete csrftoken, the username is disappeared, so you need to log in to access admin if you need. This login system is related to permission.IsAutenticated, so if 'DEFAULT_PERMISSION_CLASSES' : ['rest_framework.permissions.IsAuthenticated'], you cannot access any data if you are not logged in. Then I implemented social google login which receives google access_token to log in as a Django user(I will omit to describe how to get a google access token process), which works fine in the browser. I can see the username on the screen, and permission is working ok. But when I hit google social login endpoint from the front end, I can't log in, also csrftoken is not created in the cookies.(no error … -
PERFORMANCE Calling multiple times a posgres db to get filtered queries vs querying all objects and filtering in my django view
I'm working in a Django project and it has a postgreSQL db. I'm calling multiple times the model to filter the results: latest = Product.objects.all().order_by('-update_date')[:4] best_rate = Product.objects.all().order_by('rating')[:2] expensive = Product.objects.all().order_by('-price)[:3] But I wonder if it's better for performance and resources consumption to just do 1 query and get all the objects from the database and do the filtering inside my Django view. all = Product.objects.all() # Do some filtering here iterating over variable all Which of these do you think would be the best approximation? Or do you have a better option? -
Trying to embed a form within a form of foreign keys
I'm trying to create a form where a logged in user (PrincipalGuest) can update themselves but also multiple guests (AccompanyingGuest). I want an entire form with the attending and dietary_restrictions field embedded within a form, not just the ModelMultipleChoiceField. models.py class Guest(models.Model): """ """ attending = models.ManyToManyField("itinerary.Event", blank=True) dietary_restrictions = models.ManyToManyField(DietaryRestrictions, blank=True) last_modified = models.DateTimeField(auto_now=True) class Meta: abstract = True class PrincipalGuest(Guest, AbstractUser): """ """ USERNAME_FIELD = "email" REQUIRED_FIELDS = [] username = None email = models.EmailField(_("email address"), unique=True) phone_number = PhoneNumberField(null=True) address = AddressField(on_delete=models.CASCADE, null=True) objects = PrincipalGuestManager() @property def name(self): return self.first_name + " " + self.last_name def __str__(self): return self.name class AccompanyingGuest(Guest): """ """ principal = models.ForeignKey( PrincipalGuest, related_name="accompanying_guests", on_delete=models.CASCADE ) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) is_under_ten = models.BooleanField(default=False) @property def name(self): return self.first_name + " " + self.last_name def __str__(self): return self.name views.py class RendezvousFormView(SuccessMessageMixin, UpdateView): template_name = "rsvp.html" form_class = RendezvousForm success_url = "/rsvp" success_message = "Thank you for your RSVP" def get_object(self): return self.request.user forms.py class RendezvousForm(ModelForm): """ """ first_name = CharField( label="", widget=TextInput(attrs={"placeholder": "First Name"}) ) last_name = CharField( label="", widget=TextInput(attrs={"placeholder": "Last Name"}) ) email = CharField(label="", widget=TextInput(attrs={"placeholder": "Email"})) phone_number = CharField( label="", widget=TextInput(attrs={"placeholder": "Phone Number"}) ) address = AddressField( label="", widget=AddressWidget(attrs={"placeholder": … -
NOT NULL constraint failed: ial_profile.user_id
I am new to Django and was trying to follow a tutorial. But i came across this problem and is not able to solve it myself. When i try to access 127.0.0.1:8000/profile/id(1,2,3...) then it is throwing 'IntegrityError'. Can anyone please help me to overcome it? Code example : views.py from django.shortcuts import render from .models import Profile # Create your views here. def dashboard(request): return render(request, "base.html") def profile_list(request): profiles = Profile.objects.exclude(user=request.user.id) return render(request, "ial/profile_list.html", {"profiles": profiles}) def profile(request, pk): if not hasattr(request.user, 'profile'): missing_profile = Profile(user=request.user.id) missing_profile.save() profile = Profile.objects.get(pk=pk) # edit 1 if request.method == "POST": current_user_profile = request.user.profile data = request.POST action = data.get("follow") if action == "follow": current_user_profile.follows.add(profile) elif action == "unfollow": current_user_profile.follows.remove(profile) current_user_profile.save() return render(request, 'ial/profile.html', {'profile': profile}) models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) follows = models.ManyToManyField( "self", related_name = "followed_by", symmetrical=False, blank=True ) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: user_profile = Profile(user=instance) user_profile.save() user_profile.follows.set([instance.profile.id]) user_profile.save() profile.html {% extends 'base.html' %} {% block content %} <div class="column"> <div class="block"> <h1 class="title is-1"> {{profile.user.username|upper}}'s djail </h1> </div> … -
Django DecimalField fails to save even though I give it a floating number
class WithdrawRequests(models.Model): withdraw_hash = models.CharField(max_length=255, unique=True, db_index=True) timestamp = models.DateTimeField(auto_now_add=True) username = models.CharField(max_length=255, unique=False, db_index=True) currency = models.CharField(max_length=255, unique=False, db_index=True) user_balance = models.DecimalField(max_digits=300, default=0.0, decimal_places=150) withdraw_address = models.CharField(max_length=255, unique=False, db_index=True) withdraw_amount = models.DecimalField(max_digits=30, default=0.0, decimal_places=15) This is my models.py file. currency = request.data['currency'] payload = jwt.decode(token, settings.SECRET_KEY) user = User.objects.get(id=payload['user_id']) timestamp = datetime.datetime.now() timestamp = timestamp.timestamp() withdraw_hash = hashlib.sha256() withdraw_hash.update(str(timestamp).encode("utf-8")) withdraw_hash = withdraw_hash.hexdigest() username = user.username currency_balance = GAME_CURRENCIES[request.data['currency']] user_balance = getattr(user, currency_balance) withdraw_address = request.data['withdraw_address'] withdraw_amount = request.data['withdraw_amount'] if user_balance < withdraw_amount: return Response({ "message": "Not enough funds." }) else: # row format - hash timestamp username currency user_balance withdraw_address withdraw_amount withdraw = WithdrawRequests() withdraw.withdraw_hash = withdraw_hash, withdraw.timestamp = datetime.datetime.now(), withdraw.username = username, withdraw.currency = currency, withdraw.user_balance = user_balance, withdraw.withdraw_address = withdraw_address, withdraw.withdraw_amount = withdraw_amount withdraw.save() And here is the views.py file. Whatever I do the error is the following. ... File "C:\Users\Msi\cover_game\cover\lib\site-packages\django\db\models\fields\__init__.py", line 1554, in to_python raise exceptions.ValidationError( django.core.exceptions.ValidationError: ['“(0.011095555563904999,)” value must be a decimal number.'] As you can see with user_balance everything is fine and it's floating number. -
how to upload multipe images in django rest framework(drf)
I want to upload multiple images,Is there a way to do it without using foreign keys. The images is just a attribute in my model. model.py class sellGoods(models.Model): img = models.ImageField(max_length=100, upload_to=get_file_path, default='sell.png', verbose_name='图片', null=True, blank=True) # 与用户绑定 # user = models.ForeignKey(UserInfo, on_delete=models.CASCADE) goods_name = models.CharField(verbose_name=_('物品名称'), max_length=90) # Many attributes are omitted here serializers.py ` class sellSerializer(serializers.ModelSerializer): class Meta: model = sellGoods fields = '__all__' ` view.py class sellGoodsList(APIView): def post(self, request, format=None): serializer = sellSerializer(data=request.data) qdata = request.data print('1: ',qdata) print('2: ',qdata['img']) print('3: ',qdata.get('img')) print('------------') if serializer.is_valid(): return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) in postman Realize uploading multiple image