Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I start the creation of a Django foreign key model instance from the parent form?
I created the following two Django models: class Partner(models.Model): name = models.CharField( max_length = 100, null = False ) zip_code = models.CharField( max_length = 10, null = False ) class Meta: verbose_name_plural = "Partners" def __str__(self): return self.name class Screen(models.Model): name = models.CharField( max_length = 100, null = False ) position = models.CharField( max_length = 100, help_text = "Google Pluscode", null = False ) partner = models.ForeignKey( Partner, on_delete = models.PROTECT, null = False ) class Meta: verbose_name_plural = "Screens" def __str__(self): return self.name When I add a new instance of a screen, I would like to be able to click on a button inside the form and add a new instance of a partner (if it does not exist yet). After the creation of the foreign key instance, it should return to the original form. It is the same mechanism as in the the admin site when you add a new instance of a model (see image below) but I don't know how to implement it. Admin site model creation I have already looked up inline forms but this is not really the mechanism I want to use. I want to have a new HTML-Page or a modal for … -
how to create a post api in django if sample post request and response is already given
How to create a post rest api in django if sample request and sample response is given? Can't understand from where to begin. -
Django not showing dynamic list content
I am making a website where I show off the specs of each product using flip cards and I have django is as the backend. I was trying to make the specs dynamic using jinja format but everytime I try to put my multiple objects in list it messes the code up. views.py before def prodospecs(request): product1 = product() product1.name = 'iPhone 12 Pro 5G' product1.screen = '6.1" Super Amoled Display 60hz' product1.chipset = 'A14' product1.camera = 'Triple Camera Setup (UltraWide, Telephoto, Wide)' product1.special = 'New Design' product1.price = 999 product2 = product() product2.name = 'S21 Ultra 5G' product2.screen = '6.8" Amoled Display 120hz' product2.chipset = 'Snapdragon 888, Exynos 2100' product2.camera = 'Quad Camera Setup (UltraWide, 2 Telephoto, Wide)' product2.special = 'New Camera Design and S-Pen Support' product2.price = 1199 product3 = product() product3.name = 'Asus Zenbook Duo' product3.screen = '14 inch 16:9' product3.chipset = 'i5 or i7' product3.camera = '720p Webcam' product3.special = 'Two Displays' product3.price = 999 return render(request, 'prodospecs.html', {'product1' : product1,'product2' : product2, 'product3' : product3 }) And this one works and shows all the information necessary views.py after def prodospecs(request): product1 = product() product1.name = 'iPhone 12 Pro 5G' product1.screen = '6.1" Super Amoled Display … -
How do I show specific field in foreign key model, in Django+React app?
so I have a Django+React app, and having trouble with something. Obviously, I've created REST API with Django and fetching it with React. Let me show you the code first. models.py (Django) class Category(models.Model): category_name = models.CharField(max_length = 20) class Content(models.Model): category = models.ManyToManyField(Category) key_line = models.CharField(max_length = 100, null=True) body = models.TextField(blank=True, null=True) views.py (Django) @api_view(['GET']) def book_list(request): books = Content.objects.all() serialized = ContentsSerializer(books, many=True) return Response(serialized.data) React component class Books extends Component { constructor(props){ super(props); this.state = { } } componentDidMount() { this._getBookList(); } _renderBookList = () => { const books = this.state.bookList_object.map((this_book, index) => { return <BakeList key_line={this_book.key_line} body={this_book.body} category={this_book.category} /> }) return books } _getBookList = async () => { const book = await this._callApiBookList(); this.setState({ bookList_object : book }) } _callApiBookList = () => { return fetch("https://api.book.shop/api/books/") .then((response) => response.json()) .catch((err) => console.log(err)) } render() { return( <div>this._renderBookList()</div> ) } BookList.js class CakeList extends Component { constructor(props) { super(props); this.state = { page : 'home' } } render() { return ( <div>{this.props.key_line}</div> <div>{this.props.body}</div> <div>{this.props.category}</div> ) } Now the problem is in the {this.props.category} line in BookList.js component. What I want to get in the screen is category_name, but what I get is id. How do … -
django - No return after call from another serializer
users/models.py class GolferPhotoViewSet( mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, mixins.ListModelMixin, GenericViewSet,): queryset = GolferPhoto.objects.all() serializer_class = GolferPhotoSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, GolferPhotoPermission) def get_queryset(self): data = self.kwargs if data.get("golfer_profile_pk"): if data.get("pk"): if self.request.query_params.get("photo_nickname"): image_value = self.request.query_params.get("photo_nickname") user = self.request.user.id user_value = "GOLFER" + str(user) return FileInfo.objects.get( reference_value=user_value, image_nickname=image_value ) obj = GolferPhoto.objects.get(id=self.kwargs["pk"]) self.check_object_permissions(self.request, obj) return self.queryset.filter(pk=self.kwargs["pk"]) ... http://127.0.0.1:8000/golfer-profile/1/golfer-photos/3?photo_nickname=MAIN I'd like to return one object from a model called [Fileinfo], but it says [{"detail":"Not Found"} in postman. instance = FileInfo.objects.get( reference_value=user_value, image_nickname=image_value ) serializer = FileInfoSerializer(instance) return Response(serializer.data) Even if I put it in the serializer, it doesn't work out the way I want it to, what should I do? -
How to properly show image stored from a file server to a django HTML template?
I have trouble displaying images stored in a file server to the django template. File server link is \11234.123.123.123\dashboard.jpg (just a sample). It seems like the img src url is being added by the django localhost url prefix to the file server path as follows: http://127.0.0.1:8000/dashboard/\\11234.123.123.123\dashboard.jpg In django template, the img tag is written as: <img class="imgView" src="{{dashboard_image}}" alt="Dashboard画面.jpg"></img> My views.py just sends the image file server URL as text (with value of \11234.123.123.123\dashboard.jpg) to be displayed as image in the HTML page as the django template. But, the image does not show properly as follows. Please help, thank you! -
How can I retrieve form data out of request.POST in Django
I want to get a form data sent through request.POST. The data is in a form of dictionaries inside a list. Here is the html form and ajax request: <form class="passwordUpdateForm" novalidate="" name="passwordUpdate" action="" method="" id="passwordUpdateForm"> {% csrf_token %} <div class="md-form md-outline mb-3"> <label data-error="wrong" data-success="right" for="oldPass">current password </label> <input type="password" id="oldPass" class="form-control" name="oldPassword" placeholder="*********" value=""> </div> <div class="md-form md-outline mb-3"> <label data-error="wrong" data-success="right" for="newPass">new password </label> <input type="password" id="newPass" class="form-control" name="newPassword" placeholder="*********" value=""> </div> <div class="md-form md-outline mb-5"> <label data-error="wrong" data-success="right" for="newPassConfirm">confirm new password </label> <input type="password" id="newPassConfirm" class="form-control" name="newPasswordConfirm" placeholder="*********" value=""> </div> <button type="submit" class="btn btn-primary mb-4"> change password </button> </form> <!-- to change user password --> <script type="text/javascript"> $('#passwordUpdateForm').on('submit', function(event) { event.preventDefault(); // to get form data var formData = $(this).serializeArray(); var formData = JSON.stringify(formData); alert(formData); // submit ajax request $.ajax({ type: "POST", url: "{% url 'passwordReset' %}", dataType: "json", contentType: false, processData: false, data: { 'form_data': formData, csrfmiddlewaretoken: '{{csrf_token}}', }, success: function(data) { data = JSON.parse(data); var message = $('#flashMessage').html(''); message.append('<div class="alert alert-warning alert-dismissible fade show" role="alert">'+'<strong>'+'sorry {{first_name}} </strong>'+ data +'<button type="button" class="close" data-dismiss="alert" aria-label="Close">'+'<span aria-hidden="true">&times;</span>'+'</button></div>'); } }); }); </script> The backend view function is as follow: def passwordReset(request): # process form data if request.method == … -
accessing a json dictionary of an object from list of objects
I am new to django and I am working on project where I am storing a key value pair dictionary as JSON in database. Now later I want to show it on the html page all the list of packages but not able to access those key value pair as dictionary. here is my models.py class Packages(models.Model): package_ID = models.AutoField("Package ID", primary_key=True) package_Name = models.CharField("Package Name", max_length=30, null=False) attribute_values = models.CharField("Item Details JSON", max_length=500, null=False) package_Price = models.IntegerField("Package Price", null=False, default=0.00) quantity = models.IntegerField("Quantity", null=False, default=00) prod_ID = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name="Product ID (FK)") its data entry is something like this package_ID = 1 package_Name = "basic card" attribute_values = {"sizes": "8.5 in. x 11 in.", "Colour": "Full-Color Front - Unprinted Back",} package_Price = 200 quantity = 400 prod_ID = 1 package_ID = 2 package_Name = "best card" attribute_values = {"sizes": "8.5 in. x 11 in.", "Colour": "Full-Color Front - Unprinted Back",} package_Price = 200 quantity = 500 prod_ID = 1 here the problem is that attribute_values fields stores a JSON string so I have to convert it in dictionary first and then have to access its dictionary. the steps I want to do: get all the packages having same product … -
Django tag like input for a ManyToMany field in a model
Currently, I have an issue where within my model I have two ManyToMany fields that basically need to act like tags. I either need my data to go from my HTML to my view so I can populate it in the view function, or just have it work with some special form type. class MyModel(models.Model): ... skills = models.ManyToManyField(Skill) interests = models.ManyToManyField(Interest) Where Skill and Interest are classes as follows class Skill(models.Model): SKILLS = ( ('0','Skill 1'), ('1', 'Skill 2'), ) name = models.CharField(max_length=50, choices=SKILLS) def __str__(self): return self.name Currently, my form does not pass in the skill or interest and I can get it to populate off checkboxes. But would like to make it a taggable sort of entry used in Bootstrap: http://bootstrap-tagsinput.github.io/bootstrap-tagsinput/examples/. Any advice is greatly appreciated. Thank you. -
Like post button django
I found a ready-made solution that was not written by me. It worked, but I don't understand why. Can someone explain to me how this works? Especially not clear what is the role of "value" and "name" in form ? html <form action="{% url 'likes_post' post.pk %}" method="POST"> {% csrf_token %} <p> <button class="btn btn-success" type="submit" value="{{post.id}}" name="post_id" >likes: {{post.total_likes}} </button> </p> </form> views def likes_post(request, pk): post_for_like = get_object_or_404(Article, id=request.POST.get('post_id')) post_for_like.likes.add(request.user.profile) return HttpResponseRedirect(reverse('artical_page', args=[str(pk)])) urls path('like/<int:pk>/', views.likes_post, name='likes_post'), -
How can i display only organization groups in django admin add form?
Sorry for this type of question. I am new to django I have a situation where an organization has its own groups list and Group and organization has many to many fields relationship. Now once i try to add user from admin site, i can see all the groups from database, But it should only display the group list available thought the organization. For instance, Organization A has employee, organization admin group and Organization B has test group. But ADD form display all group list. I want display only test group as i logged in a user of Organization B So how can i implement this? Here is my Group Model extension: Group.add_to_class('organization',models.ManyToManyField(Organization,related_name='groups',blank=True)) enter image description here -
Django, Vue - How to pass prop from Django to Vue
Background Hello All, trying to build a 'retrospective app' using Django & VUE. I have already created login, and dashboard which displays list of 'boards' created by logged in user. A board is a table of topics anyone with link can add and log-in not required. Problem When I click on board, it is showing all the topics in DB, How can I pass 'PK' of board from Vue CDN to Django DRF to get filtered results. Env: Django, VUE.js, Django Rest Frame Work Please note: Very new to Django & VUE this is my first project ever in my life, learning for the past 8months, please go easy on me. Below is the Board.html, with Vue CDN. {% load static %} {% block content %} <div id="app"> <div class="container"> <form @submit.prevent="submitForm"> <div class="form-group row"> <input type="text" class="form-control col-3 mx-2" placeholder="Todo" v-model="retroboard.todo"> <input type="text" class="form-control col-3 mx-2" placeholder="inprogress" v-model="retroboard.inprogress"> <input type="text" class="form-control col-3 mx-2" placeholder="Action Items" v-model="retroboard.done"> <button class="btn btn-success">Submit</button> </div> </form> <!-- <div> <form method="POST"> {% csrf_token %} {{form.todo}} {{form.inprogress}} {{form.done}} <button class="btn btn-primary">Add</button> </form> </div> --> <table class="table"> <thead> <th>Todo</th> <th>InProgress</th> <th>Done</th> </thead> <tbody> <tr v-for="board in retroboards" :key="board.id" @dblclick="$data.retroboard = board"> <td>[[ board.todo ]] <a href=" "> … -
How do I press on the "save" button of a print pop up with selenium?
I'm trying to get selenium to press on the save button of the print pop up to save a pdf file. I can get selenium to press on the "print" button but once the pop up appears with the adress chrome://print/ nothing happens. Is there another way to do it? This is the part's code so far: #download pdf download_button = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="printpagetoolbar"]/tbody/tr/td[3]/table/tbody/tr/td/a'))) download_button.click() # download file: Nothing happens, this doesn't work download = wait.until(EC.element_to_be_clickable(By.XPATH, '//*[@id="sidebar"]//print-preview-button-strip//div/cr-button[1]')) download.click() This is the image of the pop up window: -
Django debug toolbar issue
In versions of the module higher than 2.2, the panel does not appear by starting the server through python manage.py runserver What could be the problem? -
I want to deploy a Django app on Heroku, but I got error
I want to deploy a Django app on Heroku. The development environment is wsl (debian), python3.9.0, and the virtual environment is "venv". I referred here: https://tutorial-extensions.djangogirls.org/ja/heroku/ It was completed before this code: git push heroku master Run git push heroku master, then I got the following error: (env) me@Ver:~/docker_heroku/djangogirls210307$ git push heroku master Enumerating objects: 78, done. Counting objects: 100% (78/78), done. Delta compression using up to 4 threads Compressing objects: 100% (64/64), done. Writing objects: 100% (78/78), 25.08 KiB | 885.00 KiB/s, done. Total 78 (delta 18), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: ! No default language could be detected for this app. remote: HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically. remote: See https://devcenter.heroku.com/articles/buildpacks remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: ad15f239126a3588a2ab6585b0ae52bfa25d9b7e remote: ! remote: ! We have detected that you have triggered a build from source code with version ad15f239126a3588a2ab6585b0ae52bfa25d9b7e remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch. … -
Different fieldset for Django admin inline if it's an "extra" form
I think an example is the best way to describe the problem... In Django 2.2, suppose you have a model Foo, and a model Bar that has a foreign key to Foo. Now suppose you set up the Django admin so that Bar instances appear as inlines in the Foo changeview: class BarAdmin(admin.StackedInline): model = Bar extra = 1 class FooAdmin(admin.ModelAdmin): model = Foo inlines = [BarAdmin] Finally, suppose we're looking at the changeview form for an already saved Foo instance called foo1. On that form you'll see inline forms for all existing Bar instances that point to foo1 along with an extra inline form that you can use to create a new Bar instance if you want to. What I'm trying to do is make the fieldsets be slightly different depending on whether the inline form represents a Bar instance that has already been saved or whether it is the "extra" form that does not represent an existing Bar instance. Specifically, a saved Bar should have an additional field that an unsaved, "extra" Bar should not. I've been experimenting with the InlineModelAdmin's "get_fieldsets()" method, but I have not found any way to tell from inside that method whether we're … -
django doesn't create table for custom user (postgresql)
!!NOTE: I have renamed User as MPUser and changed the code accordingly, so the issue isn't that the model is named User. I have a database called users_cc that is supposed to contain the users for the web app. When I try to register a test user, I get this response : django.db.utils.OperationalError: no such table: users_user I’ve made a custom User by inheriting AbstractUser: class User(AbstractUser): class ActivityLevel(models.TextChoices): SED = "sed", _("Sedentary") MOD = "mod", _("Moderate") High = "high", _("High") VHigh = "vhigh", _("Very High") class Gender(models.TextChoices): FE = "fe", _("Female") MA = "ma", _("Male") class Meta: app_label = 'users' managed = True bio = models.TextField(max_length=500, blank=True) # image = models.ImageField(default="", upload_to="profile_pics") weight = models.FloatField(validators = [MinValueValidator(1.0)], default=65.) #metric tbd goal_weight = models.FloatField(validators = [MinValueValidator(1.0)], default=65.) height = models.FloatField(validators = [MinValueValidator(1.0)], default=165.) #in cm activity_level = models.CharField( max_length=5, choices = ActivityLevel.choices, default = ActivityLevel.SED, ) gender = models.CharField( max_length=2, choices = Gender.choices, default = Gender.FE ) I have tried to add managed = True for the migration to create a new table. But it doesn’t! In fact, the SQL query doesn’t contain a CREATE TABLE command and I can’t figure out why. In admin.py: admin.site.register(User, UserAdmin) In Settings: AUTH_USER_MODEL … -
Creating a Python Request Equivalent in Google Script
I'm trying to upload a video url to Vimeo in Google Script. I've set this up successfully in my Python/Django app with the following: url = 'https://api.vimeo.com/me/videos' headers = {'Authorization': 'bearer xxx', 'Content-Type': 'application/json', 'Accept': 'application/vnd.vimeo.*+json;version=3.4'} data = {'upload': {'approach': 'pull', 'link': 'https://video.mp4'}} requests.post(url, headers=headers, data=json.dumps(data)) I tried to create the equivalent to the best of my knowledge in Google Scripts as follows: var url = 'https://api.vimeo.com/me/videos' var headers = { 'Authorization': 'bearer xxx', 'Content-Type' : 'application/json', 'Accept' : 'application/vnd.vimeo.*+json;version=3.4'} var data = {'upload' :{ 'approach' : 'pull','link' : 'https://video.mp4'}} var options = { headers:headers, data:data, } var response = UrlFetchApp.fetch(url,options) I get a successful response, but it seems that I'm getting a list of existing videos on my account and no video is uploaded. Could anyone provide any insight into how I could reconfigure my Google Script set up. Thank you! -
Django inspectdb omitted integer primary key
I have a legacy MySQL db, and I am trying to create Django models from it so I can use the legacy tables in my Django application. I ran inspectdb on the MySQL db and it seemed to import most fields correctly, but failed to import every single primary key and/or id field. Is this the expected behavior? I will admit I'm new to Django but I find it odd that Django wouldn't use a primary key/id in the same way as SQL. The legacy db holds 17 tables, but I'm only showing one since the behavior was the same for all. Thanks for any insight you might have! Legacy MySQL table "client" CREATE TABLE `client` ( `id` INT(10) NOT NULL AUTO_INCREMENT, `name` VARCHAR(50) NULL DEFAULT NULL COLLATE 'latin1_swedish_ci', `address` VARCHAR(128) NULL DEFAULT NULL COLLATE 'latin1_swedish_ci', `manager_id` INT(10) NULL DEFAULT NULL COMMENT 'User_id of primary contact of client', `company_id` INT(10) NULL DEFAULT NULL, `facility_id` INT(10) NULL DEFAULT NULL COMMENT 'Likely needs to change to list of facilities (if one client uses multiple facilities within a company)', PRIMARY KEY (`id`) USING BTREE, INDEX `FK_facility_client` (`facility_id`) USING BTREE, INDEX `FK_user_client` (`manager_id`) USING BTREE, CONSTRAINT `FK_facility_client` FOREIGN KEY (`facility_id`) REFERENCES `ctsclouddev`.`facility` (`id`) ON … -
Log what data user saw in Django Admin page
Is there a way to see what data the user saw on the Django admin page? For example, admin user visit list page of companies, I need to track/store which companies(ids) that user saw on the admin list page. This is related to the Django admin pages. -
Django storages using incorrect urls for s3 static files
I am using Django storages to host my static files (css, js, images) on s3. When I load my webpage django keeps pointing to the incorrect url of my s3 public bucket. For example, it keeps returning https://mysite.amazonaws.com/assets/images/cat.png despite the correct public url for the file being https://mysite.s3-ap-southeast-2.amazonaws.com/assets/images/cat.png settings.py DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = os.environ.get('aws_access_key_id') AWS_SECRET_ACCESS_KEY = os.environ.get('aws_secret_key') AWS_STORAGE_BUCKET_NAME = 'mysite' AWS_DEFAULT_ACL = "private" AWS_S3_SIGNATURE_VERSION = "s3v4" AWS_S3_REGION_NAME = 'ap-southeast-2' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_URL = 'https://mysite.s3-ap-southeast-2.amazonaws.com/static/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' -
Problems with Django Template and Json Data
I get Expecting value: line 1 column 1 (char 0) error on the page when my cart is empty but works when cart is populated. I'm expecting the error but that doesn't help either. Same continues on the other template also if data is empty. Maybe it has to do something not being returned. def cartdetails(request): if request.session.get('token', None) != None: tokenid = request.session.get("token") headers = {'Authorization': 'token ' + str(tokenid[0])} url = 'https://api-ecommerce.datavivservers.in/mobile_api/CartDetails/' jsondata = requests.get(url, headers=headers).json() print(jsondata) try: return render(request, 'cart.html', { "order_id": jsondata['order_id'], "user_id": jsondata['user_id'], "wallet_amount": jsondata['wallet_amount'], "payable_amount": jsondata['payable_amount'], "payment_status": jsondata['payment_status'], "payment_mode": jsondata['payment_mode'], "order_status": jsondata['order_status'], "delivery_status": jsondata['delivery_status'], "order_delivery_type": jsondata['order_delivery_type'], "get_cart_total_discount": jsondata['get_cart_total_discount'], "get_cart_total_GST": jsondata['get_cart_total_GST'], "get_cart_total": jsondata['get_cart_total'], "get_cart_sub_total": jsondata['get_cart_sub_total'], "get_cart_quantities": jsondata['get_cart_quantities'], "get_cart_items": jsondata['get_cart_items'], "deliveryCharges": jsondata['deliveryCharges'], "subscription_type": jsondata['subscription_type'], "subscriptionId": jsondata['subscriptionId'], "products": jsondata['products'] }) except simplejson.errors.JSONDecodeError: return render(request, 'cart.html', {}) else: print("login") return redirect('login') -
Django keeps loading signed s3 static files
I am storing my static files (css, js, images) in S3 using django-storages. Everything works as intended however Django seems to be pre-signing all the files when the page loads, making it painfully slow. My S3 permissions are set to public and work fine. For example I can access a certain file publicly at https://mysite.s3-ap-southeast-2.amazonaws.com/assets/images/cat.png However the same file seems to load in the webpage with an HMAC signature which takes forever to load https://mysite.s3.amazonaws.com/assets/images/cat.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&... settings.py DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = os.environ.get('aws_access_key_id') AWS_SECRET_ACCESS_KEY = os.environ.get('aws_secret_key') AWS_STORAGE_BUCKET_NAME = 'mysite' AWS_DEFAULT_ACL = "private" AWS_S3_SIGNATURE_VERSION = "s3v4" AWS_S3_REGION_NAME = 'ap-southeast-2' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_URL = 'https://mysite.s3-ap-southeast-2.amazonaws.com/static/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' -
Django Model Property : How can I access model class property inside .values() QuerySet?
I have PhotoComment model and their @property func. is total_reply.So How can I access this property in .values(). Is it possible or not I not know. Please tell me better way to how to access this property in .values(). models.py: class PhotoComment(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) photo = models.ForeignKey(UserPhoto,on_delete=models.CASCADE) comment_text = models.TextField(max_length = 500) comment_reply = models.ForeignKey('self',related_name='replies',blank=True,null=True,on_delete = models.CASCADE) ... def __str__(self): return '%s(photo_%s)' %(self.user,self.photo) @property def total_reply(self): total = PhotoComment.objects.filter(comment_reply = self.user).count() return total views.py: class PhotoCommentView(APIView): def patch(self,request,formate=None): all_comment = list(PhotoComment.objects.filter(photo__id = request.data.get('photo_id')).values('id','comment_text',?????))⬅⬅⬅⬅⬅⬅ return Response({"Data" : all_comment},status=status.HTTP_200_OK) -
apscheduler: returned more than one DjangoJobExecution -- it returned 2
In my proyect scheduler return this error in the execute job, help me please this is my error in cosole, then execute the program Error notifying listener Traceback (most recent call last): File "C:\Users\angel\Documents\REPOSITORIOS\ishida_comprobantes_electronicos\venv\lib\site-packages\apscheduler\schedulers\base.py", line 836, in _dispatch_event cb(event) File "C:\Users\angel\Documents\REPOSITORIOS\ishida_comprobantes_electronicos\venv\lib\site-packages\django_apscheduler\jobstores.py", line 53, in handle_submission_event DjangoJobExecution.SENT, File "C:\Users\angel\Documents\REPOSITORIOS\ishida_comprobantes_electronicos\venv\lib\site-packages\django_apscheduler\models.py", line 157, in atomic_update_or_create job_id=job_id, run_time=run_time File "C:\Users\angel\Documents\REPOSITORIOS\ishida_comprobantes_electronicos\venv\lib\site-packages\django\db\models\query.py", line 412, in get (self.model._meta.object_name, num) django_apscheduler.models.DjangoJobExecution.MultipleObjectsReturned: get() returned more than one DjangoJobExecution -- it returned 2! This is my code class Command(BaseCommand): help = "Runs apscheduler." scheduler = BackgroundScheduler(timezone=settings.TIME_ZONE, daemon=True) scheduler.add_jobstore(DjangoJobStore(), "default") def handle(self, *args, **options): self.scheduler.add_job( delete_old_job_executions, 'interval', seconds=5, id="delete_old_job_executions", max_instances=1, replace_existing=True ) try: logger.info("Starting scheduler...") self.scheduler.start() except KeyboardInterrupt: logger.info("Stopping scheduler...") self.scheduler.shutdown() logger.info("Scheduler shut down successfully!")