Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Log accesses to Django model fields?
I have a Django model with 100+ fields, and would like to log which fields are being used to clean up the model. For example, which fields are used when running Person.objects.get(person_id=123). -
Django Template: Concatinate a string and format a date
Inside Django Template, how can I concat a variable that has a formatted date? I'm trying to create a button to redirect to another page. When I do this, it gives me an error because of the quotation marks: <input type="button" class="btn btn-primary" onclick="location.href='/print_receipts?u={{ username }}&mpu=t&pst={{ pantry_start_time|date:'G:i:s' }}&pantry_end_time={{ pantry_end_time|date:'G:i:s' }}&dow={{ dow }}'" value="Mark as Picked Up" /> So I thought I can concat the string and variables, but it didn't work when I try to format the date for pantry_end_time or pantry_start_time. {% with link="/print_receipts?u={{ username }}&mpu=t&pst={{ pantry_start_time|date:'G:i:s' }}&pantry_end_time={{ pantry_end_time|date:'G:i:s' }}&dow={{ dow }}" %} <input type="button" class="btn btn-primary" onclick="location.href='{{ link }}'" value="Mark as Picked Up" /> link: {{ link }} {% endwith %} -
Django get all field after group by one field
I have a model: class AccessConfigFile(models.Model): file_name = models.CharField(unique=True, max_length=200, default=None) class AccessConfig(models.Model): file = models.ForeignKey(AccessConfigFile, on_delete=models.CASCADE, default=None) data = models.CharField(verbose_name='ems data', default='', blank=True, max_length=50000) version = models.IntegerField(default=0) I want to get data of latest version of each file for AccessConfig model. I have a query: AccessConfig.objects.values('file').annotate(version=Max('version')) But it just got 2 fields file and version. How can I get all fields with MySQL DB? Because MySQL can not use distinct('field_name') function as PostgreSQL -
How to set the vice versa condition for django models
I am using Django3 and model I want to get the data of Distance from one city to another city. But in the database, only the distance A to B is stored ( because distance of B to C is the same) So, what I want to is fetch the correct row, regardless the order of cities. I can do this with use these two sentences and error check each. Distance.objects.get(key_first=firstcity, key_second=secondcity) Distance.objects.get(key_second=secondcity, key_second=firstcity) However it looks a bit awkward and it requres two times DB fetch, Is there any smarter way like this below?? Distance.objects.get((key_first=firstcity, key_second=secondcity) | (key_second=secondcity, key_second=firstcity)) -
How to serve quasar dist files from django?
I have used python manage.py collectstatic to collect the quasar dist files generated after the quasar build command. But I am getting the following error. http://127.0.0.1:8000/static/js/vendor.df0d9f8a.js net::ERR_ABORTED 404 (Not Found)... Here are my djnago index.html code from where I am calling the js and css from the static folder. {% extends "base.html" %} {% load static %} {% block style %} <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link href="{% static 'css/vendor.187160a9.css' %}" rel=stylesheet> <link href="{% static 'css/app.0e433876.css' %}" rel=stylesheet> {% endblock %} {% block content %} <noscript> <strong>We're sorry but frontend doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> </noscript> <div id="app"></div> {% endblock %} {% block js %} <script src=https://cdn.jsdelivr.net/jsbarcode/3.3.20/JsBarcode.all.min.js></script> <script type="text/javascript" src="{% static 'js/vendor.df0d9f8a.js' %}"></script> <script type="text/javascript" src="{% static 'js/app.ba927e14.js' %}"></script> {% endblock %} Is there any other approach to serve quasar dist files from django? -
Автодополнение оставшихся полей в vue.js [closed]
Есть проект с фронтом на vue и бэком на джанго,нужно при вводе в одно поле проверять значение и вызывать функцию с этим значением,и в реальном времени обновлять оставшиеся поля инпутов значениями полученныеми из функции,но с возможностью последующего редактирования -
How to create directories/files on the local machine using Django?
I'm working on a blockchain project where I'm implementing a wallet using Django. A user logs in and get's to generate an address. Now, I want to store the user's private key/public key pair in a file locally on the user's machine every time a user generates an address, and be able to read that file again in the next session (at the user's will). I'm doing this because the app itself is a supernode of the blockchain and all users are virtual nodes. All communication between users happen through the supernode, thus the wallet functionality isn't the core function of the app. Everything is working perfectly except I can't find a way to create files locally on the client's machine. I've perused the Django documentation but I can't seem to find anything useful (maybe I'm not looking in the right place). Is there a way I can achieve that? Note: I'm trying as much as possible to avoid JavaScript, and I don't want users to download/upload files manually. -
serializer field error on serializer method field
i am trying to customer name and meter number on my customer report serializer , but i am getting below-mentioned error, i am going as Docs but don't know what seems to be the issue class CustomerReportSerializer(serializers.HyperlinkedModelSerializer): meter_no = serializers.SerializerMethodField(method_name='get_meter_num') customer_name = serializers.SerializerMethodField(method_name='get_cust_name') class Meta: model = CustomerReport fields = ['meter_no','meter','customer_name','date','customer_unit','unit_rate','bill_amount',] def meter_num(self,obj): if obj.meter.number: return obj.meter.mumber else: return "" def cust_name(self,obj): if obj.meter.customer.name: return obj.meter.customer.name else: return "" class CustomerReport(models.Model): meter = models.ForeignKey('Meter', on_delete=models.CASCADE) date = models.DateTimeField(auto_now=True) customer_unit = models.IntegerField() unit_rate = models.DecimalField(decimal_places=2, max_digits=10) bill_amount = models.DecimalField(decimal_places=2, max_digits=10) def __str__(self): return str(self.meter.customer) 'CustomerReportSerializer' object has no attribute 'get_meter_num' -
need id's of objects from Django query where customer id's are distinct and unique
CfgXmppSessions.objects.filter(character_objid=9100).values_list('customer_objid').annotate(objiod1=F('objid')).distinct()) I want all objid where customers are unique -
Serializer extra field from a ManyToMany Field
I have these serialiazers class DepartmentSerializer(serializers.ModelSerializer): class Meta: model = Department fields = ('name', 'slug', 'image', 'description') class DoctorSerializer(serializers.ModelSerializer): class Meta: model = Doctor fields = '__all__' depth = 1 and the current representation is like this: { "id": 1, "first_name": "Jhon", "last_name": "Doe", "slug": "jhon-doe", "email": null, "phone": null, "title": null, "description": "", "image": "http://localhost:8000/media/studio/default.jpg", "department": [ { "id": 1, "name": "Acupuncture", "slug": "Acupuncture", "image": "http://localhost:8000/media/studio/acupuncture-min.jpg", "description": "Acupuncture" }, { "id": 3, "name": "Cardiology", "slug": "cardiology", "image": "http://localhost:8000/media/studio/default.jpg", "description": "Cardiology" } ] } I'd like to keep the department field as IDs and have an extra field for departmentName and have a representation like this: { "id": 1, "first_name": "Jhon", "last_name": "Doe", "slug": "jhon-doe", "email": null, "phone": null, "title": null, "description": "", "image": "http://localhost:8000/media/studio/default.jpg", "department": [ 1, 3 ] "departmentName": [ { "id": 1, "name": "Acupuncture", "slug": "Acupuncture", "image": "http://localhost:8000/media/studio/acupuncture-min.jpg", "description": "Acupuncture" }, { "id": 3, "name": "Cardiology", "slug": "cardiology", "image": "http://localhost:8000/media/studio/default.jpg", "description": "Cardiology" } ] } This is because if I have the 1st representation I have problems in managing the CRUD because department are not IDs. The problem is because department is a ManyToMany relation, for example if it was just a ForeignKey I could have done … -
Auto Attribute completetion Not working at Django-HTML at vs code
Attribute completion or attribute IntelliSense not working. When I write code on an Html file, vs code suggest me attribute name, for example: if I type cl then vscode suggests me class="". this is a great feature for saving time. but when I gonna writing code on Django-HTML. this feature was not working. I tried to find the solution to this problem. but I can't. Please help me. Please tell me how can I get this auto attribute completion feature on the Django template. which is Django-html.