Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django on virtualenv but failed to run project and import using git-bash
I already installed django using virtualenv on git bash, but always gives me this error. ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Already add PYTHONPATH to environment variable as well. I tried to import django on python idle but it seems didn't work too. Any idea what I am missing? -
'max_number' is not defined using annotation with django
I have that code from django.db.models import Max User.objects.annotate(max_number=Max('number')).filter(number=max_number) # Filter all users by the highest number. And when I execute it I got that error : 'max_number' is not defined Could you help me please ? Thank you very much ! -
PostgreSQL not available: instance=None:None, timeout=30s
I am trying to run the old code of Django 1.x in my local machine, some how this project is used as microservice and make many dependencies on other project, But I want to run it locally on my machine. I set up the virtual environment, errors removed when I start the server this comes always (env) C:\Users\mahad\projects\Hermes\app>python manage.py runserver PostgreSQL not available: instance=None:None, timeout=30s here is my code, where I am connecting database: 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': environ.get('PGHOST'), 'NAME': environ.get('PGDATABASE', 'app'), 'USER': environ.get('PGUSER'), 'PASSWORD': environ.get('PGPASSWORD'), 'PORT': int(environ.get('PGPORT', 5432)), } What will be the error or what I am missing? Kindly ask if any point you want to know about project settings. -
Querying Multiple foreign key relationships in DRF
I am completely new to django and python kindly help me with below query: I have 3 models , with multiple foreign key relations with given sample data now I need 3 outputs via django ORM or Serializers 1.for a given student id ,display the Student details and marks in each subjects 2.list all the students with their total marks (sum of three subjects in this case) 3.Average marks scored by all the students for each subject for ex as per the given sample marks in English are 65 , 95 and average is 80 { Subject :"English", average : " 80" } class Student(models.Model): student_id = ShortUUIDField(primary_key=True, editable=False) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) class Subjects(models.Model): subject_code = ShortUUIDField(primary_key=True, editable=False) subject_name = models.CharField(max_length=100) class Reports(models.Model): student = models.ForeignKey(Student,on_delete=models.CASCADE,related_name='student_report') subject = models.ForeignKey(Subjects,on_delete=models.CASCADE,related_name='subject',default=None) marks = models.IntegerField(max_length='3') class Meta: unique_together = ("student", "subject") sample data Student data student_id first_name last_name 1 abc x 2 def y Subjects data subject_code subject_name 1 English 2 Science 3 Math Reports data student_id subject_id marks 1 1 65 1 2 75 1 3 92 2 1 95 2 2 85 2 3 62 -
how to send two different post request from react to Django rest framework
I am trying to send different types of data via two different POST requests from react using Axios. When I used to work on the normal Django with the template I would do this: html page with jinja2 <form action="." method="POST"> {% csrf_token %} <p><input class="btn btn-info" type="submit" name="join-group" value="Join Group"></p> <p><input class="btn btn-danger" type="submit" name="leave-group" value="Leave Group"> </p> </form> I am able to grab name, which is either join-group or leave-group above and would allow me to get a different type of post request on the same page normal Django views.py def foo(request, id): ... if 'join-group' in request.POST: # do custom action 1 elif 'leave-group' in request.POST: # do custom action 2 ... How can I achieve the result above using react with Axios and Django rest framework backend? Please note that I know how to send just a regular POST request from react to `Django rest, but sending different types on the same page is what I am looking for. -
How to filter in Django and use a method of the class as the condition?
I want to get a queryset that only contains tutors who fulfill minimum requirements. The tutor class has a method "satisfies_min_requirements(self, student) -> bool". It basically figures out whether a tutor is fitting for the student. I have an approach that works, but I think there must be a better way to do it. This is what I have: tutors = Tutor.objects.all() tutors = list(filter(lambda tutor : tutor.satisfies_min_requirements(student), tutors)) Thank you a lot! -
Is generating CSRF token on the front-end a bad idea?
In Django world, CSRF token is generated in a way that doesn't involve any information known only to the server. It's perfectly possible to generate a valid CSRF token in javascript - Django will happily accept it. In particular, we could have a piece of javascript that generates valid CSRF token and setting its value as a cookie. Are there any security related drawbacks of doing that? The only thing I can think of is that such cookie cannot have the http-only flag set (for obvious reasons). -
How to provide translations for django standalone app inside app?
I would want to provide translation texts (makemessages and write translation strings) inside django-standalone app, to make app support multiple languages. How it can be done? Currently, I use from django.utils.translation import gettext to define translation strings. I would not want to run manage.py makemessages command in the parent project and repeat writing translation strings for each parent project. -
Function to restrict access to the page by time
I have a logic: import datetime now = datetime.datetime.now() hour_now = now.hour if 23 < hour_now < 6: *...views logic...* else: *...closed.html...* But I need this logic make in separate function in utils.py def time_close(): But I don't understand how it's do... Help, please. -
Django JSONField complex query ... practical example of querying complex nested data structure
I have inherited the following JSONField data structure: [ { "name": "Firstname", "show": { "value": true }, "type": "text", "uuid": "55668e45-07d1-404e-bf65-f6a3cacfaa97", "label": { "for": "Firstname", "display": "First name" }, "value": "Michael", "options": [], "required": true, "component": "Input", "placeholder": "Input text here", "validationErrors": [] }, { "name": "Surname", "show": { "value": true }, "type": "text", "uuid": "ce91fefa-66e3-4b08-8f1a-64d95771aa49", "label": { "for": "Surname", "display": "Surname" }, "value": "Roberts", "options": [], "required": true, "component": "Input", "placeholder": "Input text here", "validationErrors": [] }, { "name": "EmailAddress", "show": { "value": true }, "type": "email", "uuid": "6012a805-da62-4cee-8656-b7565b5f8756", "label": { "for": "Email", "display": "Email" }, "value": "michael@hiyield.co.uk", "options": [], "required": true, "component": "Input", "placeholder": "Input text here", "validationErrors": [] }, { "name": "University", "show": { "value": true }, "type": "text", "uuid": "434e3781-ab8a-4f09-9c68-5ec35188f3c7", "label": { "for": "University", "display": "University/College" }, "value": "University College London", "options": [], "required": true, "component": "Input", "placeholder": "Input text here", "validationErrors": [] }, { "name": "Subscribe", "show": { "value": true }, "type": "checkbox", "uuid": "79bdc29e-6357-4175-bf65-07be60776a29", "label": { "for": "Subscribe", "display": "Subscribe to the KEVRI mailing list" }, "value": true, "options": [], "required": true, "component": "Checkbox", "description": "KEVRI is committed to respecting and protecting your privacy. The data collected here will create your personalised report which … -
Two Django websites on Windows Apache
I am trying to host two Django websites on Windows (so no WSGIdaemonprocess). When I did host only one of them it worked perfectly. Now it still works (main path "/" named magazyn). But the second one (path "/awizacje" named awizacje) throws an Internal Server Error. Full error message in Apache logs looks like this: C:\A\34\s\Modules\_decimal\libmpdec\context.c:57: warning: mpd_setminalloc: ignoring request to set MPD_MINALLOC a second time [Mon Oct 11 14:57:35.251409 2021] [wsgi:error] [pid 6268:tid 992] [client 192.168.2.54:25532] mod_wsgi (pid=6268): Failed to exec Python script file 'C:/var/www2/awizacje/rootkat/awizacje/wsgi.py'. [Mon Oct 11 14:57:35.251409 2021] [wsgi:error] [pid 6268:tid 992] [client 192.168.2.54:25532] mod_wsgi (pid=6268): Exception occurred processing WSGI script 'C:/var/www2/awizacje/rootkat/awizacje/wsgi.py'. [Mon Oct 11 14:57:35.251409 2021] [wsgi:error] [pid 6268:tid 992] [client 192.168.2.54:25532] Traceback (most recent call last):\r [Mon Oct 11 14:57:35.251409 2021] [wsgi:error] [pid 6268:tid 992] [client 192.168.2.54:25532] File "C:/var/www2/awizacje/rootkat/awizacje/wsgi.py", line 19, in <module>\r [Mon Oct 11 14:57:35.251409 2021] [wsgi:error] [pid 6268:tid 992] [client 192.168.2.54:25532] application = get_wsgi_application()\r [Mon Oct 11 14:57:35.251409 2021] [wsgi:error] [pid 6268:tid 992] [client 192.168.2.54:25532] File "C:\\var\\www\\magazyn\\env39\\Lib\\site-packages\\django\\core\\wsgi.py", line 12, in get_wsgi_application\r [Mon Oct 11 14:57:35.251409 2021] [wsgi:error] [pid 6268:tid 992] [client 192.168.2.54:25532] django.setup(set_prefix=False)\r [Mon Oct 11 14:57:35.251409 2021] [wsgi:error] [pid 6268:tid 992] [client 192.168.2.54:25532] File "C:\\var\\www\\magazyn\\env39\\Lib\\site-packages\\django\\__init__.py", line 19, in setup\r [Mon Oct … -
how to pass input to api from angular forms without formControlName?
I am passing some data from angular to django rest api, Which is as follows first what django need in for api: notice { description: something, classname : in which class notice is provided, students : from dropdown } what I am passing from angular description by formController students by formcontroller now my issue is that I am not taking classname as input because It doesn't make sense here so is there any other way by which I directly pass classname to api as input without showing on UI my angular code: this.announceForm = this._formBuilder.group({ students : [selectedStudents, Validators.required], description: ['', Validators.required] }); here is django's input fields -
Different RAW query results from django.db.connection and cx_Oracle
I executed the following query from my Django project. from django.db import connection balance_query = " SELECT HAOU.ORGANIZATION_ID ORG_ID, CASE WHEN HAOU.ORGANIZATION_ID = 1 THEN 'F' WHEN HAOU.ORGANIZATION_ID = 9 THEN 'R' ELSE HAOU.NAME END COMPANY, BLNCE (HCA.CUST_ACCOUNT_ID, HCASA.ORG_ID, 0) CCL FROM hca, hp, hcasa, hcsua, HAOU WHERE hca.party_id = hp.party_id AND hca.cust_account_id = hcasa.cust_account_id AND hcasa.bill_to_flag = 'K' AND hcasa.cust_acct_site_id = hcsua.cust_acct_site_id AND hcsua.site_use_code = 'AM' AND HCASA.ORG_ID IN (1, 9) AND HAOU.ORGANIZATION_ID = HCASA.ORG_ID AND HCASA.CUST_ACCOUNT_ID = 11211123 ORDER BY 1" with connection.cursor() as cur: cur.execute(balance_query) balance_data = cur.fetchall() print(balance_date) Then I get result after print as (1, 'F', 77259668) (9, 'R', '24153') The bold value is wrong But When I execute same query with following query import cx_Oracle dsn_tns = cx_Oracle.makedsn('host', 'post', service_name='name') conn = cx_Oracle.connect(user=r'user', password='pwd', dsn=dsn_tns) c = conn.cursor() c.execute( " SELECT HAOU.ORGANIZATION_ID ORG_ID, CASE WHEN HAOU.ORGANIZATION_ID = 1 THEN 'F' WHEN HAOU.ORGANIZATION_ID = 9 THEN 'R' ELSE HAOU.NAME END COMPANY, BLNCE (HCA.CUST_ACCOUNT_ID, HCASA.ORG_ID, 0) CCL FROM hca, hp, hcasa, hcsua, HAOU WHERE hca.party_id = hp.party_id AND hca.cust_account_id = hcasa.cust_account_id AND hcasa.bill_to_flag = 'K' AND hcasa.cust_acct_site_id = hcsua.cust_acct_site_id AND hcsua.site_use_code = 'AM' AND HCASA.ORG_ID IN (1, 9) AND HAOU.ORGANIZATION_ID = HCASA.ORG_ID AND HCASA.CUST_ACCOUNT_ID = 11211123 … -
How do I integrate live video processing in Django?
So the issue I am facing is, I am creating an application where students would join a room and stream their live video to the server (It is not necessary for each student to see each other) these live frames are then fed into the AI model which accepts frames and produces an output. How do I tackle this am I suppose to create a whole thread from the room and each thread for the student? How do I tackle live streaming to the server and processing the data? -
Django DRF api does not return any value
I am trying to create my first api using Django rest framework DRF. Here is my code: in views.py : class PostViewSet(viewsets.ModelViewSet): # permission_classes = [IsAuthenticated] @action(detail=True, methods=['GET']) def queryset(self, request, pk=None): try: queryset = Post.objects.get(post_id=pk) except Analysis.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = PostSerializer(queryset) return Response(serializer.data) and in urls.py: router = DefaultRouter() router.register(r'api/post/<int:pk>/post_analysis/', PostViewSet, basename='app_name') urlpatterns = router.urls However this raises an error that The current path, api/post/698/post_analysis/, didn't match any of these. or Not Found: /api/post/698/post_analysis/ But when I change url as follows, it returns none: PostView = PostViewSet.as_view({ 'get': 'retrieve' }) urlpatterns = format_suffix_patterns([ path('api/post/698/post_analysis/', PostView, name='app_name') ]) result is this: { "detail": "Not found." } -
how to make dynamic email template and store in database table in django?
i am working in a project where we need to have html and text email which needed to stored in database. so that we can dynamically change the values in email and send mail to the users. if any one could please suggest me how to do this all, it will be of great help. i am new to django Framework - django, for mail client - AWS ses, boto3 -
How to send data continuously from views.py to html template in Django?
Is there any way to send continuous data from views.py to a html template? If I use return then we can send data only once but i want to send continuously for some time. -
Cannot access member "create_user" for type "BaseManager[Any]" Member "create_user" is unknownPylancereportGeneralTypeIssues
When I use method create_user in django user = User.objects.create_user(username=user_name, email=email, password=password1) It was an error : Cannot access member "create_user" for type "BaseManager[Any]" Member "create_user" is unknownPylancereportGeneralTypeIssues I tried to search for that error but still can't find it -
Medias exposing from media folder when entering url domain/media from production
enter image description here If enter url : domain/media or doamin/statics . I am getting list of files in browser. I dont want to list those files or exposed in browser. -
Concatenate a specific field from child objects into parent object?
I have two models: class Chapter(models.Model): chapter = models.IntegerField() verses_amount = models.IntegerField() chapter_content = models.TextField() class Verse(models.Model): chapter = models.ForeignKey(Chapter, on_delete=CASCADE) verse = models.TextField() verse_number = models.IntegerField() On Verse, I store a paragraph in the verse field. How can I query all children (Verse), get their verse paragraph, concatenate all those and put that in Chapter.chapter_content? Eg verses = Verse.objects.filter()[0:2] for verse in verses: print(verse.verse) >> 'Lorem Ipsum.' >> 'Second Lorem Ipsum Iteration 2.' In the parent Chapter, I want chapter_content to hold the two values as one long string: 'Lorem Ipsum. Second Lorem Ipsum Iteration 2.' -
In Django Rest Api, how do you return only the Items the owner uploaded
The Viewset def list looks like this: class ThreeDimensionalModelViewSet(viewsets.ViewSet): serializer_class = ThreeDimensionalModelSerializer queryset = ThreeDimensionalModel.objects.all() permission_classes = [permissions.IsAuthenticatedOrReadOnly] def list(self, request): models = ThreeDimensionalModel.objects.all() serializer = ThreeDimensionalModelSerializer(models, many=True) print(request.user.id) return Response(serializer.data) The serializer looks like this: class ThreeDimensionalModelSerializer(serializers.ModelSerializer): class Meta: model = ThreeDimensionalModel fields = ['File', 'Uploaded', 'Owner', 'Previous', 'SharedWithUser'] read_only_fields = ['Owner'] The model looks like this: class ThreeDimensionalModel(models.Model): File = models.FileField(upload_to='models') Owner = models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True, related_name='Owner') Uploaded = models.DateTimeField(auto_now_add=True) Previous = models.ForeignKey("self", on_delete=models.SET_NULL, default=None, null=True) SharedWithUser = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='SharedWithUser') When a user requests models at /api/models it should only show the models that are the same owner Id as his. -
In Django, How to restrict particular selected user to access data
I am developing a academic website. I want to develope a function where admin can restrict particular user(selected user with its id) to access some study material. Admin in not default django admin. It has been developed customizable. Please help me to develop. -
How can I do to filter on max values using Django ORM?
I have that kind of entries : id user number 1 Peter 1 2 Jack 3 3 Kate 2 4 Carla 3 The name of my table is User so I would like to get only the user with the highest number but in some cases I don't know this number. I thought to do something like that : max_users = User.objects.filter(number=3) But the problem is in that case I suppose I know that the highest number is 3 whereas it is not always the case. Could you help me please ? Thank you very much ! -
getting post authors django
i'm trying to get post authors, to see their profiles , but idk hot to get it in detailview class. i'm using custom user registration views class GetAuthor(DetailView): model = User template_name = 'blog/author.html' context_object_name = 'author' def get_context_data(self, **kwargs): context = super().get_context_data() context['author'] = User.objects.get(username=author) models class Post(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) tags = models.ManyToManyField(Tag, related_name='post_tags') date_created = models.DateTimeField(auto_now_add=True) time_to_read = models.PositiveIntegerField(blank=True) text = models.TextField() image = models.ImageField(upload_to='photos/%Y/%m/%d', blank=True) is_published = models.BooleanField(default=True) user model class User(AbstractUser): name = models.CharField(max_length=255) username = models.CharField(max_length=255, unique=True) email = models.EmailField(unique=True) bio = models.TextField(blank=True) avatar = models.ImageField(default='img/avatar.jpg', upload_to='users/') USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] if i could use request.user i ll get logged in user , i want to take any user for watch their profiles, ty! -
Using bulk create with django-taggit
Here is my code: build_data = [ContactDetail(**parse_content(df, i, social_site_lists), admin = request.user) for i in df.index ] ContactDetail.objects.bulk_create(objs = build_data,ignore_conflicts= True) parse_content returns a dictionary, containing many fields, out of which one key is tags, which have a list of tags for that record. Is it possible to add these tags without using the object.tags.add([]), and creating all the records in a single database connection.