Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The Command "python manage.py runserver" is not running
While I use the command the terminal shows a Major Error:- "import sqlparse ModuleNotFoundError: No module named 'sqlparse' " -
Display modal with information from a specific button
I have a Django template that renders a little bit of data about the user. It is a for list that goes through and creates this element for each user. I want to be able to click on that and have a modal appear with all of their information. So if I click on user1 I get user1's information, and so on. I am not sure how to do this. I am currently trying to use JavaScript to do this. The problem is that I cannot get the data from the specific element into JavaScript. I have the modal working, in that it pops up. However, I cannot find a way to retrieve the data from the specific user clicked on. #dashboard.html {% for party in parties %} <div class="userInfo"> <div class="modal-btn">{{party.id}}</div> <img user="{{party}}" src="{% static 'restaurants/images/userIcon.png' %}"> <div class="userText"> <p>{{party.lastName}} </p></br> </div> <button name="remove"><a href="/restaurants/removeParty/{{party.id}}">Remove</a></button> </div> {% endfor %} I just need to get data from a specific user into the js from the specifc button clicked. Maybe there is a better way to do this? I am not sure. I just need be able to populate a modal with data from the specific user clicked. -
How do I show the comment of the content from Django?
I am use PostgreSQL on Django. I am use Django 2.2.3 and pyton 3.7 version. I want to display comments for related content. But all comments appear in all content. I made the coding based on the narration found in the link(https://tutorial-extensions.djangogirls.org/en/homework_create_more_models/). My codes: views.py def PostDetail(request, slug): post = Post.objects.filter(status=2, slug=slug) comment = Comment.objects.filter(approved_comment=True) comment_count = Comment.objects.count() if request.method == 'POST': post_id = post['id'] print('hata: ', post_id) comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.Post = post new_comment.save() return redirect('blog:post_detail', slug) else: comment_form = CommentForm() return render(request, 'single-blog.html', { 'post_details': post, 'comments': comment, 'comment_form': comment_form, 'comment_count': comment_count } ) models.py class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') updated_on = models.DateTimeField(auto_now=True) content = HTMLField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) model_pic = models.ImageField(upload_to='uploads/', default='upload image') class Meta: ordering = ['-created_on'] def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') # reply_to = models.ForeignKey('self', related_name='replies', null=True, blank=True) author = models.CharField(max_length=200) comment = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) comment_image = models.ImageField(upload_to='uploads/', default='upload image') def approve(self): self.approved_comment = True self.save() def __str__(self): return self.comment single-blog.html <div class="comments-area"> <h4>Comments:</h4> <div class="comment-list"> {% for comment in comments %} <div class="single-comment justify-content-between … -
Can't run django-admin startproject mysite on windows 10
I wanted to learn django but whenever i type in the command "django-admin startproject mysite" it keeps giving me an error https://i.imgur.com/wtOmVh0.png Any help please? -
DRF: Serializer Group By Model Field
I want my api to return Account objects grouped by the account_type field in the model. This is what is returned now: [{ "id": 6, "owner": 1, "account_name": "Credit Card 1", "account_type": "credit card", "created_time": "2019-07-18T02:57:44.288654Z", "modified_time": "2019-07-18T02:57:44.288842Z" }, { "id": 11, "owner": 1, "account_name": "Savings 1", "account_type": "savings", "created_time": "2019-07-18T03:00:22.122226Z", "modified_time": "2019-07-18T03:00:22.122283Z" }, { "id": 5, "owner": 1, "account_name": "Checking 1", "account_type": "checking", "created_time": "2019-07-18T02:57:28.580268Z", "modified_time": "2019-07-18T02:57:28.580305Z" }, { "id": 9, "owner": 1, "account_name": "Savings 2", "account_type": "savings", "created_time": "2019-07-18T02:59:57.156837Z", "modified_time": "2019-07-18T02:59:57.156875Z" }, { "id": 10, "owner": 1, "account_name": "Savings 3", "account_type": "savings", "created_time": "2019-07-18T03:00:12.873799Z", "modified_time": "2019-07-18T03:00:12.873846Z" }, { "id": 7, "owner": 1, "account_name": "Credit Card 2", "account_type": "credit card", "created_time": "2019-07-18T02:57:55.921586Z", "modified_time": "2019-07-18T02:57:55.921613Z" }] And I'd like it to return something like this: { "credit card": [ { "id": 6, "owner": 1, "account_name": "Credit Card 1", "account_type": "credit card", "created_time": "2019-07-18T02:57:44.288654Z", "modified_time": "2019-07-18T02:57:44.288842Z" }, { "id": 7, "owner": 1, "account_name": "Credit Card 2", "account_type": "credit card", "created_time": "2019-07-18T02:57:55.921586Z", "modified_time": "2019-07-18T02:57:55.921613Z" } ], "savings": [ { "id": 11, "owner": 1, "account_name": "Savings 1", "account_type": "savings", "created_time": "2019-07-18T03:00:22.122226Z", "modified_time": "2019-07-18T03:00:22.122283Z" }, { "id": 9, "owner": 1, "account_name": "Savings 2", "account_type": "savings", "created_time": "2019-07-18T02:59:57.156837Z", "modified_time": "2019-07-18T02:59:57.156875Z" }, { "id": 10, "owner": … -
use textbox to search multiple view functions in django
Hello I am very new to Django/python - I have a scenario where I am seeking some directional guidance/advice , so I have a basic template with a searchbox vaule = rep_date <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> </head> <body> <div class="row"> <div class="col-sm-2"> <h1 style="text-align:center;position:relative">MENU</h1> <nav class="navbar bg-ligh"> <form method="post" enctype="multipart/form-data" action=""> {% csrf_token %} <input type="text" class="form-control form-control-sm" value="rep_date"> <input type="submit" value="ok"> </form> <ul class="navbar-nav"> <li class="nav-items"><a href="" class="nav-link">Report 1</a></li> <li class="nav-items"><a href="#" class="nav-link">Report 2</a></li> <li class="nav-items"><a href="#" class="nav-link">Report 3</a></li> <li class="nav-items"><a href="#" class="nav-link">Report 4</a></li> <li class="nav-items"><a href="#" class="nav-link">Report 5</a></li> </ul> </nav> </div> <div class="col-sm-10"> {% block content %} {% endblock %} </div> </div> </body> </html> after the submission of the textbox i am trying to return the respective views for each report from the side nav bar, using the input value from the posted textbox to feed into the view for the final view results to render each html page sample for the view for each report: def ReportOne(request): RepOneResult = Reporttable.objects.filter(yyyy_mm=PostedVal).order_by("-approved")[:25] return render(request, "reports/RepOne.html", {'RepOneResult': RepOneResult}) So I am having issues appling the code logic along with including the form posted value = rep_val in … -
How create model field that accepts two different dict keys and values and has posibility to import data?
I'm newbie in Django. I started little project of collecting data about books - from google books api and with possibility to manualy add new postions. I don't how to deal with dictionary inside JSON, with i mean "industryIdentifiers": "publisher": "Random House Digital, Inc.", "publishedDate": "2005-11-15", "description": "\"Here is the story behind one of the most remarkable Internet successes of our time. Based on scrupulous research and extraordinary access to Google, ...", "industryIdentifiers": [ { "type": "ISBN_10", "identifier": "055380457X" }, { "type": "ISBN_13", "identifier": "9780553804577" } ], How to make manual input and import from API compatible? What kind of field should I choose in "industryIdentifiers" to input ISBN_10 and ISBN_13 with their identifiers? class Books(models.Model): title = models.CharField(max_length=250) authors = models.CharField(max_length=250) publishedDate = models.DateField(blank=True, null=True) industryIdentifiers = pageCount = models.IntegerField(blank=True, null=True) imageLinks = models.URLField(blank=True, null=True) language = models.CharField(max_length=5) -
How to make two different types of registration and login in django?
I have two different types of users employees and customers. how to make to different types of registration and login and i want to redirect them to different page. I am new in django but i want to learn this things. I had searched every where but i don't find any solutions Is this possible to make two different types of user login and registration in django? Help will be appreciated and motivation for me to learn django Thanking you all in advance -
TypeError: 'Object' object does not support item assignment
Good afternoon I am presenting the following TypeError error: 'Teams' object does not support item assignment, the question is that I am serializing my interfaces model, but I am adding another model's field through Foreign Key, but when trying to Post / Put a a record of my interfaces model, it asks me for the fields Name, Location, Category which I do not want to modify since these values are in the Equipo Model, and automatically from there they must bring those values class Equipos(models.Model): id_equipo=models.PositiveSmallIntegerField(primary_key=True) nombre=models.CharField(max_length=15) vendedor=models.CharField(max_length=10,default='S/A',blank=True) ip_gestion=models.GenericIPAddressField(protocol='Ipv4',default='0.0.0.0') tipo=models.CharField(max_length=8,default='S/A',blank=True) localidad=models.CharField(max_length=5,default='S/A',blank=True) categoria=models.CharField(max_length=10,default='S/A',blank=True) ultima_actualizacion=models.DateTimeField(auto_now=True) class Meta: db_table = 'Equipos' class Puertos(models.Model): id_puerto=models.PositiveIntegerField(primary_key=True) nombre=models.CharField(max_length=25) ultima_actualizacion=models.DateTimeField(auto_now=True) class Meta: db_table='Puertos' class Interfaces(models.Model): id_interface=models.PositiveIntegerField(primary_key=True) id_EquipoOrigen=models.ForeignKey(Equipos,on_delete=models.DO_NOTHING,related_name='equipo_origen') id_PuertoOrigen=models.ForeignKey(Puertos,on_delete=models.DO_NOTHING,related_name='puerto_origen',null=True,blank=True) estatus=models.BooleanField(default=False) etiqueta_prtg=models.CharField(max_length=80,null=True,blank=True) grupo=models.PositiveSmallIntegerField(default=0,blank=True) if_index=models.PositiveIntegerField(default=0,blank=True) bw=models.PositiveSmallIntegerField(default=0,blank=True) bw_al=models.PositiveSmallIntegerField(default=0,blank=True) id_prtg=models.PositiveSmallIntegerField(default=0,blank=True) ospf=models.BooleanField(default=False) description=models.CharField(max_length=200,null=True,blank=True) id_EquipoDestino=models.ForeignKey(Equipos,on_delete=models.DO_NOTHING,related_name='equipo_destino') id_PuertoDestino=models.ForeignKey(Puertos,on_delete=models.DO_NOTHING,related_name='puerto_destino') ultima_actualizacion=models.DateTimeField(auto_now=True) class Meta: db_table='Interfaces' class EquipoSerializer(serializers.ModelSerializer): class Meta: model=Equipos fields=('id_equipo','nombre','vendedor','ip_gestion','tipo','localidad','categoria','ultima_actualizacion',) class NestedEquipoSerializer(serializers.ModelSerializer): class Meta: model = Equipos fields = ('id_equipo', 'nombre', 'localidad', 'categoria',) class PuertoSerializer(serializers.ModelSerializer): class Meta: model=Puertos fields=('id_puerto','nombre','ultima_actualizacion') class InterfaceSerializer(serializers.ModelSerializer): EquipoOrigen = serializers.CharField(source='id_EquipoOrigen.nombre') PuertoOrigen = serializers.CharField(source='id_PuertoOrigen.nombre') LocalidadOrigen=serializers.CharField(source='id_EquipoOrigen.localidad') CategoriaOrigen=serializers.CharField(source='id_EquipoOrigen.categoria') EquipoDestino = serializers.CharField(source='id_EquipoDestino.nombre') PuertoDestino = serializers.CharField(source='id_PuertoDestino.nombre') LocalidadDestino=serializers.CharField(source='id_EquipoDestino.localidad') CategoriaDestino=serializers.CharField(source='id_EquipoDestino.categoria') class Meta: model=Interfaces fields=('id_interface','id_EquipoOrigen','EquipoOrigen','id_PuertoOrigen','PuertoOrigen','LocalidadOrigen','CategoriaOrigen','estatus','etiqueta_prtg','grupo','if_index','bw','bw_al','id_prtg','ospf','description','id_EquipoDestino','EquipoDestino','id_PuertoDestino','PuertoDestino','LocalidadDestino','CategoriaDestino','ultima_actualizacion',) class EquiposViewSet(viewsets.ModelViewSet): queryset=Equipos.objects.all() serializer_class=EquipoSerializer class PuertosViewSet(viewsets.ModelViewSet): queryset=Puertos.objects.all() serializer_class=PuertoSerializer class InterfacesViewSet(viewsets.ModelViewSet): queryset=Interfaces.objects.all() serializer_class=InterfaceSerializer -
Do time consumption of query set matter in django?
i want to know do function model_name.objects.Filter takes the more time then the model.objects.get ? as we all see that the filter gives you the queryset but the get method gives you the single object but having queryset is not equal to having all the object even after having queryset if i select single object by slicing(without loop) or using get method to select the object i tryed to get time difference but it takes soo less time that i can't see from time import time def f1(): t0 = time() # Used filter print("Execution time of f1: {}".format(time()-t0)) def f2(): t0 = time() # Used Get print("Execution time of f2: {}".format(time()-t0)) can someone show me the difference or which is better even i think that get is better but how? -
Why isn't Django Memcached activity being logged?
I'm trying to use Memcached as my main cache for a Django project. However, when I enter some data into my cache to ensure that it's working properly, nothing is being logged into my log file. Here are my Django settings: # settings.py CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } CACHE_MIDDLEWARE_ALIAS = 'default' CACHE_MIDDLEWARE_SECONDS = 300 CACHE_MIDDLEWARE_KEY_PREFIX = '' MIDDLEWARE_CLASSES = ( 'django.middleware.cache.UpdateCacheMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', ) Here is my Memcached configuration: # /etc/memcached.conf -d logfile /var/log/memcached.log -vv -m 64 -p 11211 -u memcache -l 127.0.0.1 I created the logfile /var/log/memcached.log and gave it owner 'memcache', group 'adm' and permissions 0644. I've confirmed memcached is running and listening on its port: $ netstat -tupan | grep 11211 tcp 0 0 127.0.0.1:11211 0.0.0.0:* LISTEN 20655/memcached tcp 0 0 127.0.0.1:11211 127.0.0.1:53822 ESTABLISHED 20655/memcached tcp 0 0 127.0.0.1:53822 127.0.0.1:11211 ESTABLISHED 22403/python To test Memcached with Django I ran the following commands: python manage.py shell from django.core.cache import cache cache.set('my_key', 'hello world!', 30) cache.get('my_key') # Returns 'hello world!' However, after running this command, the memcached log file is still empty when it should contains the get and set I just ran. What am I missing? … -
Can a Websocket message from the server be spoofed?
I am creating a multiplayer game where users have the option to move up/down/left/right. When a user makes a movement, this movement is sent to the (websocket) server so the opponent can see where the other user is. I'm wondering if these messages that contain user movements can be spoofed? If so, I will have to think of a new method. Thanks in advance -
Problem with getting post data from user and saving it to sessions in django
I'm working on my django-shop project. I have adding to cart view function. Now I want to upgrate it by adding product to cart with user selected quantity. I'm trying to get quantity from form and send it to cart view. But it doesn't work. How can I send recieved data to cart_form input value? Sorry for my bad English Here is my add_to_cart_form <form action="" method="POST" id="product-quantity"> <label for="product-quantity">Количество:</label> <input class="product-quantity-input" type="number" name="quantity" value="1" step="1" min="1" max='10' data-id='{{ item.id }}'> <button type="submit" class="btn add-to-cart-btn btn-sm" data-slug='{{ product.slug }}'>В корзину <img src="{% static 'img/shopping-cart.png' %}" class="shopping-cart-icon-in-btn"> </button> </form> Here is my cart_form <td class="text-center cart-table-info"> <form action="" method="GET"> <input class="cart-item-quantity" type="number" name="quantity" value=" recieved quantity from add_to_cart_form" step="1" min="1" max='10' data-id='{{ item.id }}'> </form> </td> Here is views.py def getting_or_creating_cart(request): try: cart_id = request.session['cart_id'] cart = Cart.objects.get(id=cart_id) request.session['total'] = cart.items.count() except: cart = Cart() cart.save() cart_id = cart.id request.session['cart_id'] = cart_id cart = Cart.objects.get(id=cart_id) return cart def cart_view(request): cart = getting_or_creating_cart(request) categories = Category.objects.all() context = { 'cart' : cart, 'categories' : categories, } return render(request, 'ecomapp/cart.html', context) def add_to_cart_view(request): cart = getting_or_creating_cart(request) product_slug = request.GET.get('product_slug') quantity = request.POST.get('quantity') product = Product.objects.get(slug=product_slug) cart.add_to_cart(product.slug) new_cart_total = 0.00 for item in cart.items.all(): … -
Django rest framework Token for "per device" authentication
i want to set a token for a mobile app in order for it to have access to server resources , the project doesn't contain users but only an admin panel deployed in a server , and a mobile app which doesn't require authentication ( no account , not user based) . how can i make a token for that specific mobile app using django rest framework api? -
Django website is loading slow on Heroku, and it is not because of QuerySets
Have website that is running on simple generic Class-Based Views. First I thought - the QuerySets are the issue but since all my queries are lower than 8ms, that is not the issue. Locally the website is running fast under - 200/300ms with all images and everything. When I have pushed it to Heroku it was slow. In the inspect chrome bar - it shows 1 straight line for 1-2 seconds and then loading the rest - it waits 1-2 seconds and then it loads. So I have started to break down the process and came to 1 conclusion - removed the DB and it started loading very fast like 100ms - when I have plugged in the Postgres DB - instantly went to slow mode. Have installed Django-Toolbar as well to see what is going on. Here are the results. I have even tried to put DB and app on higher tiers just to see and no difference. So what I did is as well created simple view Test - with 3 images that I see the images are not causing it and load it - takes 1-2secs to start loading as well - removing DB - loads very … -
how can i make an auto populated dropdown with AJAX in django?
im working on a search form on diffrent tables, i have two tables called 'specialte' and 'option' both assosiated with a table called 'service', what i want is when i choose a 'service' from a dropdown, another dropdown is auto populated with specialtes and options using AJAX. this is my .models : class Service(models.Model): value = models.CharField(max_length = 45, blank = False, null = False) departement = models.ForeignKey(Departement, on_delete = models.CASCADE) def __str__(self): return self.value class Option(models.Model): value = models.CharField(max_length = 45, blank = False, null = False) service = models.ForeignKey(Service, on_delete = models.CASCADE) def __str__(self): return self.value class Specialite(models.Model): value = models.CharField(max_length = 45, blank = False, null = False) service = models.ForeignKey(Service, on_delete = models.CASCADE) def __str__(self): return self.value this is my view: def personnel(request): if not request.user.is_authenticated: return redirect('authentification') else: a = Affectation.objects.all().prefetch_related() o = Option.objects.all().prefetch_related() s = Specialite.objects.all().prefetch_related() context = { 'affectation':a, 'option':o, 'specialite':s } return render(request,'personnel/personnel.html',context) this is the html code : <div class="form-group"> <div class="row"> <div class="col"> <label for="formGroupExampleInput1">Service:</label> <select name="service" id="service" class="form-control"> <option>...</option> </select> </div> <div class="col"> <label for="formGroupExampleInput1">Specialite:</label> <select name="specialite" id="specialite" class="form-control"> {% for o in option%} <option>{{ o.value }}</option> {%endfor %} {% for s in specialite%} <option>{{ s.value }}</option> {%endfor %} … -
My templates doesn't work even I connected all the links
I downloaded free templates zip files(contact form, css,fonts, img, js, readme.txt folders included) to use django templates, then pasted main templates in home.html. I also made a directory in this "good(app)-static(folder)-good(folder)-contact form,css,fonts,img,js,readme.txt(folders)" orders.After I connected all the links that might I need, but templates still doesn't work. Can you find me what's the problem? I changed all the directory paths to make proper connection for my template. part of tag in home.html near head tag <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Maundy | Comming Soon Page</title> <meta name="description" content="Free Bootstrap Theme by BootstrapMade.com"> <meta name="keywords" content="free website templates, free bootstrap themes, free template, free bootstrap, free website template"> <link href='https://fonts.googleapis.com/css?family=Lobster|Open+Sans:400,400italic,300italic,300|Raleway:300,400,600' rel='stylesheet' type='text/css'> <link rel="stylesheet" type="text/css" href="{% static 'good/static/good/css/animate.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'good/static/good/css/bootstrap.min.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'good/static/good/css/font-awesome.min.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'good/static/good/css/style.css' %}"> <!-- ======================================================= Theme Name: Maundy Theme URL: https://bootstrapmade.com/maundy-free-coming-soon-bootstrap-theme/ Author: BootstrapMade.com Author URL: https://bootstrapmade.com ======================================================= --> </head> <body> <div class="content"> <div class="container wow fadeInUp delay-03s"> <div class="row"> <div class="logo text-center"> <img src="{% static 'good/static/good/img/banner01.jpg' %}"/> <h2>We Are Baking Something New!! Comming Soon</h2> </div> Designed by <a href="https://bootstrapmade.com/">BootstrapMade</a> </div> </div> </div> </div> </footer> <script src="{% static 'good/static/good/js/bootstrap.min.js' %}"></script> <script src="{% static … -
Can i set an external clone of my Django db?
I have a Django App with this db: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } now, i want to configure a secondo db (clone of first) on a web path. for eaxample: http://clone_db.no-ip.com how can i do? -
Django: Trying to implement a file upload progress bar
I am trying to implement a progress bar for my file upload. However, I kept on getting 405 Method not allowed error. I am very new to Ajax and jQuery so it would be great it someone can help me out. Currently my file upload class-based view is working fine. This is my class-based view: class UploadLessonView(CreateView): model = Lesson fields = ['title', 'file'] template_name = 'store/upload_lesson.html' success_url = '/' def form_valid(self, form): form.instance.post = get_object_or_404(Post, pk=self.kwargs.get('post_id')) return super(UploadLessonView, self).form_valid(form) def get_success_url(self): return reverse_lazy('lesson_uploaded', kwargs={'post_id' : self.object.post_id}) This is my html template <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"> </script> <script src="/static/store/upload.js"></script> <div id="main"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form | crispy }} <button href = "{% url 'store-home' %}" class="btn btn-secondary" type="submit" >Upload File</button> </form> </div> This is my js: $(document).ready(function() { $('form').on('submit', function(event) { event.preventDefault(); var formData = new FormData($('form')[0]); var csrftoken = $("[name=csrfmiddlewaretoken]").val(); $.ajax({ xhr : function() { var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener('progress', function(e) { if (e.lengthComputable) { console.log('Bytes Loaded: ' + e.loaded); console.log('Total Size: ' + e.total); console.log('Percentage Uploaded: ' + (e.loaded / e.total)) } }); return xhr; }, type :'post', url : '/', headers: {'X-CSRFToken': csrftoken }, data: formData, processData : false, contentType : false, success : … -
Pydub write to buffer Django and Cloudinary
I'm using pydub to slice audio. My use case is that users send long audios (.wav files) from which I only want the first 3 seconds. The .wav files come from a web client to a Django Rest Framework backend, I read (intercept the request) those files and take only the first 3 seconds. Everything works till that point with the following code: # load audio audio_data = request.data.get('sample') audio_pydub = AudioSegment.from_wav(audio_data) # Shorten audio audio_pydub_shortened = audio_pydub[:seconds_to_take] audio_pydub_shortened.duration_seconds But then I want to write the resulting file into the request data, so the request can follow it's flow, so I'm trying to do (without success): resulting_audio = audio_pydub_shortened.export(None, 'wav') request.data['sample'] = resulting_audio.read() super(request) Where resulting_audio is a TemporaryFileWrapper. The error is that the file is deleted from the request as resulting_audio.read() seems to be empty. -
HTML template doesn't see the variable passed from views
I am trying to pass a variable from views.py to my login.html template. This is my views.py from django.shortcuts import render # Create your views here. def home(request): numbers = [1, 2, 3, 4, 5] context = { 'numbers': numbers } return render(request, 'accounts/login.html', {'title': 'Login'}, context) and this is my login.html {% extends 'accounts/base.html' %} {% block content %} <h1>Welcome</h1> <h5 class="text-muted">Please log in to continue</h5> <button href="#" class="btn btn-outline-primary mt-1">Log in</button> {{ numbers }} {% endblock content %} also, this is my urls.py file inside of my application from . import views from django.urls import path urlpatterns = [ path('', views.home, name="home"), path('home/', views.home, name="home"), ] I expect the list [1, 2, 3, 4, 5] to show on login.html, when the address is localhost:8000/myappname/home -
How to fix " TypeError missing 1 required positional argument: 'on_delete' "
I am setting up my category tags for my blog, I am getting a TypeError: init() missing 1 required positional argument: 'on_delete', even though I included "on_delete=models.CASCADE". from django.db import models from django.urls import reverse from tinymce import HTMLField class CategoryTag(models.Model): title = models.CharField(max_length=150) slug = models.SlugField() parent = models.ForeignKey( 'self', on_delete=models.CASCADE, blank=True, null=True, related_name='children' ) class Meta: unique_together = ('slug', 'parent',) verbose_name_plural = "categories" def __str__(self): full_path = [self.title] k = self.parent while k is not None: full_path.append(k.title) k = k.parent return ' -> '.join(full_path[::-1]) class Post(models.Model): title = models.CharField(max_length=100) overview = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) content = HTMLField() comment_count = models.IntegerField(default=0) post_img = models.ImageField() category = models.ForeignKey('CategoryTag', null=True, blank=True) featured = models.BooleanField() slug = models.SlugField(unique=True) def __str__(self): return self.title def get_cat_list(self): k = self.category breadcrumb = ["dummy"] while k is not None: breadcrumb.append(k.slug) k = k.parent for i in range(len(breadcrumb)-1): breadcrumb[i] = '/'.join(breadcrumb[-1:i-1:-1]) return breadcrumb[-1:0:-1] def get_absolute_url(self): return reverse('post-detail', kwargs={ 'id': self.id }) I've tried to bypass by using removing the other fields (blank=True, Null=True, related_name='children') and I am still receiving the same error. -
pytz.exceptions.UnknownTimeZoneError: 'Asia/kolkata'
In my project (made in Virtual Environment), when I run the server, it gives me no errors. But when I open the 127.0.0.1:8000 , it gives me an error saying: A server error occurred. Please contact the administrator. Had referred the below post to set the timezone to 'Asia/kolkata':- How to add Indian Standard Time (IST) in Django? It worked fine till yesterday and today I got an error in prompt as: File "C:\Users\Ajay\Anaconda3\lib\site-packages\pytz\__init__.py", line 181, in timezone raise UnknownTimeZoneError(zone) pytz.exceptions.UnknownTimeZoneError: 'Asia/kolkata' How to tackle this? (Using Django V2.1) -
Django: migrating one manytomany field to another manytomany field
I need to migrate some data from class A to class B class A contains a m2m field that, say, links to auth.User This is simply migrating data over, so I add those fields from class A into class B and created migration file. I then loop through all class A objects and assign those fields for each object into class B. When it gets to the m2m field, I run into TypeError: 'ManyRelatedManager' object is not iterable class A(object): something = CharField(blehbleh) something_else = CharField(blehbleh) thing_to_migrate = models.ManyToManyField('auth.User', related_name='some_name', blank=True) class_b = models.ForeignKey('class_B_path', related_name='some_name', on_delete=models.SET_NULL) # so A.class_b gets me class B class B(object): already_exist_field = CharField(blehbleh) thing_I_want_to_migrate_here = models.ManyToManyField('auth.User', related_name='some_other_name', blank=True) related_name needs to be unique, so I set a new name there. When I modify the migration script first the def def migrate_lpinvite_to_invite(apps, schema_editor): ClassA = apps.get_model('appname', 'A') for obj in ClassA.objects.all(): obj.class_B.thing_I_want_to_migrate_here = obj.thing_to_migrate obj.save() then actual runmigration operations = [ migrations.AddField( model_name='B', name='thing_I_want_to_migrate_here', field=models.ManyToManyField(blank=True, related_name='some_other_name', to=settings.AUTH_USER_MODEL), migrations.RunPython(migrate_to_B) ] And I got the error listed above. What's the correct way to migrate related fields like this? Can I somehow refer to the through table directly and don't do this kind of data migration? -
How to change website bootstrap 4 components/contents based on user input in django
I have a Django bootstrap 4 project and I need to implement the following requirements:- show personalized content for each authenticated user based on user input via the form. if the user fills up his brand name this should show up in nav-brands only for him when he's logged in. I am planning to use Django-cms for this but not sure where to start. Any inputs regarding this?