Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Automatically check a directory in Django and read the file only once
How do I write a program in Django that always checks a specific directory? If a file is added, it only reads it once and does not read it again? The following program is inside a Python app and I do not know how to write like this inside Django and it reads directory files every 5 seconds. I want to read it once and after 5 seconds a new file was added to read it def uptime_bot(path_root): postfix_json = os.path.join(path_root, '*.json') postfix_csv = os.path.join(path_root, '*.csv') while True: try: if postfix_json: for filename in glob.glob(postfix_json): with open(filename) as file: file_data = json.load(file) for key, val in file_data.items(): for i, doc in enumerate(file_data[key]): print(doc) print(Collection.insert_one(doc)) if postfix_csv: for filename in glob.glob(postfix_csv): with open(filename) as file1: content = [] df = pd.read_csv(filename, index_col=None) content.append(df) data_frame = pd.concat(content) data = [] headlist = [] final_result = [] for index, row in enumerate(data_frame): headlist.append(row) for index, row in enumerate(data_frame.values): res = {} for i in range(len(headlist)): res.update({headlist[i]: row[i]}) final_result.append(res) print(final_result) print(Collection.insert_many(final_result)) except: print('Error:Some json file data is duplicate!') time.sleep(5) path_root = 'Data/js' uptime_bot(path_root) -
Djagno and ElasticSearch how to allow search with typos
I'm fairly new to elastic search and I want to enable searching with typos (max of 2 letters) example input: gpple result: google ///////////// input: convarsetyon (3 letters typos, meant to be : conversation ) result: none my backend is Django and the way i communicate with elastic search is via elasticsearch-dsl I tried to implement add fuzziness attribute to the wildcard query but it resulted in an error views.py: class SearchRecipes(ListAPIView): serializer_class = RecipeSearchSerializer def get_queryset(self, *args, **kwargs): word = self.kwargs['word'] recipeQueryset = RecipeDocument.search().query('wildcard',title=f'*{word}*').sort("-score") return recipeQueryset documents.py autocomplete_analyzer = analyzer('autocomplete_analyzer', tokenizer=tokenizer('trigram', 'edge_ngram', min_gram=1, max_gram=20), filter=['lowercase'] ) @registry.register_document class RecipeDocument(Document): title = fields.TextField(required=True, analyzer=autocomplete_analyzer) class Index: name = 'recipes' settings = { 'number_of_shards': 1, 'number_of_replicas': 0, 'max_ngram_diff': 20 } class Django: model = Recipe fields = [ 'score', ] Anyone have a clue how to do this? thanks in advance -
How to add CSP for Django CKEditor
I'm not using CDN or any link for CKEditor but I have PIP installed it using pip install django-ckeditor. I have added all necessary CSPs and CKEditor configurations in settings.py file but CKEditor is not working in html. Please help me fix it. -
C# developer switching to Python
I've been working with .NET for the last 10 years. Recently I switched to a new company that is using Python. I'm looking for a book or web series that can explain the intent of Pythons designer as well as the inner workings of the language. Something along the lines of C# in depth by Jon Skeet. I'm currently reading Effective Python by Brett Slatkin which is incredibly helpful but it doesn't seem to touch on the languages design decisions. Honestly a lot of what I'm reading seems like the wild west of programming (I guess that's to be expected from a duck typed language). Material that incorporates duck vs static type would appreciative as I can use help with the paradigm shift needed between the 2. I'd also be interested in any material that could be helpful with Django architecture and best practices. I've noticed that my company has many apps in the same project, something that I've never seen in .NET (I've always moved common libraries into a Nuget and then created separate repos and solutions for each service). I understand there may be advantages to doing so in python (debugging across multiple apps from one IDE and … -
How to send data from one consumer to another consumer
This is a consumer which serves data to other clients. class GetLocationConsumer(AsyncConsumer): data = '' async def websocket_connect(self, event): self.bus = self.scope["url_route"]["kwargs"]["bus"] print(self.bus) #self.user = self.scope["user"] self.bus_room = self.bus self.channel_name = self.bus_room await self.channel_layer.group_add(self.bus_room, self.channel_name) await self.send( { "type": "websocket.accept", } ) await self.send( { "type": "websocket.send", "text": "connected", } ) async def websocket_receive(self, event): self.user = self.scope["user"] print(self.user) print(f'{randint(1,100)}{event["text"]}') await self.channel_layer.group_send( self.bus_room, { "type": "send_message", "text": event["text"], }, ) async def send_message(self, event): # print("message hit") await self.send( { "type": "websocket.send", "text": event["text"], } ) async def websocket_disconnect(self, event): await self.send({"type": "websocket.send", "text": "Connection close"}) await self.send({"type": "websocket.close", "text": "Connection close"}) This is another consumer which will receive location data from a client. class SetLocationConsumer(AsyncConsumer): async def websocket_connect(self, event): self.token = self.scope["url_route"]["kwargs"]["token"] print(self.token) if self.token is None or self.token == '': await self.send({ "type": "websocket.close", "text": "No token provided", }) self.user = await self.check_token(self.token) if self.user is AnonymousUser: await self.send({ "type": "websocket.close", "text": "Invalid token", }) self.bus = self.scope["url_route"]["kwargs"]["bus"] self.bus_room = self.bus self.channel_name = self.bus_room await self.channel_layer.group_add(self.bus_room, self.channel_name) await self.send({ "type": "websocket.accept", }) async def websocket_receive(self, event): await self.channel_layer.group_send( self.bus_room, { "type": "send_message", "text": event["text"], }, ) async def websocket_disconnect(self, event): await self.send({ "type": "websocket.send", "text": "Connection close" }) … -
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', …