Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Save some fields from one model to another.When i create News I want the title,mainphoto,created and gallery_news fields were saved in the Photo model
When i create News I want the title,mainphoto,created and gallery news fields were saved in the Photo model. I tried to do it by save method in serializers.py, but it did not work.Can someone help me with this problem models.py class News(models.Model): title = models.TextField(blank=True, verbose_name='Название') mainphoto = ThumbnailerImageField(upload_to='images/', null=True, verbose_name='Фото', help_text='Размер фотографии должен быть 1200x550') created = models.DateField(verbose_name='Дата создания') class Meta: verbose_name = 'Новость' verbose_name_plural = 'Новости' ordering = ('-created',) def __str__(self): return str(self.title) class Gallery(models.Model): image = models.ImageField(blank=True, null=True, upload_to='gallery/', verbose_name='Галерея') gallery_news = models.ForeignKey(News, related_name='gallery', on_delete=models.CASCADE, null=True, blank=True, verbose_name='Галерея') class Meta: verbose_name = 'Галерея новостей' verbose_name_plural = 'Галерея новостей' def __str__(self): return str(self.gallery_news) class Photo(models.Model): title = models.CharField(max_length=155, verbose_name='Название') preview = models.ImageField(upload_to='images', null=True, verbose_name='Превью') created = models.DateField(default=timezone.now, verbose_name='Дата мероприятия') class Meta: verbose_name = 'Фото галерею' verbose_name_plural = 'Фото галерея' def __str__(self): return self.title class PhotoGallery(models.Model): image = models.ImageField(blank=True, null=True, upload_to='images/', verbose_name='Галерея') photo_gallery = models.ForeignKey(Photo, related_name='gallery', on_delete=models.CASCADE, null=True, blank=True, verbose_name='Галерея') class Meta: verbose_name = 'Фото галерею' verbose_name_plural = 'Фото галерея' def __str__(self): return str(self.photo_gallery) News.title=Photo.title News.created=Photo.created News.mainphoto=Photo.mainphoto Gallery.gallery_news=PhotoGallery.photo_gallery My serializers.py class GallerySerializer(serializers.ModelSerializer): class Meta: model = Gallery fields = ('__all__') class PhotoGallerySerializer(serializers.ModelSerializer): class Meta: model = PhotoGallery fields = '__all__' class NewsSerializer(serializers.ModelSerializer): gallery = GallerySerializer(many=True, read_only=True) created = serializers.DateField(format='%Y-%m-%-d', … -
foreign key problem in postgres' logical replication in django
I configured postgres logical replication between several DBs in my django project to replicate common data like django_content_types, comments etc. from primary db to peripheral DBs. There is no master or slave DBs though, because data from peripheral DBs is also replicated in primary DB. I call it primary because I have some basic data in it. And I use django-viewflow application, so instances of viewflow app are read from primary db. But I have models inherited from django-viewflow's models and they are read from perpheral DBs. The system is like as below: class Process(models.Model): # django-viewflow model, read from primary class SomeProcess(Process): # inherited model, read and written into another DB Also there is a model called Task, that has a foreign key to process and a self-referencing field called "previous" and there is a table called viewflow_task_previous, that has task_ids like this: class Task(models.Model): process = models.ForeignKey(Process, on_delete=models.CASCADE, verbose_name=_('Process')) previous = models.ManyToManyField('self', symmetrical=False, related_name='leading', verbose_name=_('Previous')) Naturally I use django routers. So the problem is that when task object is created in peripheral DB it is replicated to primary, but viewflow_task_previous table is only read from primary db, so sometimes task data is not in time to replicate to … -
sending data from PLC to a web server http://localhost:8080
Please help!! I have a Programmable Logic Controller (PLC) which can work on ethernet to communicate to other devices over TCP/IP protocol. Now my question is: "Is it possible to receive data into the web server from external device like PLC?? Also, is it possible for the web server to send data over TCP/IP protocol to other controller devices (PLC in this case) ??" Please help me out. This ques has been haunting me since many days. -
Missing required flag in Heroku and Django
I am using Heroku to deploy my simple Django app. But when I try to create the secret command, it gives me an error. The steps are from real python -
Django: help in implementing error reporting
I am trying to implement an error reporting system that directly sends the errors to slack. The steps are like this: My API fails and return a 400 error. The Middleware will check if the response code equals 400 Call the function to send the error message to slack. API: class SomeWorkingAPI(APIView): permission_classes = (AllowAny,) def get(self, request): client = request.query_params.get('client', None) try: #do something except: error_msg = "error occurred in the API" return Response({'message': error_msg}, status=status.HTTP_400_BAD_REQUEST) return Response(result, status=status.HTTP_200_OK) Middleware: def error_reporting(request, error_msg=None): # this is the function that sends the message to my slack channel return 'error reported successfully' class SomeMiddleWare(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_template_response(self, request, response): if response.status_code >= 400: error_reporting(request, error_msg=response['message']) The help I need: I want to send the error message returned from the API (return Response({'message': error_msg}, status=status.HTTP_400_BAD_REQUEST)) to the middleware. How can i achieve that? What i'm doing in middleware (response['message']), is throwing KeyError. Since the middleware has both request and response, it would be great if I can get all the query params and payload from the request. When I'm using request.query_params in the error_reporting function, I'm getting AttributeError: 'WSGIRequest' … -
Hide the (obvious) relation from nested serializer in DRF
Django + rest framework. This seems like it should be a frequent and common issue, but I could not find anything like it, so here I ask: I have a Document and its Items: class DocumentSerializer(ModelSerializer): ... items = ItemsSerializer(many=True, required=False) class Meta: model = Document exclude = () class ItemsSerializer(Serializer): ... class Meta: model = DocumentItem exclude = ('document', ) # hide the ForeignKey as it should be obvious by nesting Expected result for JSON serialized data something like: { "id": 1, "date": "2021-01-01T00:00:00Z", "title": "Test doc", "items": [ {"code": 43, quantity: 3}, {"code": 28, quantity: 15} ] } It should be fairly obvious that the "document" field from ItemsSerializer should be derived from the parent serializer at the time of storage. The field itself being a ForeignKey to Document, of course. However, I can't get past the ValidationError({"document":["This field is required."]}). If I say the field is not required, then save()complains AssertionError: The '.create()' method does not support writable nested fields by default. What is the accepted way of handling relations like this in serializers? -
Why is Exception Value: cursor "_django_curs_140539182187712_sync_1" error generated in Django?
I am getting the below error on Herokuapp site, while the local version of my Django app works just fine. Any help or guidance would be appreciated. (Also, the site was not being recognized earlier, and had to add SITE_ID=1 to my settings.py file) Exception Value: cursor "_django_curs_140539182187712_sync_1" InvalidCursorName at /admin/home/influencers/add/ cursor "_django_curs_140539182187712_sync_1" does not exist Request Method: GET Request URL: http://www.[mysite].com/admin/home/influencers/add/ Django Version: 3.1.13 Exception Type: InvalidCursorName Exception Value: cursor "_django_curs_140539182187712_sync_1" does not exist Exception Location: /app/.heroku/python/lib/python3.9/site-packages/django/db/models/sql/compiler.py, line 1159, in execute_sql Python Executable: /app/.heroku/python/bin/python Python Version: 3.9.6 Python Path: ['/app/rathee', '/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python39.zip', '/app/.heroku/python/lib/python3.9', '/app/.heroku/python/lib/python3.9/lib-dynload', '/app/.heroku/python/lib/python3.9/site-packages', '/app/.heroku/python/lib/python3.9/site-packages/odf', '/app/.heroku/python/lib/python3.9/site-packages/odf', '/app/.heroku/python/lib/python3.9/site-packages/odf', '/app/.heroku/python/lib/python3.9/site-packages/odf', '/app/.heroku/python/lib/python3.9/site-packages/odf', '/app/.heroku/python/lib/python3.9/site-packages/odf', '/app/.heroku/python/lib/python3.9/site-packages/odf', '.']``` The error can be viewed here – http://www.manishrathee.com/Article. Many thanks! -
How to know which domain is running? [closed]
I have two servers running only one celery at a time, and I need to know which server is running when running cron classes.Is there any way to find it? -
how to upload image to django and nextJs using formidable
I'm new to NextJs and I have no idea what I'm doing. I tried to upload an image from Postman it worked, but when I tried to use NextJs (send data to /api and then send data to the backend it didn't work), then I tried to use formidable, but I found no answer how to upload the image to Django from NextJs with formidable(I should send it at first to/api because i should send the token too). -
Use template tag (in HTML ) in view as a variable
I'm creating a web page on Django, I want to create next and previous post in the bottom of blog page. is there any way to use a simple tag like {{post.title}} in HTML and refer it to view page to find the index of current post ? -
Django - Comparing datetime values in template
I need to display datetime values differently for events in a Django HTML template if the date components are equal, for example, where start and end times occur on the same date, I need to display in this format 'Wed 15 Dec 2021 18:00 to 21:00' and where start and end times occur on different dates, I need to display the full datetime value for both the start and end dates in this format 'Wed 15 Dec 2021 09:00 to Thu 16 Dec 2021 18:00' I've had a play with the following code but I always get a difference as I don't think it is comparing the formatted date, but the full datetime value. <li> {% if "{{ date.start|date:'D d M Y' }}" == "{{ date.end|date:'D d M Y' }}" %} {{ date.start|date:"D d M Y" }} {{ date.start|time:"H:i" }} to {{ date.end|time:"H:i" }} {% else %} {{ date.start|date:"D d M Y" }} {{ date.start|time:"H:i" }} to {{ date.end|date:"D d M Y" }} {{ date.end|time:"H:i" }} {% endif %} </li> I could put a boolean flag in the database and do it in the view but would much prefer to do it in the template if possible; any ideas appreciated! … -
How to update a Datatable via Django - Ajax call
I have a table that displays the content from a model whenever someone accesses the URL /project_page. On that page, the user can add files and I would like the table to be updated in real-time without having to constantly refresh. For that purpose, I have tried to implement an Ajax function that updates the table content every few seconds. Since it is something that was suggested a few years ago here I think the function is implemented and I receive the data properly in the Ajax success function but I don't know how to 'inject it' to the table. I would also like to know if there is a more optimal or pythonic way to achieve this result. urls.py path('project_page_ajax/', views.project_page_ajax, name='project_page_ajax'), views.py @login_required def project_page(request): context = {} context['nbar'] = 'projects' if request.method == 'POST': print(request.FILES) form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): file_hist = form.save(commit=False) file_hist.user = request.user # file is saved file_hist.save() file_hist_results = FileHistory.objects.all().filter(user=request.user) context['file_hist_results'] = file_hist_results print(type(context['file_hist_results'])) return render(request, 'project_page.html', context) print (form.errors) else: form = UploadFileForm() file_hist_results = FileHistory.objects.all().filter(user=request.user) context['file_hist_results'] = file_hist_results context['form'] = form return render(request, 'project_page.html', context) @login_required def project_page_ajax(request): response = dict() if request.method == 'GET': file_hist_results = FileHistory.objects.all().filter(user=request.user).values() #response.update({'file_hist_results': file_hist_results}) … -
Dictionaries in Django Views: Iterating over a dictionary containing key-queryset pairs
Currently, I have a very bloated detail view function in my Django Views module. The main reason for this is because I'm creating lists from dictionaries (between 2-50 key-value pairs) by iterating over each dictionary and appending the result to a unique list. These lists are then made available to the templates for further iteration and display. Here is an example of a list from dictionary code within the detail view function in Views: def bacteria_detail_view(request, slug): ... temperature = [] temp_dict = {'low': My_model.growth_temp_low, 'room_temp': My_model.growth_temp_room, 'body_temp': My_model.growth_temp_body, 'high': My_model.growth_temp_high} for key, val in temp_dict.items(): if val is not None: temperature.append(val) ... This is then displayed in the template: <li> {% if temperature %} <i style="color: blue"><b>T</b>emperature tolerance:</i> {% for t in temperature %} {{ t|growstemp|default_if_none:''}} {% endfor %} {% endif %} </li> A custom template filter is applied to the iterated object: @register.filter(name='growstemp') def growstemp(value): if value: if "+" in value: value = value.replace("(+)", "") return f"grows at {value}\u2103;" elif "neg" in value: value = value.replace("(neg)", "") return f"doesn't grow at {value}\u2103;" ... else: return '' This approach works well, but I suspect it is not optimal and it does crowd the View function. Is there a more … -
Postgres search functionality that allows to user to search UUID string in database table in Django APP
I would like to use postgres to perform searches on a django app, most pf the resources seem to focus on full text search. However I would like the ability to search by UUID, Peoples' names, Reference numbers etc. I have googled to find resources and examples, but thinking is coming up. Please assist, with links or ideas on hoe to tackle this. Our Django app is using SQLAlchemy -
Django autoescape still displays HTML Tags for a custom filter
I have created a custom filter, that basically looks like this from django import template from datetime import datetime from django.contrib.humanize.templatetags.humanize import intcomma from django.utils.safestring import mark_safe register = template.Library() def into_bs_badge(value): # <span class="badge badge-primary">Primary</span> # <span class="badge badge-secondary">Secondary</span> # <span class="badge badge-success">Success</span> # <span class="badge badge-danger">Danger</span> # <span class="badge badge-warning">Warning</span> # <span class="badge badge-info">Info</span> # <span class="badge badge-light">Light</span> # <span class="badge badge-dark">Dark</span> badge = '<span class="badge badge-primary">' + str(value)+ '</span>' return badge # return mark_safe(badge) register.filter('into_bs_badge', into_bs_badge) In my page I have {% autoescape off %} {{ value.credits_count | into_bs_badge}} {% endautoescape %} But I still gets something like, instead of rendering the actual badge <span class="badge badge-primary">28</span> I have also tried return mark_safe(badge) But when I use mark_safe i get nothing display in the page, I am wondering what could i possible be missing -
django.utils.crypto get_random_string() causing duplicate key error?
I'm using get_random_string() from django.utils.crypto to generate a random short_id for my model. There's only a few dozen entries. from django.utils.crypto import get_random_string class MyModel(models.Model): ... short_id = models.CharField(default=get_random_string, max_length=12, unique=True) For some reason, I'm getting a duplicate key error when I try to run my migration: Any ideas? DETAIL: Key (short_id)=(88hUwNQjTIns) is duplicated. -
How to add IP whitelist in an HTTP API?
I want to add the feature of allowing only some IP addresses(list would be given already) to access my HTTP API, written with DJango and Django Rest Framework. -
How to get recent values in this db?
I use sqlite. class Member(models.Model): member_id = models.AutoField(primary_key=True) is_update = models.IntegerField(default=0) member_name = models.CharField(max_length=50) member_group = models.IntegerField(default=0) room_name = models.CharField(max_length=20) bed_name = models.CharField(max_length=20) gender = models.IntegerField(default=0) birth_date = models.DateField() phone_number = models.CharField(max_length=11) protector = models.CharField(default='protector',max_length=50) def __str__(self): return str(self.member_id) def initIsUpdate(self): self.is_update = 0 return 0 class Inpatient(models.Model): member_id = models.ForeignKey(Member, on_delete=models.CASCADE, db_column = 'member_id', related_name='member') inpatient_status = models.IntegerField(default=0) is_in_room = models.IntegerField(default=0) is_on_bed = models.IntegerField(default=0) heart_rate = models.IntegerField(default=0) breath_rate = models.IntegerField(default=0) update_time = models.DateTimeField(auto_now_add=True, blank=True) protector_name = models.CharField(max_length=50) def __str__(self): return str(self.member_id) And Members are 4 people.. Each Members have same values in Inpatient DB. It gets new queryset for every 1 sec. And I want get 4 Member's most recent Inpatient DB. How I get that DB?? -
How to generate a testing report in Django using selenium and LiveServerTestCase?
I have been using LiveServerTestCase to build test cases for my Django project for a month. Now, I am creating more test cases using Selenium and LiveServerTestCase together to test how my project runs automatically. I want to know how can I generate and export a testing report using Selenium and LiveServerTestCase. Is there an inbuilt solution from selenium that allows me to do so? Or I have to code the part of generating the file? Sorry, I am new to Django and Selenium. Thanks in advance! -
How to calculate date between different fields in two querysets with same foreign key in Django
I am using Django. Is there a way to count between different fields in a queryset with the same foreign key??!! That is, we want to subtract register_date from injection_date. You want to get (2021-1-03) - (2021-10-31) = 3days. injection_date enroll_date student_id (외래키) 2021-10-31 52 2021-11-03 52 Below is the code I've written so far, how do I fix it?! Please help. [views.py] injection_enroll = Student.objects\ .annotate(injection_enroll=F('injection_date') - F('enroll_date'))\ .values('injection_enroll') -
Text editor summernote for admin panel Django loading very slowly
I have an Enterprise model and there are more than 60 fields in this model, Summernote-Django has been added to the text editor. In my case, 25 fields in one model have been added to the text editor by the Summernote-Django, the problem is that this model on the admin panel is very, very slow to load. How can I optimize Summernote-Django? I added 'lazy': True to the settings, but it didn't help.Perhaps you would recommend another library for adding text editors to the django administration more optimized? Here is a screenshot on the Enterprise page, on dev tools shows that more than 100 js/jQuery files are being uploaded from Summernote-Django -
Multiple templates in a single Listview
I have some ListViews implemented seperately with different template_names with similar model,How can i use implement them in one single List view that can take multiple templates? Views.py class ManagerOpenedTicketView(LoginRequiredMixin,TemplateView): template_name = 'app/pm_open_tickets.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['tickets'] = Ticket.objects.filter(status = 'Opened',created_by = self.request.user) return context class ManagerCompletedTicketView(LoginRequiredMixin,TemplateView): template_name = 'app/pm_completed_tickets.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['tickets'] = Ticket.objects.filter(status = 'Completed',created_by = self.request.user) return context -
What is the difference in using Django Rest API vs django.contrib.auth to build a login/logout app
I am new to Django and I want to build a login and logout for a chat app I am making which I plan to deploy eventually. From the online tutorials I see, there are some that use the Django Rest API framework, and some use the pre-installed django.contrib.auth Is there any difference in choosing which to use? -
Trying to stay DRY in Django: Refactoring repetitive code in Views
I have a lot of different list views for tables. Each view differs only in the template used. My only successful strategy involves using a decorator containing the common code and then returning 'pass' for the view function. The problem I face is if I want to add individual code to a specific list view that differs from the others. Is there a better way of doing this? Here is my decorator: def my_decorator(html=""): def my_decorator(*args, **kwargs): def wrapper(request, *args, **kwargs): bacteria = Bacteria.objects.all() bacteria_count = bacteria.count() bacteriaFilter = BacteriaFilter(request.GET, queryset=bacteria) bacteria = bacteriaFilter.qs remaining = bacteria.count() common_tags = Bacteria.tags.most_common()[:8] ''' context = {"bacteria": bacteria, 'common_tags': common_tags, 'bacteria_count': bacteria_count, 'bacteriaFilter': bacteriaFilter, 'remaining': remaining} ''' return render(request, html, locals()) return wrapper return my_decorator And here are several examples (I have over 15 tables) of the list view functions: @my_decorator(html="bacteria/generalPhysiology.html") def general_physiology_view(request): pass @my_decorator(html="bacteria/enzymeActiveTable.html") def enzyme_activity_table_view(request): pass -
Django autocomplete light Select2 widget not appearing
I have been following the DAL tutorial and can access a json object at http://127.0.0.1:8000/entry/river-autocomplete/?q=S So i know my view is working. Beyond that I cannot seem to get anything but the standard widget for ForignKey. From looking at the following posts in stackoverflow I feel that some static files or javascript libraries are not loading properly but for the life of me I cannot figure out how to fix this. django-autocomplete-light template not rendering autocomplete widget django-autocomplete-light displays empty dropdown in the form Below are all of the files that I think pertain to this issue. If I can clarify things any further please let me know. views.py #autocomplete view class RiverAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): #User filtering code goes here if not self.request.user.is_authenticated: return River.objects.none() qs = River.objects.all() if self.q: qs = qs.filter(river_name__istartswith=self.q) return qs models.py class River(models.Model): river_name = models.CharField(max_length=50) aw_id = models.CharField(max_length=20) state = models.CharField(max_length=5) def __str__(self): return "{river}".format(river=self.river_name) class JournalEntry(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField() river = models.ForeignKey("River", on_delete=models.CASCADE) flow = models.FloatField() description = models.TextField(max_length=250) public = models.BooleanField(default=False) # picture = models.ImageField() def __str__(self): return "{river}--{date}".format(river=self.river, date=self.date) forms.py from django import forms from . import models from .widgets import FengyuanChenDatePickerInput from dal import autocomplete class …