Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Request Post URL is not working with Django
I have tried requests.post in Django but it was not working. It was fine with request.get. headers = {'Content-type': 'application/json'} answer = requests.post('http://www.testing/getdata', data = {'testing': 'testing'}, verify=False,auth=(testing,testing),headers=headers) Results: "Unexpected Error Occurred:RESTEASY008200: JSON Binding deserialization error" -
Adition of css class on widget file input has no effect
Try to add a css class into a forms.ImageField, has no effect. From model.py class ProductImages(models.Model): ... image_file_w200_png = models.ImageField( verbose_name = "Imagens", upload_to=upload_to_image_file_w200_png, null=True, blank=True, default='magickhat-profile.jpg' ) ... In forms.py class ProductImagesForm(ModelForm): image_file = forms.ImageField(widget=forms.FileInput(attrs={'class': 'image_add_product'})) class Meta: model = ProductImages fields = ['image_file_w200_png'] That code has no effect, what is missing? -
Cannot get images to load in django
I cannot get an image to load in Django by following the documentation. I have the following directory structure: And here is a snippet of my code within backend/views.py: def landing(request): template = loader.get_template(os.path.join(os.getcwd(), 'templates', 'backend', 'index.html')) context = {} return HttpResponse(template.render(context, request)) I have an HTML file within templates/backend/index.html: {% load static %} <img src="{% static 'backend/example.jpg' %}" alt="My Image"> Any idea what might be missing? -
What is the problem in this shell code (Django and sql)
I got this error in my shell code. -
"Parser must be a string or character stream, not DeferredAttribute"
I can't make a comparison, it would be more correct I can't get "date_answer" this is a DateField how can I get it correctly def get_queryset(self): n_date = parser.parse(Documents.date_answer) date = datetime.date.today() if n_date > date: messages.error(self.request, '"Дата исполнения" не выполнена') -
How to import values from database into a OptionMenu Django Python
I have a models page here. from django.db import models class Trainee(models.Model): TraineeID = models.AutoField(primary_key=True) Name = models.CharField(max_length=50) Course = models.CharField(max_length=20) BatchNo = models.CharField(max_length=15) DateofBirth = models.CharField(max_length=30) ContactNo = models.CharField(max_length=20) ContactAddress = models.CharField(max_length=80) EmailAddress = models.EmailField() class Meta(): db_table = "Trainee" class Course(models.Model): CourseID = models.AutoField(primary_key=True) CourseName = models.CharField(max_length=20) CourseDuration = models.CharField(max_length=30) CourseCost = models.CharField(max_length=50) class Meta(): db_table = "Courses" I made a html page where I can enter data and save Trainee. I want to make it so that Course will be a OptionMenu not a charfield that will have the options <select> only from the data saved in Courses table. So if there are saved data's like-Java, Python, C etc in Courses table then the option menu Course will only have these on it. And if they are deleted or new ones are added then the optionmenu will change accordingly. This is my html page where I can enter the data and save it: {% extends "MyTestApp/base.html" %} {% block body_block %} {% load static %} <link rel="stylesheet" href="{% static '/css/bootstrap.min.css'%}" /> <form method="post" action="/trainee/"> {%csrf_token%} <div class="container"> <br/> <div class="form-group row"> <label class="col-sm-1 col-form-label"></label> <div class="col-sm-4"> <h3> Enter Trainee Information </h3> </div> </div> <div class="form-group row"> <label … -
django relation between classes
Let say you have a class Project that is own by a team. One team can have many projects, but only one team for each project. class Project(models.Model): project_manager = models.ForeignKey(Profile, on_delete=CASCADE) title = models.CharField(max_length=55, null=True, blank=True) developers = models.ManyToManyField(Profile, related_name='projects') slug = models.SlugField(max_length=500, unique=True, blank=True) description = models.TextField(default="Project description") teams = models.ForeignKey(Team, blank=True, null=True, on_delete=CASCADE) Then each project has a task, so have to create a task class with a foregin key to project class Task(models.Model): title = models.CharField(max_length=55, null=True, blank=True) members = models.ManyToManyField(Profile, related_name='tasks') slug = models.SlugField(max_length=500, unique=True, blank=True) task_completed = models.BooleanField(default=False) description = models.TextField(default="Task description") project = models.ForeignKey(Project, blank=True, null=True, on_delete=CASCADE) when then trying to get all the members from the task class, while being in a view for the project class, there is no relation, project does not have access, how do one make sure project knows of Tasks as Tasks knows of project? -
Sending Django URL to javascript amend table
I am filtering a table in Django using Ajax and Javascript. After filtering and amending the table. I am trying to add that update url to the for each row in the table. function putTableData(response) { let row; $("#table_body").html(""); if (response["data"].length > 0) { $.each(response["data"], function (a, b) { row = `<tr class="hover:bg-indigo-50"> <td class="px-6 py-4 whitespace-nowrap hover:bg-indigo-50"> <div class="flex items-center"> <div class="ml-2"> <div class="text-sm leading-5 font-medium text-gray-900">${b["first_name"]} ${b["last_name"]}</div> <div class="text-sm leading-5 text-gray-500">${b["email"]}</div> </div> </div> </td> <td class="px-6 py-4 whitespace-nowrap"> <div class="text-sm text-gray-900">${b["address"]}</div> <div class="text-sm text-gray-500">${b["city"]} ${b["state"]} ${b["zipcode"]}</div> </td> <td class="px-6 py-4 whitespace-nowrap"> <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-200 text-green-800"> Active </span> </td> <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> +1${b["phone"]} </td> <td class="px-6 py-4"> <a class="p-2 mr-3 rounded" href="${b["url"]}"> </a> </td> </tr>`; $("#table_body").append(row); }); -
How to put Excel data in multiple model columns in django.?
I'm developing a shopping mall integrated management site. There is a lot of order data in one Excel file, and the data in each row of order data contains the data required for each model, so the reason the model is separated is because it has been normalized. Anyway, I want to put the data in this Excel in the field of each model. Is there a way? And I will receive the Excel file from the template through form. There are three models, and I want to insert data from one Excel file into the fields of each model.? models.py 배송요금정산코드 = ( ('정산완료','정산완료'), ('미정산','미정산'), ('취소/차감','취소/차감'), ) '''배송관리 모델''' class DEL(models.Model): del_no = models.CharField(db_column='DEL_NO', max_length=17, primary_key=True) # Field name made lowercase. ord_no = models.ForeignKey('ORD', models.DO_NOTHING, db_column='ORD_NO' ,related_name='ORD_NO_DEL',verbose_name='주문번호') # Field name made lowercase. del_wy_cd = models.CharField(db_column='DEL_WY_CD', max_length=19,verbose_name='배송방법코드') # Field name made lowercase. del_co = models.CharField(db_column='DEL_CO', max_length=20, blank=True, null=True,verbose_name='택배사') # Field name made lowercase. wb_no = models.CharField(db_column='WB_NO', unique=True, max_length=14, blank=True, null=True,verbose_name='송장번호') # Field name made lowercase. wb_dttm = models.DateTimeField(db_column='WB_DTTM', blank=True, null=True,verbose_name='송장입력일시') # Field name made lowercase. to_nm = models.CharField(db_column='TO_NM', max_length=100,verbose_name='수취인명') # Field name made lowercase. to_tel1 = models.CharField(db_column='TO_TEL1', max_length=12,verbose_name='수취인 연락처1') # Field name made lowercase. to_tel2 = models.CharField(db_column='TO_TEL2', max_length=45, blank=True, null=True,verbose_name='수취인 … -
Django find average number of followers
I have a model: class User(models.Model): followers = models.ManyToMany('users.User', related_name='following') # Other non important fields... From this I want to find BOTH: the average number of followers a user has the average number of users a user is following I have tried these respectively: User.objects.aggregate(Avg('followers'))['followers__avg'] User.objects.aggregate(Avg('following'))['following__avg'] But they are not pulling up the correct data. For example for (1) I have 3 users, one of them follows the other 2 and one of the other 2 follows the first. My code above gives 1.3333, which is not correct, it should be 1 as each there are 3 followers total (even though the first user follows 2 users he should count as 2x followers) Let me know if you need anymore examples. Thanks in advance. -
Use Django Auth User for frontent Firebase authentification
I'm using Django as my Backend REST API with MongoDB and React in my Frontend. My goal is to work with multiple Databases. MongoDB (handled over Django) and Firebase (mostly handled in Frontend over React in JSX). Currently, all my users and authentification is happening in Django with MongoDB and I want to use the already existing working user accounts to log into Firebase in the Frontend if they are logged in in Django. I found multiple resources but nearly all of them have the users and auth happening in Firebase and I need it the opposite way. My users are in Django so I need some kind of creds or auth that will be forwarded to the frontend and logged the user automatically into firebase if they're logged in into Django. I hope anyone can help me out I'm lost here been reading a lot of resources but none was matching this request. -
Django : How to position the content next to the sidebar and below a navbar
I am a newbee in Django, CSS, JS. I'm using the Sidebar and NavBar Templates from the Bootstrap and I would like to add the content of the page next to the sidebar and below the navbar. Like I saw in few tutorials, I split the html script of the sidebar and navbar, and call them in the main.html. I want to do an app where I upload files. So when I click on the "Upload File" from the sidebar, I would like that the content appears next to it, but I do not see how to do it. Here are my codes : main.html <!DOCTYPE html> <html> {% load static %} <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors"> <meta name="generator" content="Hugo 0.88.1"> <title>Sidebars · Bootstrap v5.1</title> <link rel="canonical" href="https://getbootstrap.com/docs/5.1/examples/sidebars/"> <!-- Bootstrap core CSS --> <link href="{% static 'assets/dist/css/bootstrap.min.css' %}" rel="stylesheet"> <style> .bd-placeholder-img { font-size: 1.125rem; text-anchor: middle; -webkit-user-select: none; -moz-user-select: none; user-select: none; } @media (min-width: 768px) { .bd-placeholder-img-lg { font-size: 3.5rem; } } .content{ margin-left: 1.30rem; margin-top: 20px; } </style> <!-- Custom styles for this template --> <link href="{% static 'sidebars.css' %}" rel="stylesheet"> <link href="{% static … -
Ajuda com Django, Django_Rest_Framwork e SQLITE
Bom dia! Estou precisando com urgência uma ajuda aqui. Estou tentando criar uma api com django e django_rest_framework que tenha conexão com SQLITE, eu preciso fazer uma api com o banco de dados de 2 tabelas e com dados inseridos para depois fazer a ligação, eu fiz API, só falta a parte do SQLITE mas está bem difícil eu encontrar no Google, como inserir dados, eu criei 2 tabelas no (models.py) com 1 coluna mas não sei como inserir os dados. Alguém me ajuda? models.py from django.db import models from uuid import uuid4 # Create your models here. class Regiao(models.Model): id_regiao = models.UUIDField(primary_key=True, default=uuid4, editable=False) nome = models.CharField((""), max_length=50) class Meta: db_table = 'regiao' class Fruta(models.Model): id_fruta = models.UUIDField(models.ForeignKey(Regiao, verbose_name='fruta', on_delete=models.CASCADE)) nome = models.CharField((""), max_length=10) class Meta: db_table = 'fruta' -
Django iterate over list, return seperate items in template
I'm new to django, so the solution I'm looking for is possibly very basic. However, I read what I could find about list iteration in templates, but I still can't seem to get it right. I'm working on a search function that takes a query and compares it to a list of entries ('entries'). If the query is a substring of one of the entries in the list, I want to add that entry to a list ('results'). Then, I want to print the items in the list 'results' from a template. def search(request): query = request.POST["q"] if util.get_entry(query) == None: results = ["foo", "baz"], entries = util.list_entries(), for entry in entries: if query in entry: results.append(entry) return render(request, "encyclopedia/search.html", { "title": query, "results": results, "entries": entries }) and the template: <ul> {% for result in results %} <li>{{ result }}</li> {% endfor %} </ul> <h3>For testing purposes:</h3> <ul> {% for entry in entries %} <li>{{ entry }}</li> {% endfor %} </ul> However, I can't get it to work. For testing purposes, I first tried printing the list of entries from the template. But in stead of printing the separate entries, it seems to print the full list: ['foo', 'baz'] … -
GeoDjango rendering same geometry multiple times in leaflet map
I have a GeoDjango app following this tutorial but substituting World Borders polygon data as included in the standard GeoDjango tutorial. I have created serializers and a django rest api that displays geometry intersecting the current bounding box using leaflet. The problem I've noticed is that when I pan around the map, it renders duplicate polygons on top of each other each time I set a new bounding box extent request. This results in the map slowing down as the number of polygons increases and also results in an opaque symbology. How do I ensure each polygon only renders once and not each time the map location refreshes? models.py from django.contrib.gis.db import models class WorldBorder(models.Model): # Regular Django fields corresponding to the attributes in the # world borders shapefile. name = models.CharField(max_length=50) area = models.IntegerField() pop2005 = models.IntegerField('Population 2005') fips = models.CharField('FIPS Code', max_length=2, null=True) iso2 = models.CharField('2 Digit ISO', max_length=2) iso3 = models.CharField('3 Digit ISO', max_length=3) un = models.IntegerField('United Nations Code') region = models.IntegerField('Region Code') subregion = models.IntegerField('Sub-Region Code') lon = models.FloatField() lat = models.FloatField() # GeoDjango-specific: a geometry field (MultiPolygonField) mpoly = models.MultiPolygonField() # Returns the string representation of the model. def __str__(self): return self.name class Meta: ordering … -
Django DeserializedObject update
I have a dynamically loaded object from a json file. As per documentation, I can save the object in this way: for deserialized_object in serializers.deserialize("json", data): if object_should_be_saved(deserialized_object): deserialized_object.save() However, if the object already exists in the datadatabase, I quite rightly get the django.db.utils.IntegrityError: duplicate key value violates unique constraint . I can't see anything in the docs that would allow to do a deserialized_object.update() instead of a deserialized_object.save(). Is that possible? -
Wagtail embedding images with HTML
We use StreamField to allow editors to add HTML for custom layouts. We used to be able include images in by looking up the ID of the Image and an embed code: <embed alt="My Image" embedtype="image" format="responsive" id="3896"/> Since performing an update to Wagtail these do not render. I'm wondering if this was an unintended feature which has been removed or if something about this code has changed. -
How I can send Ajax data in Django website?
Could you please share the tutorials also this section. I need to improve the my coding skills -
How to change plain message into html message in django?
I'm getting string representation of html code in email.. How can i get proper html email ? message1 = (subject, 'Here is the message', from_email, recipient_list) message2 = (subject, html_message, from_email, recipient_list) message2.content_subtype = "html" send_mass_mail((message1, message2), fail_silently=False) -
How to find which channel sent a particular message in Django channels + Websocket api?
I am implementing a broadcaster using Django channels i.e, i am implementing a group of channels where a message sent from a single consumer instance associated with a channel will be sent to all other instances that have their associated channels registered in that group. I am using the template as following: <!-- {% load static %} --> <!DOCTYPE html> <html lang="en"> <head> <title>Messages</title> <!-- <link href="{% static 'hello/styles.css' %}" rel="stylesheet"> --> </head> <body> <textarea name="" id="chat-log" cols="100" rows="20"></textarea><br> <input type="text" id="chat-message-input" size="100"><br> <input type="button" value="send" id="chat-message-submit"> <script> var ws = new WebSocket('ws://127.0.0.1:8000/ws/sc/') ws.onopen = function(){ console.log('Websocket connection open....', event) } ws.onmessage = function(event){ const messageTextDom = document.getElementById('chat-log') messageTextDom.value += JSON.parse(event['data']).msg + '\n' console.log('Message Recieved From Serever...', event) } ws.onerror = function(event){ console.log('Message Error Occured...', event) } ws.onclose = function(event){ console.log('Webdsocket connection closed..', event) } document.getElementById('chat-message-submit').onclick = function(event){ const messageInputDom = document.getElementById('chat-message-input') const message = messageInputDom.value ws.send(JSON.stringify({ 'msg': message })) messageInputDom.value = '' } </script> </body> </html> and have setup the group and message sending utility on the backend as: from channels.generic.websocket import SyncConsumer from asgiref.sync import async_to_sync from channels.exceptions import StopConsumer class TestConsumer(SyncConsumer): def websocket_connect(self, event): async_to_sync(self.channel_layer.group_add)('programmers', self.channel_name) self.send({ 'type': 'websocket.accept' }) def websocket_receive(self, event): async_to_sync(self.channel_layer.group_send)('programmers', { 'type': 'chat_message', … -
Where is my "raw data & HTML form" option in django rest api?
Hellow developers, I started using django rest framework, but I am not able to see raw data/ HTML form options in my post request user interface. My dhango and rest framework versions are latest. The whole API works fine when I insert the data as json inside the content textarea, but I would like to have another options as well. -
Django url not cannot find some UTF-8 usernames
i am experimenting with UTF-8 for usernames in a django app. Django is Version 3.2.11 Python used is 3.9.4 Some users might have a profile visible to others and ther username in the url: re_path("^u/(?P<username>\w+)/$", views.author_profile_view, name="author_profile_view"), Normal Example works fine: Browser shows -> /u/brainyChowder3/ Django shows -> GET /u/brainyChowder3/ HTTP/1.1" 200 10593 UTF-8 example 1 works also fine: Browser shows -> /u/ɊȁⱲÒđΈⱦİĬd/ Django shows -> GET /u/%C9%8A%C8%81%E2%B1%B2%C3%92%C4%91%CE%88%E2%B1%A6%C4%B0%C4%ACd/ HTTP/1.1" 200 12508 But this UTF-8 does not work: Browser shows -> /u/ɂáⱳ1⁄4%7Cĭğę Django shows -> "GET /u/%C9%82%C3%A1%E2%B1%B31%E2%81%844%7C%C4%AD%C4%9F%C4%99 HTTP/1.1" 404 5585 The browser does show it strange, as he does not "translate" %7C to |, but that should be just optical? Error shown is just Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/u/%C9%82%C3%A1%E2%B1%B31%E2%81%844%7C%C4%AD%C4%9F%C4%99 The current path, u/ɂáⱳ1⁄4|ĭğę, didn’t match any of these. In Django shell I can query this user: >>> User.objects.get(username='ɂáⱳ1⁄4|ĭğę') <User: ɂáⱳ1⁄4|ĭğę> The URI decoding looks ok to me. I hope someone can explain why this is happening to one UTF-8 string, but not the other. Or maybe even knows how to fix it? :-D I know it may not be the smartes thing to allow all UTF-8 for usernames, but this is more an experiment for me. … -
How do I pass Django local variable of a funtion in views to javascript fetch API?
I am all new to javascript. I am making a like button that will increase the number of likes of a post asynchronously without reloading the whole page. Following is my Django views function. views.py @login_required def likepost(request,id): post = NewPost.objects.get(id = id) is_like = False for like in post.likepost.all(): if like == request.user and request.method == "POST": is_like = True break if not is_like: post.likepost.add(request.user) else: post.likepost.remove(request.user) return JsonResponse({ "id" : id, "is_like" : is_like, "num_like" : post.likepost.count() }) Here id is the primary key of NewPost model. My javascript will fetch an API using this id variable. Here is my js function. document.addEventListener("DOMContentLoaded",function(){ document.querySelector('#like').addEventListener('click', ()=> like_function()); }) function like_function(){ fetch(`index/${id}/like`) .then(response => response.json()) .then(result => { if(result.is_like){ document.querySelector('#like').innerHTML = "Like"; } else{ document.querySelector('#like').innerHTML = "Unlike"; } }) } <button onclick="like_function()" id = "like" class="btn btn-link"><i class="fa fa-heart"></i> </button> <small id="num_of_likes">{{ posts.likepost.all.count }}</small> {% block script %} <script src="{% static 'network/controller.js' %}"></script> {% endblock %} <button class="btn btn-link" style="text-decoration: none;">Comment</button> <a href="{% url 'postpage' id=posts.id %}" class="btn btn-link" style="text-decoration: none;">View Post</a> Here, I've shared my javascript function as well as my HTML template. If I click the like button following message appears. What should I do now? -
RegisterSerializer WARNING:django.request:Bad Request:
Hi I override my User and now i create app connect Django Forms and Django DRF with model. And i have bad POST in serializer and i dont know why its not work, Its happend when i change image in project using Model but dont know why. I'm using swagger drf to POST.I'm using default when avatar == None and use link when no. class CreateUserManager(BaseUserManager): def _create_user(self, email, password, date_of_birth, is_verified, is_admin, is_superuser, **extra_fields): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), date_of_birth=date_of_birth, **extra_fields ) user.is_admin = is_admin user.is_verified = is_verified user.is_superuser = is_superuser user.set_password(password) user.save(using=self._db) return user def create_user( self, email, password, date_of_birth, is_verified=False, is_admin=False, is_superuser=False, **extra_fields): return self._create_user(email, password, date_of_birth, is_verified, is_admin, is_superuser, **extra_fields) def create_superuser( self, email, password, date_of_birth, is_verified=True, is_admin=True, is_superuser=True, **extra_fields): return self._create_user(email, password, date_of_birth, is_verified, is_admin, is_superuser, **extra_fields) class CreateUser(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=150, blank=True) last_name = models.CharField(max_length=150, blank=True) date_of_birth = models.DateField(blank=True, validators=[validate_date_of_birth]) date_joined = models.DateTimeField(blank=False, default=timezone.now) username = models.CharField(max_length=150, blank=True) email = models.EmailField(max_length=150, blank=False, unique=True) is_active = models.BooleanField(default=True) is_verified = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) avatar = models.ImageField(default='./default/accounts/user/default_user.png', blank=True, upload_to='./images/accounts/user/', validators=[validate_image, validate_exist_image]) password = models.CharField(max_length=120, blank=False, validators=[validate_password]) objects = CreateUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['date_of_birth'] def … -
getting wrong slug when trying to return to last page
Trying to create a function to return to last page, but slug is wrong and i cannot seem to get the correct slug. models.py class Checklist(models.Model): title = models.CharField(max_length=55) slug = models.SlugField(max_length=500, unique=True, blank=True) due_date = models.DateTimeField() check_completed = models.BooleanField(default=False) notes = models.ManyToManyField(Note, blank=True) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Checklist, self).save(*args, **kwargs) def get_url(self): return reverse('task_detail', kwargs={ 'slug':self.slug }) def return_url(self): return reverse('project_detail', kwargs={ 'slug':self.slug }) def __str__(self): return self.title @property def last_comment(self): return self.notes.latest("date") class Task(models.Model): title = models.CharField(max_length=55, null=True, blank=True) slug = models.SlugField(max_length=500, unique=True, blank=True) task_completed = models.BooleanField(default=False) description = models.TextField(default="Task description") start_date = models.DateTimeField() due_date = models.DateTimeField() checklist = models.ManyToManyField(Checklist, blank=True) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Task, self).save(*args, **kwargs) def __str__(self): return self.title @property def num_checklists(self): return self.checklist.count() @property def num_checklist_completed(self): return self.checklist.filter(check_completed = True).count() class Project(models.Model): project_manager = models.ForeignKey(Profile, on_delete=CASCADE) title = models.CharField(max_length=55, null=True, blank=True) developers = models.ManyToManyField(Profile, related_name='projects') slug = models.SlugField(max_length=500, unique=True, blank=True) description = models.TextField(default="Project description") date = models.DateTimeField(auto_now_add=True) start_date = models.DateTimeField() due_date = models.DateTimeField() tasks = models.ManyToManyField(Task, blank=True) teams = models.ManyToManyField(Team, blank=True) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Project, self).save(*args, **kwargs) def get_url(self): return reverse('project_detail', kwargs={ 'slug':self.slug }) def …