Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ERROR: Could not find a version that satisfies the requirement apturl==0.5.2 (from versions: none)--
i try to deploy my application on heroku while the process going on i got a error the error is ERROR: Could not find a version that satisfies the requirement apturl==0.5.2 (from versions: none) ERROR: No matching distribution found for apturl==0.5.2 ! Push rejected, failed to compile Python app. ! Push failed -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> Python app detected -----> No Python version was specified. Using the buildpack default: python-3.10.4 To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes -----> Installing python-3.10.4 -----> Installing pip 21.3.1, setuptools 57.5.0 and wheel 0.37.0 -----> Installing SQLite3 -----> Installing requirements with pip ERROR: Could not find a version that satisfies the requirement apturl==0.5.2 (from versions: none) ERROR: No matching distribution found for apturl==0.5.2 ! Push rejected, failed to compile Python app. ! Push failed plese this is my first app deployment please help how to slove it -
Is it possible get two fields from parent model to one child model using foreign key?
consider the below models, class Country_City(models.Model): country_name = models.CharField(max_length=200) city_name = models.CharField(max_length=200) class Register_user(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE,related_name='country', null=True) city = models.ForeignKey(Country_City,on_delete=models.CASCADE,related_name='city',null=True) is it a right way to use? I want to get two fields from parent model to child model -
Write a program to help the manager to find out the employee of the week [closed]
There is a family consisting of a husband-wife from Stone Age. Every day, the husband goes fishing in the sea and brings a certain number of fishes for food at the end of the day. The mood of the wife i.e.to be happy or sad depends on the number of fishes' husband brings back home. Everyday wife updates record of 'max' and 'min' fishes husband caught. She gets happy only when the husband brings more fishes than 'max' of the all the previous day and gets sad when he brings fewer fishes than 'min' of the all previous day. Write a program to predict the overall happiness of the wife with her husband. Create your own logic to define the "overall" happiness and clearly state your assumptions. Sample Input: 9 10 5 20 20 4 5 2 25 1 Sample Output: You can show output in your own way. But output should represent Happiness. It may be in percentage or count of happiness and sadness. Explanation: As the husband caught less fish than his all past fishing records for 4 days and caught record- breaking fish for 2 days. Hence 4 - 2 = 2 is overall happiness (difference of … -
What is the best approach to use cache in Django?
I have a GET and POST request in a Django APIView. from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status class DemoView(APIView): def get(self, request): user_id = request.query_params.get('user_id', None) num = MyModel.objects.get(id=user_id).num for i in range(num): num = num*i + 1. # In real work, much more complicated. return Response({'success': True, 'square':num}, status=status.HTTP_200_OK) def post(self, request): user_id = request.data.get('user_id', None) num = request.data.get('num', None) num_from_my_model = MyModel.objects.get(id=user_id).num if num == num_from_my_model: MyModel.objects.filter(id=user_id).update(num=num) return Response({'success': True}, status=status.HTTP_200_OK) The problem is in my real work, GET method may need a long time(about 10 seconds) to finish. Here is how I do it: (1) First of all, I create a database MyCache to see if num has changed in POST method. (2) If changed, MyCache will turn the cache_changed parameter to True(default False). (3) In GET method, I will check if cache_changed is True. If True, I will save result into cache. If False, I will get result from cache. from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status from django.utils.decorators import method_decorator from django.views.decorators.cache import cache_page from django.core.cache import cache class DemoView(APIView): @method_decorator(cache_page(60)) def get(self, request): user_id = request.query_params.get('user_id', None) cache_changed = MyCache.objects.get(id=user_id).cache_changed if cache_changed: num … -
How i can handle django nested serializer with django sub nested model
I want to find a more convenient way to handle the Django nested serializer with Django sub-nested models. I have create these two model with override function get_attribute. It's work fine for me but I'm, looking for more convential way to handle this. Two serilizers `class ProductSerializer(serializers.ModelSerializer): def get_attribute(self, instance): if isinstance(instance, Invoice): instance = instance.invoiceitems.all().first().price return super().get_attribute(instance) class Meta: model = Product class InvoiceSerializer(serializers.ModelSerializer): product = ProductSerializer() class Meta: model = Invoice ` from Invoice model i can access Product by reverse ORM method like i use in get_attribute overirde function. e.g: invoice_object.invoiceitems.all().first().price. For now it's working fine for me. But looking for more conventional way. Thank you in advance. -
I Can't Create a Virtual environment For Django
I wanted to create a Virtual Environment for My Django Project But whenever i tried to install pipenv it doesn't work. Please I want to install and create a Virtual environment. -
dateutil.parser parsing the time problem, unable to get the correct time
Using celery to execute tasks asynchronously, the time of the text needs to be parsed in the task. Normally, an error will be reported in the try process during parsing, and then the correct time will be obtained by executing the content of except But the local running process is normal, but the online is wrong, the content under except is not executed online, and the wrong time is obtained. # environment python3.8 ubuntu14 python-dateutil = ">=2.5.2" # imported package from dateutil.parser import parse # parsing time def parse_datetime(msg): try: dt = parse(msg, fuzzy=True) print("dt: ", dt) return dt.strftime('%Y-%m-%d %H:%M:%s') except Exception as e: print(e) ... return time_.strftime('%Y-%m-%d %H:%M:%S') # result of execution time_ = parse_datetime(msg="下午5点53") # dt print result dt :2053-05-25 00:00:00 # type:<class 'datetime.datetime'> # The result is normally an error when formatting, but the online environment does not report an error, and the result is directly obtained The result of local parsing is normal:local run result The online running result is wrong, the code content below the except is not executed, and the wrong result is directly obtained:Online Environmental Results The result of the local python environment test is also wrong:local python -
Django ImageField is not being updated while submiting a form
Issue describrion I have a model which describes a UserProfile and a dedicated form to allow user to update the model. Except photo(ImageField), everything is working fine. Issue with photo field is that the image is not being changed at all with EditProfileForm. In other words I have same image attached to this field before and after form submition, the photo is pointing to the same picture, and nothing new was uploaded to the server. It is worth to be noted that photo field is working through the form from admin panel. No issues with other fields related to UserProfile and User: all of them can be updated, and the update is saved in database. Environment details For a time being I am using Django in version 4.0.3 running with DEBUG=True and build in development server. Code ### Models def get_image_save_path( instance, filename:str ) -> str: save_dir = instance.__class__.__name__ file_name = uuid.uuid4().hex file_extension = pathlib.Path(filename).suffix return f"{save_dir}/{file_name}{file_extension}".lower() def validate_image_size(image): if not image: raise ValidationError("No image found") if image.size > 512*1024: raise ValidationError("Max size is 512kb") class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_profile', primary_key=True) photo = models.ImageField(upload_to=get_image_save_path, verbose_name="Photo", validators=[validate_image_size], default="userprofile/default_photo.jpg", null=False, blank=False) bio = models.TextField(default='', blank=True) def __str__(self): return f"{self.user.username}" @receiver(post_save, … -
Need to generate a client and project code for a client and project in django rest framework
models.py class Client(models.Model): client_name=models.CharField(max_length=30,default=None) client_code = models.CharField(max_length=3, default=None, null=True) company=models.CharField(max_length=200) finance_contact_email=models.EmailField(max_length=25,default=None) business_purpose=models.CharField(max_length=50,null=True,default=None) location=models.CharField(max_length=200) emergency_contact=models.CharField(max_length=200,null=True,default=None) website=models.URLField(max_length=200,null=True) comments=models.TextField(max_length=300,null=True, blank=True) start_Date = models.DateTimeField(max_length=10,null=True) end_Date=models.DateField(max_length=10,null=True) class Meta: db_table ='Client' def __str__(self): return '{}'.format(self.client_name) #Project model class Project(models.Model): project_code = models.CharField(primary_key=False, editable=False, max_length=10,default=None,null=True) #client_project_code = models.CharField(primary_key=False, editable=False, max_length=10,default=None,null=True) project_name = models.CharField(max_length=30,unique=True,default=None) client_code = models.ForeignKey(Client,on_delete=CASCADE,related_name="Client5",default=None, null=True) # need to get the client code instead of name but the name should be returned in client model client= models.ForeignKey(Client,on_delete=CASCADE,related_name="Client1",default=None) user=models.ManyToManyField(User,related_name='users',default=None) description=models.TextField() type=models.TextField() #dropdown start_date = models.DateTimeField(max_length=10) end_date=models.DateTimeField(max_length=10) technical_contact_name = models.CharField(max_length=30) email=models.EmailField(max_length=254,default=None) phone = PhoneField(blank=True) delivery_head_contact_name=models.CharField(max_length=30) class Meta: db_table ='Project' def save(self, **kwargs): if not self.id: max = Project.objects.aggregate(id_max=Max('project_code'))['id_max'] self.project_code = "{}{:03d}".format('', max if max is not None else 1) super().save(*kwargs) def __str__(self): return '{}'.format(str(self.client_code), str(self.project_code)) As per the above code I created a client code in client model and I need to combine the client code plus the project code which is auto generated in the project code field itself or in a new field. for ex: client code: ICN and project code: ICN001. And one main thing is i want the client name to be returned in the client model and i need to link the client code from the client model to the project, I was … -
(1062, "Duplicate entry '' for key 'email'") and (1062, "Duplicate entry '' for key 'phone'") in Django
I am trying to implement Sign Up page in Django using User models. In HTML page, there is an input field for email or phone number. The value I got from this field is assigned to username in Django User model and if the entered value is email, then the value is assigned to email in the User model. Otherwise value assigned to the phone in the User model. When I run the server, user can enter his details with email once. For the second time onwards, I got an error like this: IntegrityError at /Accounts/CandidateRegister/ (1062, "Duplicate entry '' for key 'phone'") Request Method: POST Request URL: http://127.0.0.1:8000/Accounts/CandidateRegister/ Django Version: 4.0.2 Exception Type: IntegrityError Exception Value: (1062, "Duplicate entry '' for key 'phone'") Exception Location: C:\job\venv\lib\site-packages\MySQLdb\connections.py, line 254, in query Python Executable: C:\job\venv\Scripts\python.exe Python Version: 3.9.7 Python Path: ['C:\\job\\jobsite', 'C:\\Users\\Student\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\Student\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\Student\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\Student\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\job\\venv', 'C:\\job\\venv\\lib\\site-packages'] Similarly, when a user enter with his phone number, their details will saved to database once. After that I got an error like this: IntegrityError at /Accounts/CandidateRegister/ (1062, "Duplicate entry '' for key 'email'") Request Method: POST Request URL: http://127.0.0.1:8000/Accounts/CandidateRegister/ Django Version: 4.0.2 Exception Type: IntegrityError Exception Value: (1062, "Duplicate entry '' for key … -
Django Submitting two forms depending on each other with single submit button
I'm building a django app for managing orders. I have divided the orders management into two separated tables as follows: Order: Fields include customer (Foreign Key), order_date, total_order_value and order_status. OrderLine: Fields include item (Foreign Key), quantity, discount, total, order_id (Foreign Key). I am trying to do the template for the order page such as below. <div class="row mb-2 mt-2" style="text-align: center;"> <div class="col-2"> <input type=button value="Back" class="btn btn-secondary" onClick="javascript:history.go(-1);"> </div> <div class="col-9"></div> </div> <form method="POST" action="" enctype="multipart/form-data" id= "test"> {% csrf_token %} <form id="order" action="" method="POST" enctype="multipart/form-data"></form> <form id="orderLine" action="" method="POST" enctype="multipart/form-data"></form> <div class="card"> <div class="card-header" style="text-align: center;"><h1> Order Details </h1></div> <div class="card-body"> <div class="card-text"> <div class="row"> <div class="col-md-6"> <label for="id" class="form-label">Order ID</label> <input type="text" class="form-control" id="id" value="{{order.id}}" readonly> </div> <div class="col-6"> <label for="order_date" class="form-label">Order Date</label> {{orderForm.order_date}} </div> <div class="col-6"> <label for="customer" class="form-label">Customer Name</label> {{orderForm.customer}} </div> <div class="col-6"> <label for="status" class="form-label">Order Status</label> {{orderForm.status}} </div> </div> </div> </div> </div> <div class="row"> <br> </div> <div class="card"> <div class="card-body"> <div class="card-text"> <table class="table table-hover"> <thead> <tr> <th scope="col">Item</th> <th scope="col">Unit Price</th> <th scope="col">Quantity</th> <th scope="col">Discount</th> <th scope="col">Total</th> </tr> </thead> {{ orderLineForm.management_form }} <tbody> {% for orderLine in orderLineForm %} <tr class="orderline"> <th>{{orderLine.item}}</th> <td>0</td> <td>{{orderLine.qty}}</td> <td class="omr" id="disc">{{orderLine.disc}}</td> <td class="omr" id="total">{{orderLine.total_price}}</td> </tr> {% … -
Put the user name in change_reason when deleting with SafeDeleteModel
I am using django-simple-history and SafeDeleteModel I override the save()and store the updater name in _change_reason. then When deleting, I want to put the deleter name in _change_reason However it doesn't works. How can I make it? class BaseModel(AuditableModel, SafeDeleteModel): _safedelete_policy = SOFT_DELETE_CASCADE objects = DeletedInvisiableManager() class Meta: abstract = True def save(self, operator: str = None, **kwargs): self._change_reason = operator return super().save(**kwargs) def delete(self,operator: str = None,**kwargs): self._change_reason = operator return super().delete(**kwargs) -
Show particular records at the bottom in webpage
I have drf website where i am showing the records of some sought on my website i have 4 different type of statuses on my webpage for records how do i show a particular status records related to the records at the bottom. class MyListView(APIView): -
How to get the many to one relatiodata on DRF
How can I get the information which has a relationship with another modal class For eg. class UserSensorDevice(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) sensor_type = models.ForeignKey( 'core.Component', on_delete=models.CASCADE ) sensor_code = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.pseudonym And I have another modal class: class ReplacedSensorDevice(models.Model): sensor_type = models.ForeignKey( 'core.Component', on_delete=models.CASCADE ) replaced_for = models.ForeignKey( 'UserSensorDevice', on_delete=models.CASCADE, null=True ) sensor_code = models.CharField(max_length=255, unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) When I will call UserSensorSerializer then if replacement is available then I need to get that information as well. I am not able to figure it out how can I get that views.py class UsersSensorDeviceView(generics.ListAPIView): permission_classes = (permissions.IsAuthenticated, jwtPermissions.IsOwner,) queryset = sensorModels.UserSensorDevice.objects.all() pagination_class = pagination.PostLimitOffsetPagination filter_backends = (DjangoFilterBackend,OrderingFilter,SearchFilter) filter_fields = ('user','id','sensor_type',) serializer_class = serializers.UserSensorDeviceSerializer serializers.py class UserSensorDeviceSerializer(serializers.ModelSerializer): sensor_name = serializers.CharField(source='sensor_type.comp_code', read_only=True) class Meta: model = sensorModels.UserSensorDevice fields = '__all__' read_only_fields = ['id','created_at'] Any suggestion will be of great help. -
Is it possible to pass the foreign key id in Django rest-framework URL?
I am using routers in Django Rest Framework and trying to create a dynamic URL based on a foreign key. My urls.py file looks like this, router = routers.DefaultRouter() router.register('user/<int:user_id>/profile', IntensityClassViewSet, 'intensity_classes') urlpatterns = router.urls My models.py file looks like below, class Profile(models.Model): user = models.ForeignKey( User, related_name='profile_user', on_delete=models.CASCADE) character = models.CharField(max_length=10, null=True, blank=True) My views.py file looks like below, class ProfileViewSet(viewsets.ModelViewSet): queryset = Profile.objects.all() serializer_class = ProfileSerializer I am getting the 404 error in all (post, put, get) request. Is there any possible easy solution for such kind of implementation? -
How to create own storage for COS in Django
ValueError: Cannot serialize: <desert.storage.TencentStorage object at 0x104fcc580> There are some values Django cannot serialize into migration files. For more, see https://docs.djangoproject.com/en/4.0/topics/migrations/#migration-serializing I want to link the FileField in Django to my COS so that I can upload file from admin site to COS. Here is my code: secret_id = settings.COS_SECRET_ID secret_key = settings.COS_SECRET_KEY region = settings.REGION bucket = settings.BUCKET config = CosConfig(Region=region, Secret_id=secret_id, Secret_key=secret_key) client = CosS3Client(config) host = 'https://' + bucket + '.cos.' + region + '.myqcloud.com/' class TencentStorage(Storage): def save(self, name, content, max_length=None): filename = self.generate_filename(name) client.put_object( Bucket=bucket, Key='song/' + filename, Body=content.read() ) return filename def generate_filename(self, filename): return filename + '_' + sha1(str(time.time()).encode('utf-8')).hexdigest() def url(self, name): file_url = client.get_object_url(bucket, 'song/' + name) return str(file_url) But after I fill this storage into model like this and use the make migration command: song_file = models.FileField(storage=TencentStorage(), null=True) It raised an error: ValueError: Cannot serialize: <desert.storage.TencentStorage object at 0x104fcc580> There are some values Django cannot serialize into migration files. For more, see https://docs.djangoproject.com/en/4.0/topics/migrations/#migration-serializing How to solve this. -
Implementing Django Bootstrap crispy forms into default signup / login pages?
I've set up user account signup and login pages following this tutorial and it all works great, except the pages have no formatting. I'm now looking for a simple drop in solution to improve the appearance of "templates/registration/login.html" and "templates/registration/signup.html". Someone recommended crispy forms which look great, and as the rest of my site uses Bootstrap 5, crispy-bootstrap5 looks ideal. I'm struggling to implement crispy-bootstrap5 as I don't understand Django's inbuilt django.contrib.auth.forms nor forms in general, and can't find simple reproducible examples for crispy forms with signup.html and login.html. I've installed packages fine, but now don't know how to beautify login.html and signup.html from that tutorial: {% extends 'base.html' %} {% block title %}Sign Up{% endblock %} {% block content %} <h2>Sign up</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign Up</button> </form> {% endblock %} I don't know where to go with this, but the docs for regular django-crispy links to a gist for an eg form, and the index.html {% load crispy_forms_tags %} and {% crispy form %}. I've put them in which mostly left the page unchanged except for messing up the formatting. I think I now need to modify class CustomUserCreationForm(UserCreationForm) in forms.py but … -
DRF: How to pass extra context data to serializers
I was searching the net and found the similar problem but it doesn't work in my case, Idk why. I try to put some extra data to context in serializer, but get only 3 default fields: request, view and format and no mention for my custom data. My model: class Match(models.Model): sender = models.ForeignKey( Client, on_delete=models.CASCADE, related_name='senders' ) recipient = models.ForeignKey( Client, on_delete=models.CASCADE, related_name='recipients' ) class Meta: app_label = 'clients' db_table = 'matches' verbose_name = 'match' verbose_name_plural = 'matches' constraints = [ models.UniqueConstraint( fields=['sender', 'recipient'], name='unique_match' ) ] My Serializer: class MatchSerializer(serializers.ModelSerializer): sender = serializers.HiddenField(default=serializers.CurrentUserDefault()) def validate(self, data): if data['sender'] == self.context['recipient']: raise serializers.ValidationError('You cannot match yourself') return data def create(self, validated_data): return Match.objects.create( sender=validated_data['sender'], recipient=self.context['recipient'] ) class Meta: model = Match fields = ['sender']` My ModelViewSet: class MatchMVS(ModelViewSet): queryset = Match.objects.all() serializer_class = MatchSerializer http_method_names = ['post'] permission_classes = [IsAuthenticated] # without and with doesn't work def get_serializer_context(self): context = super(MatchMVS, self).get_serializer_context() context.update({ "recipient": Client.objects.get(pk=23) # extra data }) return context @action(detail=True, methods=['POST'], name='send_your_match') def match(self, request, pk=None): sender = request.user recipient = Client.objects.get(pk=pk) serializer = MatchSerializer(context={'request': request, 'recipient': recipient}, data=request.data) data_valid = serializer.is_valid(raise_exception=True) if data_valid: recipient = serializer.save() is_match = Match.objects.filter(sender=recipient, recipient=sender).exists() if is_match: send_mail( f'Hello, {sender.first_name}', f'You … -
Adding uploaded text file to textbox field - Django
I am pretty new to Django and still learning, but I am having a hard time trying to figure out how to let a user upload a .txt file but instead have the uploaded .txt file overwrite in the textfield itself. Example: When uploaded https://imgur.com/a/jdCjlVS I haven't been able to find understandable resources, but this is all I have at the moment: forms.py class NewInput(forms.Form): text = forms.CharField(label='Input', max_length=1000, required=False) file = forms.FileField(required=False) models.py class Collection(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="collection", null=True) text = models.TextField(max_length=1000, default='') create.html {% extends 'main/base.html' %} {% load crispy_forms_tags %} {% block title %} New Input {% endblock %} {% block content %} <center> <h3>Create a New Input:</h3> <p class="text-primary"></p> <form method = "post" action = "/create/" class="form-group" enctype="multipart/form-data"> {% csrf_token %} {{form|crispy}} <div class="input-group mb-3"> <div class="col text-center"> <button type="submit" name="save" class="btn btn-success">Create</button> </div> </div> </form> </center> {% endblock %} views.py def create(response): if response.user.is_authenticated: username = response.user.username if response.method == "POST": form = NewInput(response.POST) if form.is_valid(): n = form.cleaned_data["text"] t = Collection(text=n) t.save() response.user.collection.add(t) return HttpResponseRedirect("/collections/%s" % username) else: form = NewInput() return render(response, "main/create.html", {"form": form}) else: return HttpResponseRedirect("/login") I tried adding a separate class as a form field but I was … -
Get "Foo" queryset of ForeignKey relationships for initial "Bar" queryset?
I have a simple ForeignKey relationship: class Foo(models.Model): id = UUIDField() class Bar(models.Model): id = UUIDField() foo = ForeignKey(foo) If I have an initial queryset of Bar objects, how can I get a queryset of related Foo object for each respective Bar? I'm currently doing this but I'm wondering if there's a better way: bar_qs = Bar.objects.all().select_related("foo") foo_ids = [] for i in bar_qs: foo_ids.append(i.foo.id) foo_qs = Foo.objects.filter(id__in=foo_ids) -
Why does assigning value to Django Object change the value from NoneType to Tuple?
I am polling an API and I am returned a dictionary. I take this dictionary and attempt to take the data from it and assign it to a new django object: def write_object(account, data): #account is a Django object #data is a dictionary from an API if Obj.objects.filter(account=account, pk=data['id']).exists() == False: #create new Obj.objects.create(account=account, pk=data['id']) #object already exists, fetch relevant application object obj = Obj.objects.get(account=account, pk=data['id']) #assign the values from data to the object obj.name = data['name'], obj.notes = data['notes'], obj.status = data['status'], obj.created_at = iso8601_to_datetime(data['created_at']) This all works fine: print(type(data)) -> <class 'dict'> print(data['notes']) -> None print(type(data['notes'])) -> <class 'NoneType'> print(obj.notes) -> (None,) print(type(job.notes)) -> <class 'tuple'> print(data['opened_at']) -> 2022-02-28T15:23:11.000Z print(obj.opened_at) -> datetime.datetime(2022, 2, 28, 15, 23, 11, tzinfo=),) print(type(obj.opened_at)) -> <class 'tuple'> My question is: How do the data types become tuples when I assign it to the object? -
Error While Deploying Django Application on Heroku
I have been following a tutorial to deploy my application on Heroku, however, when I try running the application it gives me an error. I was not able to understand the logs properly from Heroku nor find any information over the internet. This is the error that I get when I run the application: The error image Hope somebody can answer this or at least let me know where within django project I can find this error. As I need some sort of leads towards this issue. Do let me know if you require further information from me. Thanks -
Django project How to change an object from for loop (its a JSON response) to readable by Java-Script
I would like to make easy math in my currency Django project but I got response in google chrome inspect that one object (that which comes from API JSON response) is undefined but second is a String When I change code a little bit to this below I got response in console inspect And I can see clearly this object is there but I can't get it out of class .value console.log(amount1, amount2); <p id="crypto-price">3289.00221916 </p> <option id="user-wallet">15000 </option> static/js/javascript.js const amount1 = document.getElementById("crypto-price"); const amount2 = document.getElementById("user-wallet"); function calculate() { console.log("YESS"); **console.log(parseInt(amount1.value) * parseInt(amount2.value));** console.log(typeof amount1.value, typeof amount2.value); } calculate(); YESS javascripts.js:13 NaN javascripts.js:14 undefined string Django templates where are both objects "crypto-price" "user-wallet" comes from the for loop {% extends "web/layout.html" %} {% block body %} <div class="row"> {% for crypto_detail in crypto_detail_view %} <div class="col-lg-12 col-md-6 mb-4"> <div class="card h-100"> <div class="card-body"> <img class="rounded mx-auto d-block" src="{{crypto_detail.logo_url}}" width="50" height="50"> <h4 class="card-title text-center" id="crypto-name">{{ crypto_detail.name }} </h4> </div> <div class="card-footer text-center"> <p id="crypto-price" >{{crypto_detail.price}} </p> <p>{{fiat_currency}}</p> </div> <div class="card-footer text-center" > <p href="">Price Date: {{ crypto_detail.price_date }}</p> </div> </div> </div> {% endfor %} <div class="row g-3 align-items-center"> <p>Your Money:</p> <select class="form-select" aria-label="Default select example"> <option selected>which currency do … -
How to a calender with Django that will highlight seven days from the user's input
Hi I need your help guys I'd like to make an app in Django to take a date from the user then replay with the next seven dates, those seven days will be shown as highlighted dates on the calendar on the web page and the same on a mobile app, and I a don't know how can I do it. PS. I'm working with the rest framework -
OSError: [Errno 24] Too many open files when uploading 9000+ csv files through Django admin
I've been struggling to upload csv files containing data to populate the database of my Django project. I am serving my project using Django 3.1 and Gunicorn if that is important. I've referred to multiple stack overflow posts regarding the same issue, but none of them have resolved this problem. Just to list out the steps I've taken to solve this problem: Ran ulimit -n 50000 in terminal to increase the max number of files that can be opened as suggested by this post. Used ulimit -n to find the max number of files that can be opened and changed the configurations of this limit in the limits.conf file, as suggested by this post, to changed the system limits. I confirmed it was changed by running ulimit -a I believed it might be a memory issue and that Linux was limiting the max amount of space available on the heap so I changhed the configuration for that as well. Fortunately, it was not a memory issue since RAM usage appeared to be extremely stable according to my control panel Here is the code related to my issue: admin.py class CsvImportForm(forms.Form): csv_upload = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) @admin.register(dummyClass) class dummyClassAdmin(admin.ModelAdmin): search_fields = search …