Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to store user auto in database?
I created a form for adding products to an e-Commerce site. The form isn't working perfectly. First issue: I want to store the user automatically by submitting the form. I actually want to store Who did add the product individually. Second Issues: The image field is not working, the image is not stored in the database. How can I fix these issues? help me forms.py: from django import forms from .models import Products from django.forms import ModelForm class add_product_info(forms.ModelForm): class Meta: model = Products fields = ('product_title','product_image') model.py: class Products(models.Model): user = models.ForeignKey(User, related_name="merchandise_product_related_name", on_delete=models.CASCADE, blank=True, null=True) product_title = models.CharField(blank=True, null=True, max_length = 250) product_image = models.ImageField(blank=True, null=True, upload_to = "1_products_img") views.py: def add_product(request): if request.method == "POST": form = add_product_info(request.POST) if form.is_valid(): form.save() messages.success(request,"Successfully product added.") return redirect("add_product") form = add_product_info context = { "form":form } return render(request, "add_product.html", context) templates: <form action="" method="POST" class="needs-validation" style="font-size: 13px;" novalidate="" autocomplete="off" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <div class="d-flex align-items-center"> <button type="submit" class="btn btn-outline-dark ms-auto" style="font-size:13px;">Add</button> </div> </form> -
Why DecimalField are serialized sometimes as number sometime as string numer
I have a django app with rest framework and I noticed that some DecimalField are serialized as string, others as numbers. Why? Here's my model: class TestModel(models.Model): quantity1 = models.DecimalField("quantity1", default=0.0, max_digits=10, decimal_places=3) quantity2 = models.DecimalField("quantity2", default=0.0, max_digits=10, decimal_places=3) quantity3 = models.DecimalField("quantity3", default=0.0, max_digits=10, decimal_places=3) latitude = models.DecimalField(max_digits=9, decimal_places=6) longitude = models.DecimalField(max_digits=9, decimal_places=6) Here's the serialization "quantity1": "1.000", "quantity2": "1.000", "quantity3": "1.000", "latitude": 45.49907, "longitude": 9.18749, I am aware of the problem of serialize floating point and their precision (see here), but why quantities are represented as string while lat/lon are numbers? They are both decimalFields... -
how to start overriding file after it reaches certain size?
Is there a way to start overriding a file when it reaches, for example, 50 MB size? Currently I started with: with open("mylogfile.log", "a") as myfile: myfile.write(something) I want to keep adding text at the end of my file as long as it is under 50 MB size. Then, I want to start overriding, I mean saving the new lines of text but delete the text from the beginning of the file. How do I do that? -
OSError at / [Errno 22] Invalid argument: 'C:\\Users\\HP\\OneDrive\\Desktop\\datascience\\EED\\Emotion\\emotion\templates\\index.html'
Exception Type: OSError at / Exception Value: [Errno 22] Invalid argument: 'C:\Users\HP\OneDrive\Desktop\datascience\EED\Emotion\emotion\templates\index.html' {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Emotion Detection Website</title> <link rel="stylesheet" href="../static\css\style.index.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font- awesome/5.15.3/css/all.min.css"/> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/typed.js/2.0.11/typed.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/waypoints/4.0.1/jquery.waypoints.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js"> </script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.min.css" /> </head> <body> <div class="scroll-up-btn"> <i class="fas fa-angle-up"></i> </div> <nav class="navbar"> <div class="max-width"> <div class="logo"><a href="home">Xim<span>ple.</span></a></div> <ul class="menu"> <li><a href="home" class="menu-btn">Home</a></li> <li><a href="#about" class="menu-btn">About</a></li> <li><a href="#services" class="menu-btn">Services</a></li> <li><a href="#skills" class="menu-btn">Skills</a></li> <li><a href="#teams" class="menu-btn">Teams</a></li> <li><a href="#contact" class="menu-btn">Contact</a></li> </ul> <div class="menu-btn"> <i class="fas fa-bars"></i> </div> </div> </nav> <!-- home section start --> <section class="home" id="home"> <div class="max-width"> <div class="home-content"> <div class="text-1"><text style="color: rgb(240, 40, 40);font- size:50px;">Ximple. </text> provides mission-critical IT services that <br>transform global businesses. .</div> <div class="text-3">And we are <span class="typing"></span></div> <a href="login">Get Started</a> </div> </div> </section> </body> -
How to implement Token Authentication in Django Rest Framework without using a password?
How to implement Token Authentication in Django without using a password? Can we override is_authenticated() ? Can we use a pin number instead of password? -
django dropdown not coming even after adding for loops
Hi I am new to django and I am doing CRUD using serializers having Products,categories,sub categories,size and color as models I am trying to make a django dropdown IN MODELS SUBCATEGORIES below is the model of subcategoires: class SUBCategories(models.Model): category_name = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories_name = models.CharField(max_length=20) sub_categories_description = models.CharField(max_length=20) isactive = models.BooleanField(default=True) below is the insert function def insert_sub_categories(request): if request.method == "POST": insertsubcategories = {} insertsubcategories['sub_categories_name']=request.POST.get('sub_categories_name') insertsubcategories['sub_categories_description']=request.POST.get('sub_categories_description') form = SUBCategoriesSerializer(data=insertsubcategories) if form.is_valid(): form.save() print("hkjk",form.data) messages.success(request,'Record Updated Successfully...!:)') print(form.errors) return redirect('sub_categories:show_sub_categories') else: category_dict = Categories.objects.filter(isactive=True) category = CategoriesSerializer(category_dict,many=True) hm = {'context': category} print(hm) # print(form.errors) return render(request,'polls/insert_sub_categories.html') else: category_dict = Categories.objects.filter(isactive=True) category = CategoriesSerializer(category_dict,many=True) hm = {'context': category} print(hm) return render(request,'polls/insert_sub_categories.html',hm) below is the for loop in html page for dropdown <td>category name</td> <td> <select name="category_name" id=""> {% for c in hm %} <option value="{{c}}">{{c}}</option> {% endfor %} </select> </td> in print statement the hm dictionary is showing : {'context': CategoriesSerializer(<QuerySet [<Categories: Categories object (5)>, <Categories: Categories object (6)>]>, many=True): id = IntegerField(label='ID', read_only=True) category_name = CharField(max_length=10, required=False) category_description = CharField(max_length=10) isactive = BooleanField(required=False)} even though the data of models Category is saved in the database successfully, where am I going wrong? -
How to create a timetable in the shape of a donut chart with django
I want to make a webpage that manages time using Django. Managing the time I'm talking about means checking the start time and end time of an activity and displaying it on a donut chart with a specific color. Currently, only temporary html is created. I want to display a donut chart on a calendar. <div class="footer"> <div class="input_content"> <form> <label>Input activity</label> <input> <button>play / pause</button> <button>stop </button> </form> </div> </div> html above: enter image description here Example image I want to draw in html: enter image description here What I am currently thinking about is: Enter a color and activity in html and press the play button to save data (date, color, activity, start time) to Django's sqlite, and press the end button to save the end time to sqlite. Render the donut chart in html using the saved data (date, color, activity, start time, end time) using views.py. Activities on the same day should be displayed on one chart. I'd like to ask if what I'm thinking of is implementable, or if there is a better way. Thank you in advance. -
How to fork Django project from github without previous superuser info?
I forked a Django project. I created myself as a new superuser and logged in to the admin page. But the models had previous info already which were added by the one whose project I forked? Can we delete all his info that he added in his version? -
Unable to impliment Comments xtd in my blog
Hi mates i am trying to implement comments xtd to my django blog and getting below error anyone here can help in resolving the issue. settings done in the code are given below and also the error i am receiving is also listed below. Error produces when i try to explore the article AttributeError at /postpage/first/ 'str' object has no attribute '_meta' Request Method: GET Request URL: http://127.0.0.1:8000/postpage/first/ Django Version: 3.1.14 Exception Type: AttributeError Exception Value: 'str' object has no attribute '_meta' Exception Location: C:\Users\navee\OneDrive\Desktop\script\VENV\lib\site-packages\django\contrib\contenttypes\models.py, line 27, in _get_opts Python Executable: C:\Users\navee\OneDrive\Desktop\script\VENV\Scripts\python.exe Python Version: 3.8.10 Python Path: ['C:\\Users\\navee\\OneDrive\\Desktop\\script\\admin', 'c:\\program files\\python38\\python38.zip', 'c:\\program files\\python38\\DLLs', 'c:\\program files\\python38\\lib', 'c:\\program files\\python38', 'C:\\Users\\navee\\OneDrive\\Desktop\\script\\VENV', 'C:\\Users\\navee\\OneDrive\\Desktop\\script\\VENV\\lib\\site-packages'] Server time: Tue, 05 Jul 2022 06:28:17 +0000 Error during template rendering In template C:\Users\navee\OneDrive\Desktop\script\admin\firmApp\templates\firmApp\basic.html, error at line 0 'str' object has no attribute '_meta' 1 {% load static %} 2 {% load comments %} 3 <!doctype html> 4 <html lang="en"> 5 <head> 6 <meta charset="utf-8"> 7 <meta name="viewport" content="width=device-width, initial-scale=1"> 8 9 <title >{% block title %} {% endblock %}</title> 10 Settings done in Article.html {% get_comment_count for object as comment_count %} <div class="py-4 text-center"> <a href="{% url 'blog:post-list' %}">Back to the post list</a> &nbsp;&sdot;&nbsp; {{ comment_count }} comment{{ comment_count|pluralize }} … -
AttributeError: 'QuerySet' object has no attribute 'add_message'
Can anyone please tell me how to add messages in Django rooms for chat applications. Ex: For making comments in a blog or having conversation in chat rooms. Here is my error page after adding message. The problem is message are saved in the database and shown when he go to room page where we added the message but on hitting enter page displays an error AttributeError: 'QuerySet' object has no attribute 'add_message'. Rooms page page shows error in this image but message is saved in this image Here are the views.py file and room.html file views.py file, here room is the view for storing all rooms this is room.html linked to room function from views.py file for displaying messages using templates on webpage -
Azure SDK for Python: Copy blobs
For my current Python project I' using the Microsoft Azure SDK for Python. I want to copy a specific blob from one container path to another and tested already some options, described here. Overall they are basically "working", but unfortunately the new_blob.start_copy_from_url(source_blob_url) command always leads to an erorr: ErrorCode:CannotVerifyCopySource. Is someone getting the same error message here, or has an idea, how to solve it? I was also trying to modify the source_blob_url as a sas-token, but still doesn't work. I have the feeling that there is some connection to the access levels of the storage account, but so far I wasn't able to figure it out. Hopefully someone here can help me. -
Passing Data to D3.js Line Chart with Django Backend
I am following a tutorial to create dashboard with D3.js plots. I am facing errors while passing data to the Line Chart plot. I am using the code extracted from here. Instead of using the data from csv I want to use the data which is extracted from the database. I can't figure out where should the data be referred within the code? Following is the index.html file {% load static %} <html> <script src="https://d3js.org/d3.v4.js"></script> <body> <h1> Hello! </h1> <div id="my_dataviz"></div> </body> <script> // set the dimensions and margins of the graph var margin = {top: 10, right: 30, bottom: 30, left: 60}, width = 460 - margin.left - margin.right, height = 400 - margin.top - margin.bottom; // append the svg object to the body of the page var svg = d3.select("#my_dataviz") .append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); //Read the data // d3.csv("https://raw.githubusercontent.com/holtzy/data_to_viz/master/Example_dataset/3_TwoNumOrdered_comma.csv", var data = {{ AAPL|safe }}, // When reading the csv, I must format variables: function(d){ return { date : d3.timeParse("%Y-%m-%d")(d.date), value : d.Close } }, // Now I can use this dataset: function(data) { // Add X axis … -
Dynamically updating Django template with new data
I am creating a cricket website which shows the live scores of cricket matches using Django. Below I have shown the sample views.py for my website: Views.py def livescores(): # generates livescores and returns a dict containing live scores return scores def display_scores(request): # calls the livescores function and gets the dict and #passes it to django template for rendering purposes scores = livescores() return render(request, 'LiveScores/display_scores.html', scores) Here is the Django template to which it passes that dict: <!DOCTYPE html> <html> <head> <title>{{MatchName}}</title> {% load static %} <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.5/dist/umd/popper.min.js" integrity="sha384-Xe+8cL9oJa6tN/veChSP7q+mnSPaj5Bcu9mPX5F5xIGE0DVittaqT5lorf0EI7Vk" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/js/bootstrap.min.js" integrity="sha384-kjU+l4N0Yf4ZOJErLsIcvOU2qSb74wXpOhqTvwVx3OElZRweTnQ6d31fXEoRD1Jy" crossorigin="anonymous"></script> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <link href="{% static 'LiveScores/style.css'%}" rel="stylesheet" type="text/css"> </head> <body> <header> <nav class="navbar"> <div class="container-fluid"> <a class="navbar-brand" href="#"><h1>Live Cricket Scores</h1></a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">About Us</a> </li> <li class="nav-item"> <a class="nav-link">Contact Us</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> More </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="#">Live Matches</a></li> <li><a class="dropdown-item" href="#">Terms & Services</a></li> <li><hr class="dropdown-divider"></li> <li><a class="dropdown-item" href="#">Sources</a></li> </ul> </li> </ul> <form … -
ErrorDetail(string='This field is required.', code='required' )
Hi I am new to django html and I have been making a CRUD with Products having categories,sub categories,colors,size using SERIALIZERS.When I am trying to add a the data isnt getting displayed on webpage heres the error: "{'category_name': [ErrorDetail(string='This field is required.', code='required')]}" below is the model of categories: class Categories(models.Model): #made changes to category_name for null and blank category_name = models.ForeignKey(Products,on_delete=models.CASCADE) category_description = models.CharField(max_length=10) isactive = models.BooleanField(default=True) below are the show and insert functions def show_cat(request): showcategory = Categories.objects.filter(isactive=True) #print(showall) serializer = CategoriesSerializer(showcategory,many=True) #print(serializer.data) return render(request,'polls/show_cat.html',{"data":serializer.data}) def insert_cat(request): if request.method == "POST": insertcategory = {} insertcategory['category_name.id']=request.POST.get('category_name') insertcategory['category_description']=request.POST.get('category_description') form = CategoriesSerializer(data=insertcategory) if form.is_valid(): form.save() print("hkjk",form.data) messages.success(request,'Record Updated Successfully...!:)') return redirect('categories:show_cat') else: print(form.errors) return redirect('categories:show_cat') else: return render(request,'polls/insert_cat.html') below are the htmls of insert and show respetively <tr> <td>Category Name</td> <td> <input type="text" name="category_name" placeholder="CATEGORIES"> </td> </tr> <tr> <td>Description</td> <td> <textarea name="category_description" id="" cols="30" rows="10"> </textarea> </td> </tr> <td><b>{{result.category_name}}</b></td> <td><b>{{result.category_description}}</b></td> <td style="position: relative;left:50px;"> <a href="categories/edit_cat/{{result.id}}"> <button class="btn btn-primary"> <i class="fa-solid fa-pen-to-square">EDIT</i> </button> </a> </td> where am I going wrong in the code? -
Wagtail Streamblocks for logged in users
I would like to create a streamblock that can be limited to logged in users. A the moment I have this: class DefaultBlock(blocks.StructBlock): loggedin_only = blocks.BooleanBlock(required=False) class FramedVideoBlock(DefaultBlock): title = blocks.CharBlock(max_length=128, required=False) video = EmbedBlock() button = ButtonBlock(required=False) styling = blocks.ChoiceBlock(choices=STYLINGCHOICES) class Meta: template = 'streamblocks/framed_video_block.html' icon = 'radio-full' and in the template this: {% if self.loggedin_only == True and request.user.is_authenticated or self.loggedin_only == False %} <div class="bg_video_title"> ... </div> {% endif %} But I have the idea this can be done better. Maybe with a mixin? Any ideas? -
Celery task is not getting registerd
So I am using celery to run a task in an assigned time. I used ClockedSchedule since I wanted to run the task only one time in a particular time. clocked, _ = ClockedSchedule.objects.get_or_create( clocked_time=time PeriodicTask.objects.create( name=slug, task="account.tasks.send_money", clocked=clocked, one_off=True ) # creating periodic task using celery to run the task at scheduled time So when i run the code, PeriodicTask object is created. Task(custom) field is saved. but Task(registered) field is not being saved. So when it tries to run the task, I get the following error: [2022-07-05 11:19:00,035: ERROR/MainProcess] Received unregistered task of type 'account.tasks.send_money'. The message has been ignored and discarded. Please help me to find out the reason behind it. -
How to access a post author's profile picture in Django?
I am trying to display a username's profile picture in a blog/social media app when some user clicks on some other user's username but it is currently not working. In my template: (I think my issue is I don't have access to post?) <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}"> My users\models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) In my blog/models.py: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) I can retrieve some user's username by {{ view.kwargs.username }}, how can I do this with profile pictures? -
Convert Xml and Json file to string in Django
I Have data in XML and JSON and I want to upload it into MongoDB, but in string type. So how do I convert all files into a string and upload them into MongoDB ? -
To build an API for data transfer between MSSQL database and MySQL
I've built 2 websoftwares one with .Net and MSSQL server, the other with Django and MySQL. Now I want to transfer datas which falls in MSSQL to MySQL automatically. Is it possible to build an API for that?? I've no idea how to do it. Thanks in advance. -
Expected pk value, received str (pk is a CharField)
Hi i am new to django and html and I am making a shopping CRUD project with models Producst,categories,Sub_categories,size,colors using SERIALIZERS. I am now trying to make crud of categories,and while inserting I am getting the following error: "{'category_name': [ErrorDetail(string='Incorrect type. Expected pk value, received str.', code='incorrect_type')]}" below is my show_cat function def show_cat(request): showcategory = Categories.objects.filter(isactive=True) #print(showall) serializer = CategoriesSerializer(showcategory,many=True) #print(serializer.data) return render(request,'polls/show_cat.html',{"data":serializer.data}) insert_cat function def insert_cat(request): if request.method == "POST": insertcategory = {} insertcategory['category_name']=request.POST.get('category_name') insertcategory['category_description']=request.POST.get('category_description') form = CategoriesSerializer(data=insertcategory) if form.is_valid(): form.save() print("hkjk",form.data) messages.success(request,'Record Updated Successfully...!:)') return redirect('categories:show_cat') else: print(form.errors) return redirect('categories:show_cat') else: return render(request,'polls/insert_cat.html') below is html for insert <tr> <td>Category Name</td> <td> <input type="text" name="category_name" placeholder="CATEGORIES"> </td> </tr> <tr> <td>Description</td> <td> <textarea name="category_description" id="" cols="30" rows="10"> </textarea> </td> </tr> below is the showcategory html page {% for result in data %} <tbody> <tr> <td><b>{{result.category_name}}</b></td> <td><b>{{result.category_description}}</b></td> <td style="position: relative;left:50px;"> <a href="categories/edit_cat/{{result.id}}"> <button class="btn btn-primary"> <i class="fa-solid fa-pen-to-square">EDIT</i> </button> </a> </td> <td> <a href="{% url 'categories:del_cat' result.id %}" onclick="return confirm('Are You Sure you want to delete?')"> <button class="btn btn-danger"> <i class="fa-solid fa-trash">DELETE</i> </button> </a> </td> </tr> </tbody> {% endfor %} </table> Where am I going wrong in the code -
django media images forbidden
I got a weird bug: after deploying my django project to server, particular media folder is 403 forbidden for no reason (others work fine), here's a tree diagram of my media folder. . ├── [drwx------] avatar │ ├── [-rw-r--r--] 1.png │ ├── [-rw-r--r--] 10.png │ ├── [-rw-r--r--] 11.png │ ├── [-rw-r--r--] 77.png │ ├── [-rw-r--r--] 78.png │ ├── [-rw-r--r--] 79.png ├── [drwxr-xr-x] cdn │ ├── [drwxr-xr-x] css │ │ ├── [-rw-r--r--] console.css │ │ ├── [-rw-r--r--] demo.css │ │ ├── [-rw-r--r--] demo_list_jYn4xiM.css │ │ └── [-rw-r--r--] shelf.css │ ├── [drwxr-xr-x] js │ │ ├── [-rw-r--r--] demo.js │ │ └── [-rw-r--r--] ui.js │ └── [drwxr-xr-x] webfonts │ ├── [-rw-r--r--] fa-regular-400.woff2 │ └── [-rw-r--r--] fa-solid-900.woff2 ├── [drwxr-xr-x] common │ ├── [-rw-r--r--] 172-1720825_small.jpg │ └── [-rw-r--r--] bg2.jpg ├── [drwxr-xr-x] demo │ └── [-rw-r--r--] Screen_Shot_2021-08-16_at_3.45.01_pm.png ├── [drwxr-xr-x] look │ ├── [-rw-r--r--] 2625191.JPG │ └── [-rw-r--r--] me.jpg ├── [drwxr-xr-x] portray │ ├── [-rw-r--r--] Screen_Shot_2021-08-16_at_3.45.01_pm.png │ ├── [-rw-r--r--] Screen_Shot_2021-08-16_at_3.45.01_pm_VsswTUf.png │ └── [-rw-r--r--] Screen_Shot_2021-08-16_at_3.45.01_pm_XIA2JgY.png ├── [drwxr-xr-x] profile │ ├── [-rw-r--r--] IMG_1684.JPG │ └── [-rw-r--r--] me.jpg ├── [drwxr-xr-x] projects │ └── [-rw-r--r--] default.jpg ├── [drwxr-xr-x] team │ └── [-rw-r--r--] default.jpg ├── [drwxr-xr-x] thumbnail │ ├── [-rw-r--r--] seagull_Z2AYe1w.png │ └── [-rw-r--r--] typescript-in-react.png └── [drwxr-xr-x] video ├── [-rw-r--r--] card.mp4 ├── … -
i have an error when using django for loop in script tag
i have an error when using django for loop in script tag`enter <script> $('#cat_input').hide() $('#addcat').click(function(){ $('#cat_input').show() }); $('#backcat').click(function(){ $('#cat_input').hide() }); {% for book in books %} $(".cat{{book.category.id}}").click(function(){ $(".book_hide").hide() $(".book{{book.category.id}}}").show() }); {% endfor %} </script> code here` enter image description here -
How to replace get_declared_classes() from CakePHP to Python?
I have been moving website made in Cakephp into Django. In one place I found get_declared_classes(). I thinks this function returns list of previously used classes before running current class. First time when I encounter this, I just store list of classes manually in one file and I was using that and this solution worked only for a particular web page but Now I have multiple pages calling this class and everytime list of classnames are very different so I can not store class name list. If question is not clear please let me know, I can provide more information. Is there any other library that can replace this function in Python? Or Is there any other solution I can try ? -
Way to Filter by DB Field in Django using Class Views
I tried to search for answers, but after a few days, I'm here asking: I'm a beginner, making a todo list app - expanding on a tutorial I followed. Currently, it's filtering by user, which is fine, but I also want to filter by a field in the DB (list). Models: class ToDoList(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=200) description = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Meta: ordering = ['created'] class Task(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) list = models.ForeignKey(ToDoList, on_delete=models.CASCADE) def __str__(self): return self.title class Meta: ordering = ['complete'] View I'm trying to change: class TaskList(LoginRequiredMixin, ListView): model = Task context_object_name = "tasks" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['tasks'] = context['tasks'].filter(user=self.request.user) context['count'] = context['tasks'].filter(complete=False).count search_input = self.request.GET.get('search-area') or '' if search_input: context['tasks'] = context['tasks'].filter(title__startswith=search_input) context['search_input'] = search_input return context Also, is there a way to access the list variable in the html component, like here? url: path('tasks/<list>/create', TaskCreate.as_view(), name="task-create"), html: <a href="{% url 'tasks' 'task.list' %}">&#8592; Back</a> -
all cloud platforms like Heroku and digital ocean require billing card
Hi I want to deploy my Django app to Heroku and when I want to use add-ons like ClearDB MySQL it requires me to verify my account by giving Heroku my billing card the problem is I'm in a country that is restricted by US law and we don't have global cards so I cant use mine as I searched all over the web for cloud platforms it seems that all of them require such verification do you have any solution for that ? or any platform that won't require such verification?