Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am having problem in sending data of a select box in a django project
This is my cart.js: var updateBtns = document.getElementsByClassName('update-cart') for (i=0;i<updateBtns.length;i++){ updateBtns[i].addEventListener('click',function(){ var productId=this.dataset.product var action=this.dataset.action console.log('productId:',productId,'Action:',action) console.log('user:',user) updateUserOrder(productId, action) }) } function updateUserOrder(productId,action){ console.log('User is logged In , sending data....') var url = "/update_item/" fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'productId':productId,'action':action}) }) .then((response) =>{ return response.json() }) .then((data) =>{ console.log('data:',data) location.reload() }) } and this is my button: <button data-product={{product.id}} data-action="remove" class="flex-c-m sizefull bg1 bo-rad-23 hov1 s-text1 trans-0-4 update-cart"> Added<sub>Remove</sub> </button> I want to apply similar kind of attributes to this selectbox: <select class="selection-2" name="size" required id="sizebox"> {% for t in product.size.all %} <option value="{{t}}" id="{{t}}">{{t}}</option> {% endfor %} </select> I want to give it attributes like such that I can use javascript to send its data to my views.py: def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] I tried fetching the selected option value and in my views.py I did size=data['size'] but got an key error. What should be the best way to send the size?any help would be appreciated.Thanks -
NoReverseMatch at /. Reverse for 'topic' with arguments '('',)' not found
I'm doing Django tutorial that creates a website that keeps a journal. When I run my website, I found this error: NoReverseMatch at /topics/ Reverse for 'topic' with arguments '('',)' not found. 1 pattern(s) tried: ['topics/(?P<topic_id>[0-9]+)/$'] The code usually works well This is my link to the page: <a href="{%url 'learning_logs:topics' %}">Topics</a> This is my url patterns: # Page that shows all topics path('topics/', views.topics, name='topics'), # Page that shows individual topic path('topics/<int:topic_id>/', views.topic, name='topic') The link should be matched with path('topics/', views.topics, name='topics') , but from the error message django tried to match it with path('topics/<int:topic_id>/', views.topic, name='topic') This is my view: def topics(request): """Provide all topics""" topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) This is my template: {% extends "learning_logs/base.html" %} {% block content %} <p>Topics</p> <ul> {% for topic in topics %} <li> <a href="{% url 'learning_logs:topic' topic.id %}">{{ topic }}</a> </li> {% empty %} <p>No topic have been added yet.</p> {% endfor %} </ul> <a href="{% url 'learning_logs:new_topic' %}">Add a New Topic</a> {% endblock content %} The code isn't working since I wrote my last code. And the last code doesn't influence this link/page. This is my last code: #Page for adding … -
django rest framwork on post not intended QueryDict
I am using Django rest framework on an IIS server and it is not clear for me why the: request.data return the following: { "_content_type": "application/json", "_content": "{\r\n \"source_name\": \"None\",\r\n \"dest_name\": \"reza\",\r\n \"source_num\": \"12\",\r\n \"dest_num\": \"15\",\r\n \"amount\": 500\r\n}" } in response to the following post: { "source_name": "None", "dest_name": "reza", "source_num": "12", "dest_num": "15", "amount": 500 } while, as i know, it should be a QueryDict with only the body information, not a QueryDict with a key: value '_content': with the of type unicode. It should be noted that i get the proper results in local and i have seen the following: https://github.com/encode/django-rest-framework/issues/3623 -
Django, csv file with non-ascii text not readable in windows excel file
Below are my current code (and I tried BOM_UTF8 too) csv = df.to_csv(index=False, encoding='utf-16-le', date_format='%Y%m%d %H:%M %p') filename = 'order.csv' response = HttpResponse(content_type='text/csv', charset='utf-16-le') response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename) response.write(codecs.BOM_UTF16_LE) response.write(csv) return response Non ascii characters are all broken in windows excel. Very interesting.. frustrating not being able to solve this fast in 2020.. -
How to create a file in django app to create instances of model and save in database
I am trying to create instances of a model in a seprate .py file in my django app directory. I know I can do this in admin site as well as in the shell, views.py, models.py, however i would like to do this with a file that i have created to solely deal with creating instances. I created a createBook.py file to create instances of class Book from models. When i save the object nothing shows up on my database i.e. it didnt add anything to the database. -
How to ccess elements of list in accessor
I have two data models, company and contact_person. They are linked in a m2m variant: models.py: class ContactPerson(models.Model): name = models.CharField('first name', max_length=120) @property def contact_name(self): return [self.name, self.id] class Customer(models.Model): name = models.CharField('company name', max_length=120) contact_persons = models.ManyToManyField(ContactPerson, blank=True, null=True) @property def contacts(self): persons = [] for c in self.contact_persons.all(): persons.append({"name": c.contact_name[0], "id": c.contact_name[1]}) return persons tables.py: class CustomerTable(django_tables2.Table): name = django_tables2.LinkColumn("customer-detail", args=[django_tables2.A("pk")]) contacts = django_tables2.LinkColumn("contact-detail", args="contacts__id", accessor="contacts__name", verbose_name="contacts") class Meta: model = Customer sequence = ("name", "contacts") What I want is that every name is linked to it's contact detail, but I am addressing the content of the accessor wrong, therefore get an empty table row. Is my method with creating a list wrong [{"name": "Bart", "id": 1}, {"name": "Rita", "id": 7},] or did I just read the docs wrong on how to access that list? views.py: class CustomerListView(SingleTableView): model = Customer context_object_name = 'customer' table_class = CustomerTable template_name = "customerlist.html" def get_queryset(self): qs = super(CustomerListView, self).get_queryset() return list(qs) -
Cannot perform makemigrations in Django. Getting error OSError: /usr/gdal23/lib/libgdal.so.20: undefined symbol: sqlite3_column_table_name
I would like to use django-geojson library, but when I add it to INSTALLED_APPS in the settings.py file I get the following error when I try to perform python manage.py makemigrations: OSError: /usr/gdal23/lib/libgdal.so.20: undefined symbol: sqlite3_column_table_name I found several similar posts (here or here) but all of them refer to anaconda specific settings, but I don't use anaconda. What can I do? -
Django model not working through admin interface
Iam working on a auction site using django project. i have a model for placing bid. i have registered the model in admin.py , but when i try to place bid from admin interface it is not updating in the main website page.But through website the bid is updating perfectly and other models are working perfectly. This is my models.py from django.contrib.auth.models import AbstractUser from datetime import datetime from django.db import models CHOICES = ( ('fashion','Fashion'), ('tools', 'Tools'), ('toys','Toys'), ('electronics','Electronics'), ('home accesories','Home accessories'), ('books','Books'), ) class User(AbstractUser): pass class Bid(models.Model): user = models.CharField(max_length=64) title = models.CharField(max_length=64) listingid = models.IntegerField() bid = models.IntegerField() class Listing(models.Model): owner = models.CharField(max_length=64) title = models.CharField(max_length=64) description = models.TextField() price = models.IntegerField() category = models.CharField(max_length=64, choices=CHOICES, default='fashion') link = models.CharField(max_length=10000,default=None,blank=True,null=True) time = models.CharField(max_length=64, default= datetime.now().strftime(" %d %B %Y %X ")) class Comment(models.Model): user = models.CharField(max_length=64) time = models.CharField(max_length=64, default= datetime.now().strftime(" %d %B %Y %X ")) comment = models.TextField() listingid = models.IntegerField() This is my admin.py from django.contrib import admin from .models import User, Listing, Bid, Comment # Register your models here. admin.site.register(Bid) admin.site.register(User) admin.site.register(Listing) admin.site.register(Comment) This is the function for bidsubmit in views.py(i have imported Bid model in this file) def bidsubmit(request,listingid): current_bid = Listing.objects.get(id=listingid) current_bid … -
Django Rest Framework: how to use OperationHolderMixin?
In the source code of Django Rest Frameworksite-packages/rest_framework/permissions.py, I can see OperationHolderMixin class, and children classes AND, OR and NOT. There's nothing about it in the documentation and I didn't find a sample of a use case. Has anybody ever used those "compositing" classes, and when should I use them? -
Cant use navigation bar on multiple pages in django templates
I hav a navigation bar in my django template and thats not fully static,in fact it consumes chunk of data from backend so it must be rendered/loaded from a views.py fuction.The code for the navigation bar is quite large(python) to be injected to every other view function.so how can i make my navbar available for multiple pages?? -
Adding tags to wagtail email form submissions
in order to be able to automatically use the email send by the wagtail email form, i need to put some tags in front of the generated lines. So in short, a line inside the email should look like this: "#Start# descr: somethingsomething. #Ende#". I managed to add a "start_tag" and a "end_tag" field to the wagtail "form creator" but now i get a error when i try to load the form page. Take a look at my admin form editor. Take a look at the error I changed wagtail/contrib/forms/models.py (Basically i added start_tag and end_tag as charFields and added them to the panel. And hopefully added them correctly to the send_email funtion) import json import os from django.core.serializers.json import DjangoJSONEncoder from django.db import models from django.template.response import TemplateResponse from django.utils.text import slugify from django.utils.translation import gettext_lazy as _ from unidecode import unidecode from wagtail.admin.edit_handlers import FieldPanel from wagtail.admin.mail import send_mail from wagtail.core.models import Orderable, Page from .forms import FormBuilder, WagtailAdminFormPageForm FORM_FIELD_CHOICES = ( ('singleline', _('Single line text')), ('multiline', _('Multi-line text')), ('email', _('Email')), ('number', _('Number')), ('url', _('URL')), ('checkbox', _('Checkbox')), ('checkboxes', _('Checkboxes')), ('dropdown', _('Drop down')), ('multiselect', _('Multiple select')), ('radio', _('Radio buttons')), ('date', _('Date')), ('datetime', _('Date/time')), ('hidden', _('Hidden field')), ) class AbstractFormSubmission(models.Model): … -
Selenium giving excepion with Django
I am working on a Django project in which I need to fetch some data from an api when I receive a request. I created a simple script to check if it worked and it did. But when I did the same inside a Django view I get this exception I wanted this to be a task running in background so I used celery but had no luck and faced the same issue. -
Getting FieldError for MultipleChoiceField in Django rest framework
I am trying to use MultipleChoiceField from django Rest Framework fields as described in this link: https://pypi.org/project/django-multiselectfield/ A part of my code snippet is as below: from rest_framework import fields CHOICES = ( ('publisher', 'Can Publish programs'), ('author', 'Can author programs') ) class User(AbstractUser): email = EmailField(verbose_name=_('email address'), unique=True) edumap_roles = fields.MultipleChoiceField(choices=CHOICES, allow_blank=True) But on admin console I see these fields like, instead of string items: But when I click on email_addres to see user details, I get following error: My rest framework version is: 3.11.0. Am I missing to add anything? -
Django create returns 500 for a value with "/"
I am trying to create an object in django. But it returns the item is not iterable. It works for everything except value having "(iphone5,1; iPhone OS 18A001) Safari/20.23.93" Parameter.objects.create(**fields > The errors looks like "Error while adding parameters…" > > 'Parameter' object is not iterable---in— Any idea about this? -
JSONDecodeError("Expecting value", s, err.value)
I'm getting this error message and I'm really confused what is it about. My error is: raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) This is my source code: import sys import json import pandas from simple_salesforce import Salesforce, SalesforceLogin, SFType loginInfo = json.load(open('login.json')) username = loginInfo['username'] password = loginInfo['password'] security_token = loginInfo['security_token'] domain = 'login' sf = Salesforce(username=username, password=password, security_token=security_token, domain=domain) -
generating zip file in django
My zip file is not opening after downloading. It has 100 kb of size but still not able to open. import zipfile import io list = [[accounts],[marketing]] for sublist in list: output_buffer = io.StringIO() writer = csv.writer(output_buffer) for dept in sublist: files = '/home/employess_details/'+ dept +'.csv' if os.path.isfile(file): with open(file, 'r') as data: csv_reader = csv.reader(data) for rows in csv_reader: writer.writerow(rows) zipped = io.BytesIO() output_buffer.seek(0) with zipfile.ZipFile(zipped, 'a') as c: c.writestr(file, output_buffer.read()) zipped.seek(0) response = HttpResponse(zipped, content_type='application/octet-stream') response['Content-Disposition'] = 'attachment; filename=employess_details.zip' return response -
how to use {{ value }} to for loop
I'd like to work with the value of {{value}} returned from the template as a query statement. How can use {{value}} to use for loop for show the desired image repeatedly by value? templates.html {% for list in today_list.today_list_items %} <div class="today_list_item"> <span>{{ list.title }}</span> {% for rating_num in {{ list.rating }} %} <img src="static/quokka.jpg"> {% endfor %} </div> {% endfor %} views.py class CalendarView(generic.ListView): model = Event template_name = 'cal/calendar.html' context_object_name = 'today_list' # today_list에는 오늘 등록한 객체들이 포함됨 def get_queryset(self, **kwargs): queryset = { 'today_list_items': Event.objects.all().filter(profile=self.request.user.user_profile).filter(start_time__date=date.today()), 'today_list_rating_sum': Event.objects.all().filter(profile=self.request.user.user_profile).filter(start_time__date=date.today()).aggregate(Sum('rating')).values() } return queryset models.py class Event(models.Model): title = models.CharField(max_length=200) start_time = models.DateTimeField(default=timezone.now, blank=True) profile=models.ForeignKey(Profile, related_name='event',on_delete=models.CASCADE) rating = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)], blank=True, default='enter your value') def __str__(self): return '{}/ {}/ {}'.format(self.id, self.title, self.start_time, self.rating) -
Can I have template tag inside template tag in Django?
So first, of all, I have data that looks like this: [{'1' : 'book'}, {'2' : 'play'}, {'3' : 'drink'}, ...]. And I tried to parse 'book', 'play', and 'drink' with each key in Django template. Let me show you my code. views.py def mainPage(request): categoryList = [{'1' : 'book'}, {'2' : 'play'}, {'3' : 'drink'}, ...] categoryLength = len(categoryList) ... context = { 'categoryList' : categoryList, 'range' : range(1, categoryLength+1) } return render(request, 'main.html', context) main.html ... {% for int in range %} <button class="dropdown-item" id="cat-{{int}}">{{categoryList.int}}</button> {% endfor %} ... But as you can imagine, I get error in the {{categoryList.int}} part. As mentioned, I'm trying to parse book, play, and drink in order. How do I do this? Thank you very much. -
How to draw e-signature in PDF using ReportLab
Have got the e-signature raw data using HTML5 canvas, how to draw the signature in the PDF file using ReportLab? The e-signature raw data looks like: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAf4AAACWCAYAAAA/v+qmAAAYd0lEQVR4Xu2dT4wsuV3Hq7p7ejaw+ceGA7zRTHfNBsQK0OaEtLkgkIATJAqIPwcOXEACBByQ4AgXEBc4BCmcQELij4hgJU6shNgc2GsCQQgt01X9RjMIsZvw3m6ifdMz04U8dI9q6pXLdpVddrc/c0n2dZX98+f3K3/9s12uNOEPAhCAAAQgAIFoCKTRtJSGQgACEIAABCCQIPwEAQQgAAEIQCAiAgh/RM6mqRCAAAQgAAGEnxiAAAQgAAEIREQA4Y/I2TQVAhCAAAQggPATAxCAAAQgAIGICCD8ETmbpkIAAhCAAAQQfmIAAhCAAAQgEBEBhD8iZ9NUCEAAAhCAAMJPDEAAAhCAAAQiIoDwR+RsmgoBCEAAAhBA+IkBCEAAAhCAQEQEEP6InE1TIQABCEAAAgg/MQABCEAAAhCIiADCH5GzaSoEIAABCEAA4ScGIAABCEAAAhERQPgjcjZNhQAEIAABCCD8xAAEIAABCEAgIgIIf0TOpqkQgAAEIAABhJ8YgAAEIAABCEREAOGPyNk0FQIQgAAEIIDwEwMQgAAEIAC ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... WLU5HKOMOOVkMAAhCAgC8C8/n8n9I0/cFq/ev1+lPL5fIrvmzaaeFXbeLjMB7fYUX9EIAABOIlkGXZrydJ8oc1Ar+R57lY7/f+t3MZf9t6vjiM5+Dg4Nvffvvtd72TxQAIQAACEIiOwGw2e3U0Gomz+O//0jT90mKxeJD9+wSzU8Lftp7PBj6fYUTdEIAABCAgCGRZJkT/1QqNp+v1erZcLp+EQmhnhL9N9NnAF0o4YQcEIACBuAlsdvL/WZIkHxUk0jT97GKxeD0kKjsj/E2b+cTU/snJycGbb755ExJUbIEABCAAgXgJiB394/H4dfHqXp7nYr0/qL+dEX5Brbqpj6n9oOIIYyAAAQhAoEZADABCmuLfmrdTwi+MFpv7VqvV6vLy8gWiDAIQgAAEIAABMwI7J/xmzeNqCEAAAhCAAASqBBB+4gECEIAABCAQEQGEPyJn01QIQAACEIAAwk8MQAACEIAABCIigPBH5GyaCgEIQAACEED4iQEIQAACEIBARAQQ/oicTVMhAAEIQAACCD8xAAEIQAACEIiIAMIfkbNpKgQgAAEIQADhJwYgAAEIQAACERFA+CNyNk2FAAQgAAEIIPzEAAQgAAEIQCAiAgh/RM6mqRCAAAQgAAGEnxiAAAQgAAEIREQA4Y/I2TQVAhCAAAQggPATAxCAAAQgAIGICCD8ETmbpkIAAhCAAAQQfmIAAhCAAAQgEBEBhD8iZ9NUCEAAAhCAAMJPDEAAAhCAAAQiIvB/pBqreADY5PwAAAAASUVORK5CYII= -
How to decode an image in django request for classification in a tf model
I'm trying to classify an image in a tf model. Here is what I'm doing: views.py def make_prediction(tensor, model='MOB'): tf.keras.backend.reset_uids() folders = {'VGG': 'vgg', 'MOB': 'mobilenet', 'CNN': 'cnn3'} model_as_json = 'upload_images/model/%s/modelo.json' % (folders[model]) weights = 'upload_images/model/%s/modelo.h5' % (folders[model]) json_file = open(model_as_json, 'r') loaded_json_model = json_file.read() json_file.close() model = tf.keras.models.model_from_json(loaded_json_model) model.load_weights(weights) return model.predict(tensor) def upload_image_view(request): message = '' status = '' prediction = -1 if request.method == 'POST': form = forms.UploadImageForm(request.POST, request.FILES) if form.is_valid(): m = form.save(commit=False) # try: image = tf.io.decode_image(request.FILES['image'].read(), channels=3) image = tf.image.convert_image_dtype(image, tf.float32) image = tf.image.resize(image, size=[224, 224]) tensor = tf.constant(image) pred = make_prediction(tensor, form.cleaned_data['predicted_with'])[0][0] if pred > 0.5: # continue... The image uploaded by user is send to Azure Storage, so I can't get image path to perform the preprocessing and classification. When I was working with local images, I could access the image by m.image.path but now I cant do that. So the way I'm showing above it's how I can access the image information to decode, resize and convert to tensor, but I'm getting this error: ValueError: Input 0 of layer Conv1_pad is incompatible with the layer: expected ndim=4, found ndim=3. Full shape received: [32, 224, 3] How can I fix this? -
How can you add to a ManyToManyField extension of the default Django User model?
For my app, I want to add one extra ManyToManyField to the default User model (django.contrib.auth.models.User). This extra field is called 'favorites' and the posts favorited by a user should go there. This is what I have: class Favorite(models.Model): user = models.OneToOneField(User, related_name='favorites', on_delete=models.CASCADE) favorites = models.ManyToManyField(Recipe, related_name='favorited_by') This is what I get when trying to add to 'favorites' from the shell. # imported Recipe, Favorite, User(default) >>> recipe1 = Recipe.objects.all()[0] >>> me = User.objects.all()[0] >>> me.favorites.add(recipe1) django.contrib.auth.models.User.favorites.RelatedObjectDoesNotExist: User has no favorites. # Just checking if the the User object, me, has a 'favorites' attribute >>> 'favorites' in dir(me) True What is the correct way to add a Recipe object to this 'favorites' field? For more reference, I did something similar how I handled Friendships between users, but it was a bit simpler since I wasn't extending the User model. The code for that is below and works fine: class Friend(models.Model): users = models.ManyToManyField(User) current_user = models.ForeignKey(User, related_name='owner', null=True, on_delete=models.CASCADE) @classmethod def make_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create( current_user=current_user ) friend.users.add(new_friend) @classmethod def lose_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create( current_user=current_user ) friend.users.remove(new_friend) -
How do I get all the rows in the third table by accessing the transit (foreign keys)?
Good morning! There is a model like: class A( models.Model ): field = models.CharField() class B( models.Model ): a = models.ForeignKey( A, on_delete = models.CASCADE, related_name = 'a_b_a' ) class C( models.Model ): b = models.ForeignKey( B, on_delete = models.CASCADE, related_name = 'b_c_b' ) Referring to table "A": c_all = A.objects.all() I need to somehow add a query so that all rows from table "C" are pulled. Table "B" can have multiple rows referring to "A", similarly, table "C" can have multiple rows referring to any row in "B". -
django rest auth user is not being updated with put or patch method
I am using django-rest-auth as an API for handling accounts and I have React in the frontend. I have successfully retrieved data from 'rest-auth/user' using the token and stuffs. However, when I use "PUT" method or "PATCH" method to update the data of first_name, last_name, and username, the data are not being updated yet no error was returned. In the console, the promiseStatus was 'fulfilled' and the promiseValue returned an object of those values without being updated. const updateData = (e) => { e.preventDefault(); const csrftoken = getCookie("csrf"); const cookies = new Cookies(); const url = "http://localhost:8000/rest-auth/user/"; setIsLoading(true); fetch(url, { method: "PATCH", headers: { "Content-Type": "application/x-www-form-urlencoded", Authorization: "Token " + cookies.get("token"), "X-CSRFToken": csrftoken, }, body: JSON.stringify({ username: username, first_name: firstName, last_name: lastName, }), }).then((response) => console.log("THE RESPONSE: ", response.json())); setIsLoading(false); }; -
Django Backend loop to a frontend list
Sorry for the question, but I'm begginer in Django and I don't find any topic like this case. This is the code: views.py def select_collections(request): listacolecao = Collection.objects.order_by('upload_date') listasubscription = Subscription.objects.filter(user=request.user) for obj in listacolecao: try: Subscription.objects.filter(user=request.user, collection=obj) except Subscription.DoesNotExist: print('not exist') else: print('Ok') It prints this result in terminal: not exist not exist Ok not exist Ok Ok Ok Ok I know that isn't a list, but I need to put it result into a template. How can I do that? Thank -
how covert function to listview
This is my code, I use django v3 and want convert the category functions in views.py to a list class(ListView) for use pagination. How can do it? Thank you alot urls.py from django.urls import path from .views import posts_category urlpatterns = [ path('<slug:slug>/', posts_category, name="posts_category"), ] model.py class Category(models.Model): parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) title = models.CharField(max_length=70, unique=True) slug = models.SlugField(max_length=90, unique=True) description = RichTextUploadingField(blank=True, null=True) image = models.ImageField(blank=True, upload_to="imgs") def __str__(self): return self.title class MPTTMeta: order_insertion_by = ['title'] views.py def posts_category(request, slug): category = Category.objects.all() post = Posts.objects.filter(category__slug=slug, status="p") context = { 'category': category, 'post': post, } return render(request, 'posts_category.html', context)