Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
How to filter product by its Attribute in Django - Django?
I'm working on a Django Ecommerce project where product has several attributes like. size, color( A single product can have multiple attributes with different size and color). No i'm trying to filter products using django_filters but unable to filter by its attributes. Below are the codes(models) for your reference. Request you to kindly look in to and help. Thanks in advance. Product Model: class Product(models.Model): variations = ( ('None', 'None'), ('Size', 'Size'), ) name = models.CharField(max_length=200, unique=True) store = models.ManyToManyField(Store) slug = models.SlugField(null=True, blank=True, unique=True, max_length=500) sku = models.CharField(max_length=30, null=True) tax = models.IntegerField(null=True, blank=True) stock = models.CharField(max_length=10, null=True) variations = models.CharField(choices=variations, max_length=20) short_description = models.CharField(max_length=500, null=True) details = RichTextUploadingField(null=True, blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) discounted_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) image = models.ImageField(upload_to='product/images', default='product.png', null=True, blank=True) image_one = models.ImageField(upload_to='product/images', null=True, blank=True) image_two = models.ImageField(upload_to='product/images', null=True, blank=True) image_three = models.ImageField(upload_to='product/images', null=True, blank=True) image_four = models.ImageField(upload_to='product/images', null=True, blank=True) image_five = models.ImageField(upload_to='product/images', null=True, blank=True) tags = models.ManyToManyField(Tags) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True, related_name='products') status = models.CharField(max_length=20, choices=(('Active', 'Active'), ('Inactive', 'Inactive'))) brand = models.ForeignKey(Brand, on_delete=models.PROTECT, blank=True, null=True) offer = models.ForeignKey(Offer, on_delete=models.CASCADE, null=True, blank=True) # This is used only for filtration Product attribute model class ProductAttribute(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) size = models.ForeignKey(Size, on_delete=models.CASCADE, … -
django set_cookie does not set cookie in browser
I am writng a drf app, that sets cookie. I set cookie like this: serializer = TitleSerializer(result.titles, many=True) response = JsonResponse(serializer.data, safe=False) response.set_cookie("country_code", code) return response But when I check request for cookies like this: if 'country_code' in request.COOKIES: print(request.COOKIES['country_code']) I get nothing. I checked response object in browser console and it has them in headers: Set-Cookie country_code=unknown; Path=/ and in cookies: country_code path "/" value "unknown" But when I go to inspect>storage>cookies there is nothing there. Should I set cookies by hand in js or am I doing something wrong in django part? I just googled how to set cookies in django and it seemed like browser should set and send cookies automaticly, so I was curious what I'm doing wrong. -
Django .exclude() returns empty queryset
I have a problem with .exclude() when making a QuerySet. My models involved are: Profession class Profession(models.Model): profession_name = models.CharField(max_length=20) equipment = models.ManyToManyField(Equipment, blank=True) ability = models.ManyToManyField(Ability, blank=True) skill = models.ManyToManyField(Skill, blank=True) skill_advanced = models.ManyToManyField(SkillAdvanced, blank=True) Ability class Ability(models.Model): ability_name = models.CharField(max_length=35) When I create QuerySet with: self.prof_abilities = Profession.objects.filter(profession_name="Acolyte").values('ability') I get: <QuerySet [{'ability': 2}, {'ability': 69}, {'ability': 81}, {'ability': 86}, {'ability': 23}]> But I would like to exclude some values, so I use this instead: self.prof_abilities = Profession.objects.filter(profession_name="Acolyte").exclude(ability__in=[2, 23, 81, 86]).values('ability') But the outcome is an empty QuerySet: <QuerySet []>. I've tried various tweeks like .exclude(ability__id__in=[2, 23, 81, 86]) or .exclude(ability__ability_name__in=['Foo name', 'Bar name'] but with no success. I'm new to Django so if this is something obvious, I would also appreciate some pointers where to read more on my mistake. -
Django rest framework post request returns 200 but data is not saved in the database
when post request is sent to the api, api returns Ok as the response but no data is inserted into the database. views.py @api_view(['POST']) def createTicketList(request): serializer = TicketListSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors) serializer.py class TicketListSerializer(serializers.ModelSerializer): class Meta: model = TicketListTable fields = '__all__' def create(self, validated_data): return TicketListTable(**validated_data) models.py class TicketListTable(models.Model): ticketListName = models.CharField(max_length=50) ticketListCreated = models.DateTimeField() ticketListUpdates = models.DateTimeField() def __str__(self): return self.ticketListName class Meta: app_label = "backend" db_table = "TicketListTable" postman api postman api post request -
django getting distinct records in table seems to choose random row
I have a table that contains the pricing data for the cards and I am trying to get the pricing data for distinct cards by card_id but this seems to select the row at random. I would like to get the latest datetime pricing data for each card card_id. Table: id nonfoil foil datetime card_id "fb7fbcdc" 0.20 0.49 "2021-10-11 10:03:51.943603+01" "00302342" "d0d6f491" 0.10 0.49 "2021-10-11 10:01:09.916438+01" "00302342" "bfdca73b" 0.03 0.04 "2021-10-11 10:03:51.907601+01" "012e0b83" "33c7aeae" 0.10 0.04 "2021-10-11 10:01:09.875894+01" "012e0b83" "94ca3324" 0.10 0.04 "2021-10-11 10:01:09.961261+01" "0307f37b" "2e992a8d" 0.03 0.04 "2021-10-11 10:03:51.988602+01" "0307f37b" I currently am getting the pricing data using the following code: pricing_cards.objects.filter(card_id__rarity='mythic').values_list('nonfoil', flat=True).distinct('card_id'), For example this is returning: id nonfoil foil datetime card_id "d0d6f491" 0.10 0.49 "2021-10-11 10:01:09.916438+01" "00302342" "bfdca73b" 0.03 0.04 "2021-10-11 10:03:51.907601+01" "012e0b83" "94ca3324" 0.10 0.04 "2021-10-11 10:01:09.961261+01" "0307f37b" But I would like it to return: id nonfoil foil datetime card_id "fb7fbcdc" 0.20 0.49 "2021-10-11 10:03:51.943603+01" "00302342" "bfdca73b" 0.03 0.04 "2021-10-11 10:03:51.907601+01" "012e0b83" "94ca3324" 0.10 0.04 "2021-10-11 10:01:09.961261+01" "0307f37b"