Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django show image list in table from ManyToMany field
I have created a model to have details of job vacancy. The job model has the following fields: class Job(models.Model): job_position = models.ForeignKey(Position, on_delete=models.PROTECT, related_name='job_position') applicants_to_hire = models.IntegerField(null=True, blank=True, validators=[MinValueValidator(1), MaxValueValidator(15)], default=1) hiring_team = models.ManyToManyField(Employee, related_name='hiring_team') class JobListView(LoginRequiredMixin, ListView): model = Job template_name = 'recruitment/job_list.html' context_object_name = 'job_list' I want to use the hiring_team in a template to show image of each employee (circle avatar), and those images come from the employee model: class Employee(models.Model): image = models.ImageField(blank=True, default='blank_profile_picture.jpg') I've managed to display all images, but they are not in the same table cell, and they add additional table columns: <tbody> {% for job in job_list %} <tr> <td><span class="employee-table-name"><a href="{% url 'recruitment:job_detail' pk=job.pk %}">{{ job.job_position }}</a></span></td> <td>{{ job.applicants_to_hire }}</td> {% for team in job.hiring_team.all %} {% if team.image %} <td><img src="{{ team.image.url }}" class="rounded-circle img-fluid-80" alt="{{ team }}"></td> {% endif %} {% endfor %} <td>{{ job.job_priority }}</td> <td>{{ job.job_status }}</td> <td>{{ job.created|date:"M d, Y" }}</td> </tr> {% endfor %} </tbody> How can I "concatenate" them to display something like the screenshot below: -
Why am I getting TypeError string indices must be integers in this API call? (seeding Django DB)
I am trying to seed a django DB from an external API using this guide (https://medium.com/@chilinski.a/how-to-seed-a-django-api-with-data-from-an-external-api-b577b6e6ad54). I have replicated the code accurately for my own project, I think, but get a TypeError: string indices must be integers when i run python manage.py seed and am not sure why. Here's my code: import requests from django.core.management.base import BaseCommand from nrel_app.models import Nrel def get_nrel(): url = 'https://developer.nrel.gov/api/utility_rates/v3.json?api_key=DEMO_KEY&lat=35.45&lon=-82.98' r = requests.get(url, headers={'Content=Type': 'nrel_app/json'}) Nrels = r.json() return Nrels def seed_nrel(): for i in get_nrel(): Nrels = Nrel( utility_name = i['utility_name'], company_id = i['company_id'], utility_info =i['utility_info'], residential = i['residential'], commercial = i['commercial'], industrial = i['industrial'], ) Nrels.save() class Command(BaseCommand): def handle(self, *args, **options): seed_nrel() print("Completed.") -
Create new RT table in Django SphinxSearch
I have a django site running with sphinxsearch and am having trouble creating a new RT table. I have previously added columns to RT tables using the steps: sudo service sphinxsearch stop Delete the data in var/lib/sphinxsearch Add the field to sphinx.conf sudo service sphinxsearch start After that the new column appears in mysql, and I can confirm it by connection to the DB directly. However, I have now created a full new table, but when I run the same steps, the data file for the new table as well as the table itself are not being created. I have tried to manually go into Mysql to create the table but have had no luck. Most of the sphinx documentation is not RT table based and I'm having trouble finding how to create this... When I try to run a logdebug following, I receive an error saying that the "table_name.lock" file does not exist. The formatting can't be wrong because when it was I received errors simply running sudo sphinxsearch start...so am not sure where to go from here. Thank you! Additional detail: This new table is also part of a new django app, so the sphinx.py file in the … -
Connect ZKTECO device from hosted django Site gives an error
I have created a site that connect ZKTECO K40 device. The connection Method is pretty simple from zk import ZK, const zk = ZK('192.168.1.13', port=4370, timeout=5) conn = zk.connect() This makes a connection while running from a local host connecting in the same network But after hosting the site. The site is not able to ping to the device and can't connect the device. How can i connect to the device connected on pc local network from hosted django site. I have hosted my site on Cpanel. enter image description here -
Sending emails with EmailMessage does not work when I deploy my application
I am developing an application with django. When I send emails locally with EmailMessage it works, but after deployment on heroku it doesn't work anymore. Here is the code in views.py from django.template.loader import render_to_string message = render_to_string("elec_meter/activate_email.html", { "user": user, "domaine": request.META['HTTP_HOST'], "uid": urlsafe_base64_encode(force_bytes(user.id)), "token": default_token_generator.make_token(user), "password": password,"matricule": agent.matricule } ) email_to_send = EmailMessage("Activation du compte", message, to=[email]) email_to_send.send() in settings.py EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = "my_email" EMAIL_HOST_PASSWORD = "password" EMAIL_USE_SSL = False I need help please -
Saving previous date and adding new date in Django
I have been working on an application where user adds his tasks which he is supposed to perform, once the task is added he can update the progress. In my model I have a date field, where user is supposed to enter the estimated completion date. My task model """Creating KRA Based on Institutional Objectives""" class KraBasedOnIo(models.Model): io = models.ForeignKey(InstitutionalObjectives, on_delete=models.CASCADE, related_name='kra_io') kra_title = models.CharField(max_length = 200) kra_description = models.TextField() kra_target = models.CharField(max_length=200) kra_added_date = models.DateTimeField(auto_now_add=True) estimated_date = models.???? While updating the progress, if the user wants to extend his timeline, I am looking for an option where I can save his current estimated completion date and add the new date also. And when I am displaying his progress I want to show his defined completion date and also the extended completion date in the template. I have tried a work around with model.JSONField() but couldn't reach there. There is no ListField or DictionaryField so what could be a better solution for this? -
How can I Restrict Users on OTT Platform (Like 3 Stream/Account) [Device Limitation]
I'm working on a OTT Platform For API using Django Rest Framework & for Website React & for App React Native. I'm trying to add Device limitation on account like 3 user can watch at a same time per account. How can I do it? -
Django DetailView getting values of ManyToMany relationship
I want to get post tags with ManyToMany relationship, to display related posts with the same tags. The problem is that I don't know how to access the tags of the current post. model class Post(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True) # author = 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') is_published = models.BooleanField(default=True) view class GetPost(DetailView): model = Post template_name = 'blog/post.html' context_object_name = 'post' def get_context_data(self, **kwargs): context = super().get_context_data() post_tags = Post.tags.all() incorrect #context['related'] = Post.objects.filter(tags__in=post_tags)[:3] am i need to override get_object?? or i can get it in context_data? ty -
Django admin: the most proper way to limit choices of dropdown window?
I am trying to customize dropdown for one of my models named Recipe. The problem is I do not want duplicates appear. Say, administrator selected choice X from the first dropdown, then he or she clicks on the second one but there are the same choices though. Because of it admin can create a recipe with two identical tags, for example, so I would want to deprecate this logic. -
Django Can you please explain my code why if statement not working?
I am using signals where I am using this logic for update user data. author = MyAuthors.objects.filter(user=instance) if not author and instance.is_blog_author and instance.email: MyAuthors.objects.create(user=instance,is_blog_author=instance.is_blog_author,first_name=instance) if I remove not from if statement then user data not updating. Can you please explain why user data not updating if I use if author and instance.is_blog_author and instance.email ? -
Sending Outcome of Javascript Calculations to Django Backend
I have an HTML form where users type in the name of items and value corresponding to it in an input form, which is reflected when the form is submitted to Django backend. In my HTML form I have included some Javascript so that the total of these values are reflected instantly without refreshing and even before submitting the form. My goal is to send the total amount reflected in the HTML to the related class Model after submitting. Note that the reason for the question is that the total values are not manually added they are directly calculated using Javascript. Here is a sample to make things more clear. Here is the HTML Template: <tr> <td> <input placeholder="Type in the Equipment and assets" type="text" class="form-control" name="item_1" id="item_1" {% if form.is_bound %}value="{{ form.item_1.value }}"{% endif %}/> {% for err in form.item_1.errors %} <small class="text-danger mb-2 ml-2">{{ err }}</small> {% endfor %} </td> <td> <h6 style="float:left; margin-right:5px; margin-top:7px">$</h6> <input type="number" class="form-control w-25 subtotal-group subtotal-group-1" name="item_1_amount" id="item_1_amount" {% if form.is_bound %}value="{{ form.item_1_amount.value }}"{% endif %}/> {% for err in form.item_1_amount.errors %} <small class="text-danger mb-2 ml-2">{{ err }}</small> {% endfor %} </td> </tr> <tr> <td> <input placeholder="Type in the Equipment and assets" type="text" … -
ValueError at /plants/plants/ too many values to unpack (expected 2) when using django_filters
Hej! I'm having trouble with my django filter. When I put {{myFilter}} in the template I only get an ObjectNumber and when I put {{myFilter.form}} I get the error: ValueError at /plants/plants/ too many values to unpack (expected 2) Does anyone have an idea what's going on? # views.py def plants_view(request): plants = Plant.objects.all() myFilter = PlantFilter(plants) context = {"plants": plants, "myFilter": myFilter} return render(request, 'plants/search_table.html', context) # filters.py class PlantFilter(django_filters.FilterSet): class Meta: model = Plant fields = ['name',] it doesn't matter if I use fields = [ ] or fields = '__all__' . template.html {% extends "landing/base.html" %} {% load static %} {% load i18n %} {% load admin_urls %} {% block page-title %} {%translate "View Plants" %} {% endblock %} {% block head %} <link href="{% static 'landing/vendor/tabulator/dist/css/tabulator.min.css' %}" rel="stylesheet"> <link href="{% static 'landing/vendor/tabulator/dist/css/bootstrap/tabulator_bootstrap4.min.css' %}" rel="stylesheet"> {% endblock %} {% block content %} <br> <div class="row"> <div class="col"> <div class="card card-body"> <form method="get"> {{myFilter.form}} <button class="btn-primary" type="submit">Search</button> </form> </div> </div> </div> </br> # models.py class Plant(models.Model): name = models.CharField( max_length=200 ) def __str__(self): return f"{self.name}" def serialize(self): return { "Name": self.name } -
SQL AND PYTHON EXPRESSION MEANING
Hello i found this expression on some source code i was reading. what does the comma sign mean (between order_item and created). Is 'created' a reserved word in sql? Also if you have any source to learn using sql with python would be great thanks. Heres the expression: order_item, created = OrderItem.objects.get_or_create( item=item, user = request.user, ordered = False ) -
Passing a list of strings (uuids) back and forth between django views and template
On one of the pages of my django project I have a check box to select uuids corresponding to a model. This is what I have on the views.py page and it works well to create a checkbox. def template_page(request, uuid_selects=None, option_1=False): ... class uuidCheckBox(forms.Form): uuid_selects = forms.ModelMultipleChoiceField(queryset=uuid_model, widget=forms.CheckboxSelectMultiple) uuid_select_field = uuidCheckBox() args.update({'uuid_select_field': uuid_select_field}) ... render(request, landing.html, args) On my template page I have this: <form action='get_uuid_selects' method='GET'> {{ uuid_select_field }} <input type='submit' value='Submit' /> </form> Which redirects back to this view: def get_uuid_selects(request): uuid_selects = request.GET.getlist('uuid_selects') return landing_page(request, uuid_selects) This all works fine however when I try to pass this list of uuids back to the template as a hidden value and return it when the user accesses another form the list doesn't work. For example I pass the list as an argument following the approach here This is the views.py for template: def template_page(request, uuid_selects=None, option_1=False): ... if uuid_selects: args.update({'uuid_selects': json.dumps(uuid_selects)}) ... render(request, landing.html, args) Then I pass this list of uuids back to the template page so that it is a hidden value in another form on the template.html page. <form action='to_option_1' method='GET'> <button type='submit'>Option 1</button> {% if uuid_selects %} <input type="hidden" value= {{ uuid_selects }} name="uuid_selects"> … -
Should I use build APIs for my POS web application?
I'm building a POS(Point of sale) web application using Django for my client. This is a single instance web app. I just want to know, should I build APIs to separate Backend and Frontend? Whare are the benefits to build the APIs? -
Soft Delete. Move records or create "deleted" column
I am a little confused about which is better for soft delete. There are two ways for Soft Delete. create table for deleted records.(In this way we will make copy for the records in the table of deleted records, then delete it from its table) create extra column called deleted,(In this way we will only change the status of this field to true , then at display records we will filter according to this extra field) -
How to do nested group by with annotation in django orm?
I have the following data: publisher title -------------------------- ----------------------------------- New Age Books Life Without Fear New Age Books Life Without Fear New Age Books Sushi, Anyone? Binnet & Hardley Life Without Fear Binnet & Hardley The Gourmet Microwave Binnet & Hardley Silicon Valley Algodata Infosystems But Is It User Friendly? Algodata Infosystems But Is It User Friendly? Algodata Infosystems But Is It User Friendly? Here is what I want to do: I want to count how many books of the same titles are published by each author. I want to get the following result: {publisher: New Age Books, title: Life Without Fear, count: 2}, {publisher: New Age Books, title: Sushi Anyone?, count: 1}, {publisher: Binnet & Hardley, title: The Gourmet Microwave, count: 1}, {publisher: Binnet & Hardley, title: Silicon Valley, count: 1}, {publisher: Binnet & Hardley, title: Life Without Fear, count: 1}, {publisher: Algodata Infosystems, title: But Is It User Friendly?, count: 3} My solution goes something along the lines of: query_set.values('publisher', 'title').annotate(count=Count('title')) But it is not producing the desired result. -
Cannot access request.data in log filter
I am using Django REST Framework, and following this django logging - django.request logger and extra context answer to include custom data to my log records. When trying to access record.request.data inside filter() (to store it to record.data as that answer suggests) I get RawPostDataException: You cannot access body after reading from request's data stream. I have tried many things, none of which worked. Cannot manually rewind the request's data stream, nor get a fresh copy of the request object. I never manually access request.body, as the SO answers suggest avoiding. Any help would be appreciated. -
Datetime received a naive datetime whereas I precised before the timezone
I am working a Django project. Here is my code : today = datetime.datetime.now() currentperiod = Day.objects.get(enddate__gte=today.date(), startdate__lte=today.date()) And I got that message : RuntimeWarning: DateTimeField Day.startdate received a naive datetime (2021-10-04 00:00:00) while time zone support is active. warnings.warn("DateTimeField %s.%s received a naive datetime " So I tried that : today = datetime.datetime.now() today = pytz.timezone("Europe/Paris").localize(today, is_dst=None) currentperiod = Period.objects.get(enddate__gte=today.date(), startdate__lte=today.date()) But it does not work whereas I used pytz, I suppose it comes from today.date() but I don't know how to proceed further ... Could you help me please ? Thank you very much ! -
Django add to many to many field working without save
What's the difference between group.reportedBy.add(request.user) group.save() AND group.reportedBy.add(request.user) It gets saved to the DB even without me doing .save() -
want to return dictionaries in lists Python Django
I want to return dictionaries of lists. With total, grand total, tax amount and name in each list. ''' #branches tax report and total - FBR and NFBR def branch_report(request, params): branch = Order.value('name', 'sub_total', 'grand_total', 'tax_amount') report = report[''] for name in Order.find_all('name'): info = { "name": branch.get('name'), "sub_total": branch.get('sub_total'), "grand_total": branch.get('grand_total'), "tax_amount": branch.get('tax_amount'), } report.append(info) return response_format(SUCCESS_CODE, SUCCESSFUL_RESPONSE_MESSAGE, report) ''' I want a result like this: ''' { "code": 200, "message": "Request was Successfull", "data": { "branches": [ { [ { "name": "Bedian 1", "id": 13, "sub_total": null, "tax_amount": null, "grand_total": null, "with_fbr_sub_total": null, "with_fbr_tax_amount": null, "with_fbr_grand_total": null, "without_fbr_sub_total": null, "without_fbr_tax_amount": null, "without_fbr_grand_total": null } ] } ''' -
Why is django not able to display Images and videos in AMP-story player
I have been stack on weeks trying to resolve this issue, I don't know why the AMP Story wouldn't load images that I post through the Django database, but somehow i have observed a very strange behavior of it being able to load images and videos which are not been requested from the database and also if images are been loaded from the asset directory i have to add the image format like JPG, PNG etc.. in order for it to display in the AMP Player. My major concern now is : 1.How do I request images and videos from the Django database to be able to work in the amp story player? 2.Since the player needs me to specify the file format of the image eg, JPG,PNG,JPNG etc.. How do i go about it? Here is a sample code of what i did, This is the player! {% extends "base.html" %} {% block content %} {% for a in amp %} <amp-story standalone title="Joy of Pets" publisher="AMP tutorials" publisher-logo-src="assets/AMP-Brand-White-Icon.svg" poster-portrait-src="assets/cover.jpg"> <amp-story-page id="cover"> <amp-story-grid-layer template="fill"> <amp-img srcset="{{ a.images.url }}" width="720" height="1280" layout="responsive" amp-story-player-poster-img> </amp-img> </amp-story-grid-layer> <amp-story-grid-layer template="vertical"> <h1>{{ a.title }}</h1> <p>{{ a.description }} </p> </amp-story-grid-layer> </amp-story-page> <!-- Page 1 (Cat): … -
How do I build a points based voting system (Django)
I have designed a system with five tables. Two tables are of users, buyers and sellers. And the remaining two tables are of products and companies. The buyers can have a relationship with the products and sellers can have relationships with products. The sellers and products also have relationships with the companies. Please note that the product can change companies at any time. Also, seller, product and buyer are all people (I labeled them that way for clarity) Now where I need help, I need to know how to design this part of the system based on this requirement. I need to create a points based rating system that will rate like a quiz, in such a way that; Every seller can rate product. Every product can rate seller. Both buyer and seller can rate company Company can rate product and seller Admin of the rate can rate companies and sellers SUMMARY Existing Relationships Buyer - products seller - products sellers - company product - company Goal Sellers will have 3 set of ratings from (buyers, company, product) each set with different unique parameters to rate. Product will have ratings from sellers alone Companies will have 3 sets of ratings … -
TinyMCE: Django admin custom HTML field displays incorrectly in HTML page
I use Django on backend and VueJS on frontend. I use tinymce for creation custom HTML field. description = CustomHTMLField('Description', blank=True, null=True) Settings for tinymce: TINYMCE_DEFAULT_CONFIG = { 'plugins': 'print preview textcolor importcss searchreplace autolink autosave save directionality visualblocks visualchars fullscreen image link media codesample table charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist lists wordcount textpattern noneditable help charmap emoticons', 'toolbar': 'insert | undo redo | formatselect | bold italic backcolor forecolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat | help', 'cleanup_on_startup': True, 'custom_undo_redo_levels': 10, 'width': 'auto', 'language': 'ru', } TINYMCE_FILEBROWSER = True Code of CustomHTMLField: from contextlib import suppress from tinymce import HTMLField class CustomHTMLField(HTMLField): def pre_save(self, model_instance, add): if not add: return super(CustomHTMLField, self).pre_save(model_instance, self.attname) html_field: str = getattr(model_instance, self.attname, "") with suppress(AttributeError): return html_field.replace('../../../../', '../../../../../') I need to add some text with list into this field. On Django admin page I have indent: But on frontend I don't have the indent: How can I fix the problem? -
i need help to convert this code from django to nodejs
i need help to convert this code from django to nodejs def post(self, request): path = '/achievements/achievements.json' base = str(settings.BASE_DIR) try: with open(base+path) as f: achievements = json.load(f) except: return Response(status=status.HTTP_404_NOT_FOUND) for achievement in achievements: self.find_or_create(achievement) return Response({'data': achievements}, status=status.HTTP_200_OK)