Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"could not connect to server: No such file or directory" Django deploy to Heroku Error
Im facing this problem when i tried to deploy Django Rest Framework App to Heroku: Exception Type: OperationalError at / Exception Value: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? This Error is from Heroku, i have a .travis.yml to check errors before deploying on github, and every test went well. The deploy Building on Heroku went well, so this error is coming from the Django Debugger on Heroku App. This is my Procfile web: gunicorn wardogs.wsgi --log-file - I dont know what i have to show you becouse the error is not coming from any local directories. I read on this question that i should execute this command: heroku addons:create heroku-postgresql but the error persist. What should i do? -
Web-App framework suggestions for my CPP backend [closed]
i have a substantial piece of code written in CPP which serves as operator for IOT machines, communicates with the DB and provides REST/Websocket. Now i need a good framework to write the Web-App-Frontend. My initial thought was to use Django. The problem is that Django can not connect to the websocket, it can only provide it own, but that does not work since the Backend server does not know where the frontend clients are. It needs to be able to regularly collect the data from the backend and send commands to the same. cheers Robert -
(1366, "Incorrect string value: '\\xD9\\x86\\xDB\\x8C\\xD9\\x85...' for column '<column_name>' at row <row_number>") Django
Im trying to connect Django project to mysql in my host, when I want to install mysqlclient using pip install mysqlclient I got an error that mysqlclinet cant be install on this host, so I install pymysql and use import pymysql pymysql.install_as_MySQLdb() in init.py file in project folder where settings.py is. also I use DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': config('DB_NAME'), 'USER': config('USER'), 'PASSWORD': config('DB_PASSWORD'), 'OPTIONS': { 'charset': 'utf8mb4', 'use_unicode' : True, }, }, } Now when I want to run ./manage.py migrate some migrations has been applied but some migrations got an error to me that django.db.utils.DataError: (1366, "Incorrect string value: '\\xD8\\xAA\\xD9\\x86\\xD8\\xB8...' for column 'name' at row 5") As I said some migrations has been applied like as USERs so when I want to save Persian Characters as user first_name or in other columns I got same error that seys (1366, "Incorrect string value: '\\xD9\\x86\\xDB\\x8C\\xD9\\x85...' for column 'first_name' at row 1") so how to fix this problem?! PS: I dont have access to all terminall command like as apt and same things... Python 3.7 Django 3.2 pip 21.1.1 PyMySQL 1.0.2 -
How to send updates to client without polling?
Basically imagine you have a twitter feed and you want to notify the user when new tweets have been made. You could implement this with polling but it would be inefficient, you'd want it to be event driven, so that when a new tweet is made an update is pushed to the frontend. Part of the answer is to use websockets. But the other part I don't know is how the server knows to send an update when there's a new tweet in the database without constantly polling/querying the database to check if there's been a new tweet. It seems inefficient and that there's a better way. Someway to tie a database change to an event listener and send the response to the client. Any help would be greatly appreciated -
Why django-admin startproject creates nested project folders?
django-admin startproject mysite creates something like this: /mysite /mysite settings.py .... I know if I add a period at the end of command (django-admin startproject mysite .) the second folder will not be created, but I don't understand what is the rationale behind creating nested project folders. Maybe I'm missing something critical? -
Python/Django: How to create a loop to identify all related objects
I have two models as follows: class User(AbstractUser): def related_users(self): """Returns list related users if any. Else returns False.""" users1 = RelatedUser.objects.filter(user1=self) if not users1: return False related_users1 = [] for related_user in users1: related_users1.append(related_user.user2) users2 = RelatedUser.objects.filter(user2=self) if not users2: return False related_users2 = [] for related_user in users2: related_users2.append(related_user.user1) related_users = list(set(related_users1 + related_users2)) if self in related_users: related_users.remove(self) return related_users class RelatedUser(models.Model): """Identifies which users are related.""" user1 = models.ForeignKey("User", on_delete=models.CASCADE, related_name="related_users_1") user2 = models.ForeignKey("User", on_delete=models.CASCADE, related_name="related_users_2") Consider the following RelatedUser objects: user1 = a, user2 = b user1 = a, user2 = c user1 = d, user2 = b Now say I execute a.related_users() This returns a list [b, c] However we can see that all of the RelatedUser objects are related indirectly. How do I modify related_users() to incorporate this? So that the list, in the above case, is [b, c, d] I have been unable to come up with a recursive or other function to do this. -
Replace ajax json for python json in Django
I'm trying change Ajax json url to python variable with a json in Django. As you can see the url in both cases are the same so I can't understand what is going on. Thanks in advance. What I'm looking for and does not work <script> $(document).ready(function() { var table = $('#users').DataTable({ "ajax": "{{ es_docs }}", my view: @login_required(login_url="/login/") def index(request): context = {} context['segment'] = 'index' html_template = loader.get_template( 'index.html' ) resp = requests.get("https://gyrocode.github.io/files/jquery-datatables/arrays_id.json").json() context['es_docs'] = resp return HttpResponse(html_template.render(context, request)) Template.html: <script> $(document).ready(function() { var table = $('#users').DataTable({ "ajax": "https://gyrocode.github.io/files/jquery-datatables/arrays_id.json", 'columnDefs': [ { 'targets': 0, 'checkboxes': { 'selectRow': true } } ], 'select': { 'style': 'multi' }, 'order': [[1, 'asc']] }); -
Zoho CRM API: Python request-based POST or GET authentication + insertion of contacts
The Task## A django application that allows users to sign up and once the user clicks on the account activation link, Zoho CRM is receiving the data and a contact is created in the CRM section. The Problem I am currently working on an absolute masterpiece - the ZOHO API. I am struggling to set up the native Python code that uses POST/GET requests. Regarding the zcrmsdk 3.0.0, I have completely given up on this solution unless somebody can provide a fully functional example. The support simply blames my code. The documentation I consulted: https://www.zoho.com/crm/developer/docs/api/v2/access-refresh.html, https://www.zoho.com/crm/developer/docs/api/v2/insert-records.html Since the post request in postman API works fine I do not understand why it does not work in python code My approach Generate an self-client API code on: https://api-console.zoho.com/ Insert that code on Postman and retrieve the access or refresh token Use this access token in an add_user_contact function that is defined in the documentation It works! Response is success and it is in Zoho CRM The permsissions scope I am using is: ZohoCRM.modules.contacts.ALL, ZohoCRM.users.ALL, ZohoCRM.modules.deals.ALL, ZohoCRM.modules.attachments.ALL, ZohoCRM.settings.ALL, AAAserver.profile.ALL Picture of Post Man POST REQUEST My own Code def authenticate_crm(): """ access to response object id: response_object.get('data')[0].get('details').get('id') """ url = 'https://accounts.zoho.com/oauth/v2/token' headers = … -
How to access media files inside Javascript in Django project?
I am relatively new to Django. I have a Djano project in which I am trying to render a list of video files that are present inside the media directory in Django. I have followed all the Media URL related requisites and I am able to render the video files in a template inside an application like this: {% block content %} <video width="320" height="240" controls> <source src="{{ MEDIA_URL }}sample_video_file.mp4" type="video/mp4"> Your browser does not support the video tag. </video> {% endblock content %} and it works like a charm. However, I want to display a list of such video files that are returned from a model programmatically using JavaScript. This is my views class:- def video_quiz_data_view(request, pk): videoquiz = VideoQuiz.objects.get(pk=pk) questions = list() for q in videoquiz.get_questions(): answers = list() for a in q.get_answers(): answers.append(a.text) #questions.append({str(q.pk) + " " + q.text : answers}) print(f"Video path: {q.video_path}") questions.append({q.video_path : answers}) return JsonResponse({ 'data': questions, 'time': videoquiz.time, }) I am able to console log the response in the .js file corresponding to the .html file above. I have written an ajax function that calls the view which returns a list of video urls like sample_video_file.mp4 present inside the media directory. $.ajax({ … -
How do I use a Python utility (PyGaze) in my React Native app?
I'm a new developer working with a team developing a React Native app using Expo. We are currently using AWS to host our Django backend. The problem: Implement real time eye tracking software for users to interact with throughout the app. Is there a way to use the PyGaze utility on smartphones? Ideally with both Android and iOS. What we've tried: We worked out the old code from here http://www.pygaze.org/ and got the main GUI working (on my PC) to isolate the pupil like in the example given from YouTube: https://www.youtube.com/watch?v=KM_ruTFY8pY The issue: I haven't figured out how I would work this into our current project. My plan was to show this example window after a button press so the user can calibrate the contrast to isolate the pupil. This would fully depend on the lighting in the room, time of day, screen brightness, etc. The intention is to call the GUItest.py on that button press. Any suggestions would be greatly appreciated! Thanks, Mike -
'RegisterForm' object has no attribute 'is_valid'
This Is models.py from django.db import models class RegisterForm(models.Model): fname = models.CharField(max_length=100) lname = models.CharField(max_length=100) pno = models.CharField(max_length=100) email = models.EmailField(max_length=200) pass1 = models.CharField(max_length=100) pass2 = models.CharField(max_length=100) This is my Views.py from django.shortcuts import render from .models import RegisterForm # Create your views here. def registerView(request): if request.method=='POST': fm = RegisterForm(request.POST) if fm.is_valid(): fname = fm.cleaned_data['fname'] lname = fm.cleaned_data['lanme'] pno = fm.cleaned_data['pno'] email = fm.cleaned_data['email'] pass1 = fm.cleaned_data['pass1'] pass2 = fm.cleaned_data['pass2'] reg = RegisterForm.save(fname = fname,lname=lname,pno=pno,email=email,pass1=pass1,pass2=pass2) reg.save() fm = RegisterForm() else: fm = RegisterForm() return render(request, 'register.html', {}) Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 3.2 Exception Type: AttributeError Exception Value: 'RegisterForm' object has no attribute 'is_valid' Exception Location: H:\Django\authetication\users\views.py, line 7, in registerView -
Django Admin: How to dynamically set list_per_page
I have run into the case where I am managing the codebase for a project that utilizes the django-admin portion of a site. All of the functionality of the django admin exists in normal views as well, but for some reason the client prefers to work on the admin views as opposed to the function based views... Normally, adding in a dropdown and adjusting the pagination/filter would be easy in a function based view, but the only way I can see to modify this is with list_per_page How do I add a dropdown to the admin page (preferably with the pagination buttons) and then how do I retrieve the results on the server side to alter the list_per_page value dynamically based on what the user has selected? Would adding a form to the template and retrieving a POST in the admin work? -
How to avoid creating image thumbnail every model.save() call?
I'm creating a news blog, so I decided to add a profile image. I was thinking, how to create image thumbnail better and decide to use percent resizing. def save(self, *args, **kwargs): image = Image.open(self.image) # Открываем картинку width, height = image.size # Получаем размеры картинки new_image = BytesIO() # Создаем байтовое представление resize = (width * (height // 10 * 5) // height, height // 10 * 5) # Изменение по высоте if width > height: # Если горизонтальная картинка resize = (width // 10 * 5, height * (width // 10 * 5) // width) # Изменение по ширине image.thumbnail(resize, resample=Image.ANTIALIAS) # Делаем миниатюру картинки image = image.convert('RGB') # Убираем все лишние каналы image.save(new_image, format='JPEG', quality=90) # Конвертируем в JPEG, ибо мало весит new_image.seek(0) # Возвращение в начало файла name = f'{self.image.name.split(".")[0]}.jpeg' # Имя файла # Перезапись файла в базе данных self.image = InMemoryUploadedFile( new_image, 'ImageField', # Картинка, поля сохранения name, 'image/jpeg', # Имя картинки, содержание getsizeof(new_image), None # Размер, доп инфа ) # Сохранение через другой save класса super(KvantUser, self).save(*args, **kwargs) So, as you can see, I take only a half of the image size. It helps to keep good quality of the picture and reduce its … -
Django - Troubleshooting thread locals & middleware issue with DRF ViewSets in Production
Anyone have a recommendation for approaching this challenging problem? Not sure how to troubleshoot this further. I am setting a value in thread locals in middleware using the following: from threading import local ORG_ATTR_NAME = getattr(settings, "LOCAL_ORG_ATTR_NAME", "_current_org") _thread_locals = local() def _do_set_current_variable(variable_fun, attr_name): setattr(_thread_locals, attr_name, variable_fun.__get__(variable_fun, local)) def thread_local_middleware(get_response): def middleware(request): organization = Organization.objects.get_current(request) _do_set_current_variable(lambda self: organization, ORG_ATTR_NAME) response = get_response(request) return response return middleware def get_current_variable(attr_name: str): """Given an attr_name, returns the object or callable if it exists in the local thread""" current_variable = getattr(_thread_locals, attr_name, None) if callable(current_variable): return current_variable() return current_variable I have a Manager class that all models which contain an organization FK field make use of: class OrganizationAwareManager(models.Manager): def get_queryset(self): logger.debug(f"_thread_locals attributes in manager: {_thread_locals.__dict__}") organization = get_current_variable(ORG_ATTR_NAME) queryset = super().get_queryset().filter(organization=organization) logger.debug(f"OrganizationAwareManager queryset: {queryset.query}") return queryset This all works like a charm in dev, and also works great on nearly everything in production - except in DRF ViewSets that query models with the OrganizationAwareManager. Other ViewSets work as expected, and normal django views that refer to models with the OrganizationAwareManager in view context also work fine. Literally just DRF Viewsets with OrganizationAwareManager in Production are the only issue. As you can see, I added … -
Django restful framework "The serializer field might be named incorrectly"
Hello dear stack overflowers, I've set up a Django project with restful framework and I use JSON response in order to retrieve data from the server in a structured manner. The problematic code: class ContentView(RetrieveAPIView): queryset = Container.objects.all() serializer_class = ContainerSerializer def get_object(self): queryset = self.get_queryset() serializer = ContainerSerializer(queryset,many=True) return JsonResponse(serializer.data , safe=False) Gives the following error when being executed: AttributeError: Got AttributeError when attempting to get a value for field `title` on serializer `ContainerSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `JsonResponse` instance. Original exception text was: 'JsonResponse' object has no attribute 'title'. [21/May/2021 17:27:13] "GET /content/ HTTP/1.1" 500 18789 To be as clear as possible I'll attach the serializer's code: class ContainerSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) title = serializers.CharField(required=True, allow_blank=False, max_length=100) content = serializers.CharField() def create(self, validated_data): return Container.objects.create(**validated_data) def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.content = validated_data.get('content', instance.content) instance.save() return instance Before switching to RetrieveAPIView, everything worked well with the test server. The error arised while switching to this new-for-me method of making requests. Any help will be appreciated! -
Can someone help me here. I'm trying to assign more than one rule to a single user based on role's names in django DRF
Here in my model I have multiple roles for users like HR, IT, ADMIN, FINANCE, EMPLOYEE and PROJECT_MANAGER. Purpose is to assign roles to user more than one based on role names. But I'm unable to get there. Here are the models: class UserRole(HRMBaseModel): HR = 'HR' IT = 'IT' ADMIN = 'ADMIN' FINANCE = 'FINANCE' EMPLOYEE = 'EMPLOYEE' PROJECT_MANAGER = 'PROJECT MANAGER' ROLE_CHOICES = ( (HR, 'hr'), (IT, 'it'), (ADMIN, 'admin'), (FINANCE, 'finance'), (EMPLOYEE, 'employee'), (SUPER_ADMIN, 'super admin'), (PROJECT_MANAGER, 'project manager'), ) role_name = models.CharField(max_length=255, choices=ROLE_CHOICES) def __str__(self): return self.role_name class User(AbstractUser, HRMBaseModel): username = models.CharField(max_length=50, unique=True) email = models.EmailField(_('email address')) role = models.ManyToManyField(UserRole) Here is serializers.py to create user class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name', 'role', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): role_data = validated_data.pop('role') password = validated_data.pop('password') user = User(**validated_data) user.set_password(password) user.save() profile_data = { "display_name": validated_data['first_name'], "fullname": f"{validated_data['first_name']} {validated_data['last_name']}", "dob": None, "address": None, "country": None, "city": None, "state": None, "zip_code": None, "profile_avatar": None } UserProfile.objects.create(user=user, **profile_data) user.role.add(UserRole.objects.get(role_name=role_data[0])) return user Here is how I'm creating user { "email": "test_99@admin.com", "first_name": "test_99", "last_name": "test_99", "username": "test_99", "password": "test_99", "role": [3] } But this is how I want to … -
Django Error ''Field 'id' expected a number but got <Transfernews: Transfernews object (1)>.''
I am getting this error when trying to submit comments. Can anyone please tell me how to fix this? My models.py: class Transfernews(models.Model): player_name = models.CharField(max_length=255) player_image = models.CharField(max_length=2083) player_description = models.CharField(max_length=3000) date_posted = models.DateTimeField(default=timezone.now) class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) transfernews = models.ForeignKey(Transfernews, related_name="comments", on_delete=models.CASCADE) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.transfernews.player_name, self.user.username) My forms.py: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('body',) My views.py: def transfer_targets(request): transfernews = Transfernews.objects.all() news = request.POST.get("transfer_id", None) form = CommentForm(request.POST or None) if form.is_valid(): new_comment = form.save(commit=False) new_comment.user = User.objects.get(id=request.user.id) new_comment.transfernews_id = Transfernews.objects.get(id=news) new_comment.save() return redirect(request.path_info) return render(request, 'transfernews.html', {'transfernews': transfernews, 'form': form}) My html file: {% for transfer in transfernews %} <div>Comment and let us know your thoughts</div> <form method="POST"> {% csrf_token %} <input type="hidden" name="transfer_id" value="{{ transfer.id}}"> <div class="bg-alert p-2"> <div class="d-flex flex-row align-items-start"> </div> <div class="mt-2 text-right"> {{ form|crispy }} <br> <button class="btn btn-primary btn-sm shadow-none" type="submit">Post comment</button> <button class="btn btn-outline-primary btn-sm ml-1 shadow-none" type="button">Cancel</button> </div> </div> </form> {% endfor %} -
why am i having error whenever i tried to add image to my django project?
the idea of the base.html is not to be repeating some codes that i will need in almost all of the pages... i can easily {% extends 'homepage/base.html' %}. on every page i need it. checkout my base.html below! 1. (base.html) {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!--fonts--> <link href="https://fonts.googleapis.com/css2? family=Comfortaa:wght@300;400;500;600;700&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Niconne&family=Satisfy&display=swap" rel="stylesheet"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384- +0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'homepage/css/styles.css' %}"> {% if title %} <title>Amal Restaurant - {{ title }}</title> {% else %} <title>Amal Restaurant</title> {% endif %} </head> <body> {% block content %} {% endblock content %} <!-- Option 1: Bootstrap Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script> <!-- Option 2: Separate Popper and Bootstrap JS --> <!-- <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.min.js" integrity="sha384-Atwg2Pkwv9vp0ygtn1JAojH0nYbwNJLPhwyoVbhoPwBhjQPR5VtM2+xf0Uwh9KtT" crossorigin="anonymous"></script> --> <!--jquery cdn--> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"> </script> <!--local js files--> <script src="{% static 'homepage/js/jquery.js' %}"></script> <script src="{% static 'homepage/js/main.js' %}"></script> </body> </html> this is the index.html where i {% extends 'homepage/base.html' %}. every other thing is working well but my images. checkout my index.html below! 2. (index.html) {% extends 'homepage/base.html' %} {% block content %} <header … -
Django Docker problems
I have some problems while creating my docker container for my django application. I have my Dockerfile FROM python:3.8.6 ENV PYTHONUNBUFFERED 1 USER root RUN apt-get -y update && \ apt -y install python3-pip && \ pip3 install setuptools gitpython && \ pip install django && \ pip install stripe && \ pip install django-extensions RUN git clone https://github.com/***/*** WORKDIR /tfg/MiTfg EXPOSE 8000/tcp CMD python3 manage.py makemigrations CMD python3 manage.py migrate CMD python3 manage.py runserver localhost:8000 It works perfectly, now I run docker run --network host -p 8000:8000 1fbe And the output prints: WARNING: Published ports are discarded when using host network mode System check identified some issues: WARNINGS: Tienda.Categoria: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the TiendaConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'. Tienda.Cliente: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the TiendaConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'. Tienda.CodigoDescuento: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the … -
How to annotate Django query with days calculation?
How do you annotate a Django query of a table with the calculation of days since the record was created? I want to order a table based on a combined metric of priority multiplied by days since the record was created. To get the days annotation, I'm trying to do: qs = qs.annotate(days=(ExtractDay(Now()-F('created_datetime')))) However, this is throwing the error: django.db.utils.ProgrammingError: function pg_catalog.timezone(unknown, interval) does not exist LINE 1: ...EMENT_TIMESTAMP() - "myapp_mymodel"."created_timestamp") AT TIME ZO... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. What am I doing wrong? It looks like both the value returned by Django's Now() and my timestamp field are timezone-aware timestamps, so why is the database complaining about incompatible types? My database backend is PostgreSQL. -
How can i manipulate pandas python, excel file, postgresql in web app?
I have to create a software or web application that will allow me to handle Pandas, make basic crud with pandas, crosstabs and sent the results then obtained in PostgreSQL. Do you have tracks? Or suggestions? thank you, I look and saw pandasgui pandastable but I do not know if they can meet my needs -
How to use array from python to javascript? Django
Before you say its duplicate !! I know how to parse by using dump() in views, but right now I want to receive an array of dictionaries from a custom template tag to JavaScript. This is in my custom_template.py @register.simple_tag(takes_context = True) def messageRequest(context): request = context['request'] messageData = Message.objects.all() jsMessageData = [] if 'user' in request.COOKIES: currentUser = request.COOKIES.get('user') i = 0 for i in range(messageData): if messageData[i].receiver == currentUser: jsMessageData.append(messageData[i]) if messageData[i].sender == currentUser: jsMessageData.append(messageData[i]) i += 1 print(jsMessageData) return dumps(jsMessageData) For my template index.html I want to use it in JavaScript to display the messages- I tried this messageData = Json.parse("{% messageRequest %}"); // i want to store it as array // throws error "'QuerySet' object cannot be interpreted as an integer" when looping through it also, messageData = Json.parse("{% messageRequest|escapejs %}"); // i read this somewhere and it works fine when array is passed through render request but here it gives error as it considers escapejs as part of block tag. Any help is appreciated, I am sort of beginner so please try to give comprehensive explanation an example will be really helpful. -
How to return form field errors to template rendered in a different django view
I have a django bootstrap 4 template (wordcloud.html) that contains a form. The form was originally created as raw html within wordcloud.html, and the view for that template populates the fields. The form (create_wordcloud_form) uses post to send the data to a different view (create_wordcloud_view.py). The original developer didn't use django's built in template/form/view structure, so there is no form.py nor a form template. The issue I need to address is validating the form. It has to be server-side validation, as one of the fields needs to be tested against one of the databases to prevent duplicate fields. Do I need to refactor the whole mess into the standard django template/form/view idiom using crispy-forms, or is there a way to use what I already have and return some error messages from the view that processes the form data? The code for validating the fields is easy. I am not sure how to structure the return statement in the event there are field errors, since wordcloud.html is rendered in a different view. create_wordcloud_view: @method_decorator(login_required, name='post') class CreateWordCloud(View): def post(self, request): logger.debug("CreateWordCloud START") q_dict = request.POST logger.debug("q_dict=%s" % q_dict) sources = [] filters = {} cloud_name = None for key in q_dict: … -
Run a Scrapy spider in a Huey Task (django project)
I want create periodic task in Django to run Scrapy process, but the task in log seems doesn't end, i believe that i need connect the crawler signal with Huey task, i'm lost with this, any idea? INFO 2021-05-20 19:34:36,500 consumer.start :: Huey consumer started with 1 thread, PID 4000 at 2021-05-20 19:34:36.500022 INFO 2021-05-20 19:34:36,500 consumer.start :: Scheduler runs every 1 second(s). INFO 2021-05-20 19:34:36,500 consumer.start :: Periodic tasks are enabled. INFO 2021-05-20 19:34:36,500 consumer.start :: The following commands are available: + app.tasks.run_spider [2021-05-20 19:34:48,260] INFO:huey:Worker-1:Executing app.tasks.run_spider: 1e843422-2ab6-48fa-bf8b-6b7fe25266f8 INFO 2021-05-20 19:40:07,864 consumer.run :: Received SIGINT INFO 2021-05-20 19:40:07,865 consumer.stop :: Shutting down gracefully... [2021-05-20 19:40:07,868] INFO:huey:Worker-1:app.tasks.run_spider: 1e843422-2ab6-48fa-bf8b-6b7fe25266f8 executed in 319.608s INFO 2021-05-20 19:40:07,869 consumer.stop :: All workers have stopped. INFO 2021-05-20 19:40:07,869 consumer.run :: Consumer exiting. from multiprocessing import Process from scrapy import signals from scrapy.crawler import Crawler from twisted.internet import reactor def run_script(): crawler = Crawler(MySpider, settings=settings.SCRAPY_SETTINGS) crawler.signals.connect(reactor.stop, signal=signals.spider_closed) reactor.run() @db_task() def run_spider(): process = Process(target=run_script) process.start() process.join() huey==2.3.2 django==3.2.3 -
Django order_by() is not working along with distinct()
How can i use order_by() in combination with distinct() ? I am having multiple same run_id with different end_time data = list(table_name.objects.filter(experience=experience)\ .values('run_id', 'end_time').distinct('run_id').order_by('-end_time')) Following is the error :- django.db.utils.ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions Also, the following ORM works fine without order_by but I want the latest end_time data = list(table_name.objects.filter(experience=experience).values('run_id', 'end_time').distinct('run_id'))