Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Redirecting after a XMLHttpRequest
I'm drawing on a canvas and then I upload the drawing to a database (Django). I have made this work by creating a Blob and sending a Form with XMLHttpRequest. But once uploaded, how do I navigate to the page that shows this new file? I would like the server to send a redirect, but that doesn't work and apparently that's not how you should do it. But how otherwise? Here's the Javascript: function submitFunction() { canvas = document.getElementById('myCanvas'); var dataURL = canvas.toDataURL("image/jpeg"); form = document.getElementById('myForm'); formData = new FormData(form); blob = dataURItoBlob(dataURL); url = window.location.href; xhr = new XMLHttpRequest(); xhr.open('POST', url, true); formData.set('artwork_img', blob, 'artwork.jpeg'); xhr.send(formData); } And here's the Django View: def create (request, id): artwork = get_object_or_404(Artwork, pk=id) context = {'artwork' : artwork} if request.method == 'POST': form = ArtworkForm2(request.POST, request.FILES) if form.is_valid(): newChild = Artwork() newChild.parent = artwork newChild.artwork_img = form.cleaned_data['artwork_img'] newChild.artwork_title = form.cleaned_data['artwork_title'] newChild.ancestors = artwork.ancestors+1 newChild.save() newChild.updateAncestors() # ---> this is kind of what I'd like to do: return redirect('showwork', newChild.id) else: print(form.errors) else: form = ArtworkForm2() context.update({'form' : form}) return render(request, 'exp/create.html', context) -
Why my 127.0.0.1/800 is not connecting to Django admin database even after migrate 001 initial.py
as I am new to Django. I create a project named as trackback in which I create an app named as projects after successfully creating superuser to my Django admin and migrate my 0001 initial.py database is not connecting. I register my model name inadmin.py too. -
Django - Adding meta table for dynamic table
I would like to create a dynamic table as Person. The extra information depends on user's requirements as key-value. So, I'm looking what is the correct way to do this operation. My codes are: class Person(models.Model): age = models.CharField(..) name = models.CharField(..) class PersonMeta(models.Model): value = models.CharField(max_length=255) key = models.CharField(max_length=255) person = models.ForeignKey(Person, on_delete=models.CASCADE) with this way it works but is this correct way to do that? -
Errors getting started with django-eav2
I'm trying to make a simple app for users to create multiple choice tests for each other, where they can specify which data type should apply to the answer for each question. To this end, I'm trying to get django-eav2 working, following this guide. However, I run into errors as soon as I try to makemigrations. Using eav.register: from django.db import models from django.utils.translation import ugettext as _ from eav.models import Attribute class Question(models.Model): class DataType(models.TextChoices): TEXT = 'TXT', _('Text') INTEGER = 'INT', _('Integer (whole number)') FLOAT = 'FLT', _('Float (number with fractional parts, e.g. 3.14159)') question_text = models.CharField(max_length=400) question_type = models.CharField(max_length=3, choices=DataType.choices, default=DataType.TEXT) class Answer(models.Model): question = models.ManyToManyField(Question) import eav eav.register(Answer) Attribute.objects.create(slug='txt_value', datatype=Attribute.TYPE_TEXT) Attribute.objects.create(slug='int_value', datatype=Attribute.TYPE_INT) Attribute.objects.create(slug='flt_value', datatype=Attribute.TYPE_FLOAT) I get "django.db.utils.OperationalError: no such table: eav_attribute" Using decorators: from django.db import models from django.utils.translation import ugettext as _ from eav.models import Attribute from eav.decorators import register_eav #Dynamic user-specified data types is tricky, see # https://stackoverflow.com/questions/7933596/django-dynamic-model-fields class Question(models.Model): class DataType(models.TextChoices): TEXT = 'TXT', _('Text') INTEGER = 'INT', _('Integer (whole number)') FLOAT = 'FLT', _('Float (number with fractional parts, e.g. 3.14159)') question_text = models.CharField(max_length=400) question_type = models.CharField(max_length=3, choices=DataType.choices, default=DataType.TEXT) @register_eav class Answer(models.Model): question = models.ManyToManyField(Question) Attribute.objects.create(slug='txt_value', datatype=Attribute.TYPE_TEXT) Attribute.objects.create(slug='int_value', datatype=Attribute.TYPE_INT) Attribute.objects.create(slug='flt_value', datatype=Attribute.TYPE_FLOAT) I get … -
After any bug in Django html i get same exception: 'ascii' codec can't decode byte 0xe2 in position 9735: ordinal not in range(128)
Exception inside application: 'ascii' codec can't decode byte 0xe2 in position 9735: ordinal not in range(128) File "/venv/lib/python3.6/site-packages/channels/http.py", line 213, in __call__ await self.handle(body) File "/venv/lib/python3.6/site-packages/asgiref/sync.py", line 150, in __call__ return await asyncio.wait_for(future, timeout=None) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/tasks.py", line 333, in wait_for return (yield from fut) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/concurrent/futures/thread.py", line 55, in run result = self.fn(*self.args, **self.kwargs) File "/venv/lib/python3.6/site-packages/asgiref/sync.py", line 169, in thread_handler return func(*args, **kwargs) File "/venv/lib/python3.6/site-packages/channels/http.py", line 246, in handle response = self.get_response(request) File "/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 75, in get_response response = self._middleware_chain(request) File "/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 36, in inner response = response_for_exception(request, exc) File "/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 90, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 125, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "/venv/lib/python3.6/site-packages/django/views/debug.py", line 94, in technical_500_response html = reporter.get_traceback_html() File "/venv/lib/python3.6/site-packages/django/views/debug.py", line 332, in get_traceback_html t = DEBUG_ENGINE.from_string(fh.read()) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/encodings/ascii.py", line 26, in decode return codecs.ascii_decode(input, self.errors)[0] 'ascii' codec can't decode byte 0xe2 in position 9735: ordinal not in range(128) Always get the same exception when i get error in html files (include django admin). Project haven't any cyrillic symbols, only latin. -
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')