Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django order by count by date
Good morning! I have tried many things but can't get to order my post by likes and by date. For example, I wish to have a "popular post" page, which contains only posts from today, but order by most liked. Here are my models: Class Post(models.Model): name = models.CharField(max_length=40, default=None, null=False) cover = models.CharField(max_length=100, default=None, null=True, blank=True) content = models.TextField(max_length=2000, default=None, null=False) class VoteDate(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) date = models.DateTimeField(default=timezone.now) The closest I came but did not work is this line: hot_today = Post.objects.annotate(count=Count('votedate', filter=Q(votedate__date=datetime.today()))).order_by('count')[:30] Thank you for your help! -
Django social share fb link with 500 internal error header [closed]
I've installed django-social-share and added a social share button to fb. How can the text of the shared link be customized? Right not it is showing Server Error 500 although when you click on the link it actually works fine. I cant seem to find the answer to this problem in the library documentation. The goal is that in stead of "Server Error (500)" there would be the header of the page and a favicon like you'd normally see in shared pages In my template I have added this template tag for the social share {% post_to_facebook "Random text" %} -
Can I specify a custom default value to be used when migrating after adding a new parent class in a Django model?
I am writing a Django app that provides a very simple model called Submittable, which users of the app are supposed to inherit from when they want to use other functionalities of the app. # app1 class Submittable(models.Model): is_submitted = models.BooleanField(default=False) # other methods here # app2 class Paper(Submittable): # some fields However, when I add this as a parent to an already existing model in another app and run makemigrations, I am asked to provide a default value to the new field submittable_ptr_id. The problem is, that I want this field to simply point to a new instance of Submittable but I don't know how to do that. I know, that I could simply edit the migration file created like so: class Migration(migrations.Migration): dependencies = [ # some dependencies ] operations = [ migrations.AddField( model_name='Paper', name='submittable_ptr_id', # here I set default to a function from the Submittable app that just creates a new submittable field=models.OneToOneField(auto_created=True, default=app1.utils.create_submittable, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key =True, serialize=False, to='app1.Submittable'), preserve_default=False ), ] But I want to know if I can specify anything somewhere in app1 that makes this happen automatically? I don't want users of the app to have to make this change themselves and instead, … -
File read issue using python
I am trying to read file(text),used readlines() function but not getting in format like bold,headings,italics in the read file -
Read some products Data from a csv file using python in command line
i have a csv file which have information about all the products so i want to perform some basic functions like You have to show data based on user selection. User will select filters he wants to apply (he can select multiple fields). Also user can select the fields he wants to see like he can select full item or he wants to see only price of item or he wants to see some specific fields as am new to it so kindly help to learn. I have read python basics like its Datastructure , loops, file system Here is the sample Data -
TypeError: Object of type ImageFieldFile is not JSON serializable - django
I'm trying to make post via ajax request and JsonResponse but when i try to upload image to the form and submit it raise this error from server side : TypeError: Object of type ImageFieldFile is not JSON serializable and this error from client side (in the console browser) Uncaught TypeError: Illegal invocation and here is my models.py and my views.py @login_required def create_modelcategory(request): form = ModelCategoryForm() if request.is_ajax() and request.method == 'POST': form = ModelCategoryForm(request.POST,request.FILES) if form.is_valid(): obj = form.save(commit=False) obj.admin = request.user obj.save() data = { 'id':obj.id, 'admin':obj.admin.username, 'category':obj.category.category, 'model':obj.model, 'giga':obj.giga.giga_byte, 'img':obj.image.url, } return JsonResponse({'success':True,'data':data},status=200) else: return JsonResponse({'sucess':False,'error_msg':form.errors},status=400) context = { 'form':form } return render(request,'storage/modelcategory.html',context) and here is my html and jquery-ajax functions is there something i've missed to add ? or if its not right way to save image data into database via ajax and jsonresponse please let me know . I much appreciate your helps .. -
localization bootstrap-Table not displaying as wanted
Im using the following code: Based on the browser language i change up the locale Even if the browser fex is en-US its get defaulted to dutch <script src="https://unpkg.com/bootstrap-table@1.18.3/dist/bootstrap-table.min.js"></script> <script src="{% static 'js/bootstrap-table-nl-BE.js'%}"></script> <script src="{% static 'js/bootstrap-table-fr-BE.js'%}"></script> <script> $(document).ready(function() { var userLang = navigator.language || navigator.userLanguage; if (userLang == "fr" || userLang == "fr-FR" || userLang == "fr-BE") { language = "fr-BE" } else { language = "nl-BE" } $("#table").bootstrapTable({ locale : language, }) } ) </script> But even when the browser is in en-US it keeps displaying in French. -
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 …