Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
How to disable access to a django APIs based on is_active boolean field?
I have an author's model with a field: is_active = models.BooleanField(default=False) I wish to restrict access to the author whose is_active=False. I can use something like this in every api: get_object_or_404(uuid=id, is_active=True) But I wish to globally restrict access to the UUID whose is_active=false, instead of actually writing this statement in every api. Is there a way I can do that? -
Django Rest Framework nested relationship performance on SerializerMethodField
I have been looking for an answer but get none. This is the situation: I have 3 models defined like this: class State(models.Model): name = models.CharField(max_length=150, null=False) code = models.CharField(max_length=5, null=False) class City(models.Model): name = models.CharField(max_length=150, null=False) code = models.CharField(max_length=7, null=False) state = models.ForeignKey(State, related_name='cities', on_delete=models.RESTRICT) class Home(models.Model): code = models.CharField(max_length=25, null=False city = models.ForeignKey(City, related_name='homes', on_delete=models.RESTRICT) The response that the people needs on homes is something like this [ { "code": "10011", "city": "Municipio 1", "state": "Departamento 1" }, { "code": "10012", "city": "Municipio 1", "state": "Departamento 1" } ] I was able to create that response doing this with the serializer: class HomeSerializer(serializers.ModelSerializer): city = SlugRelatedField(slug_field='name', queryset=City.objects.all()) state = SerializerMethodField() class Meta: model = Home fields = ['code', 'city', 'state'] def get_state(self, obj): return obj.city.state.nombre But Im not sure if this is the right way to do it, home is a table that is gonna grow up a lot (maybe 1M+ rows), and I am thinking that this solution is gonna hit the database multiple times. Now I know that I can add filtering and pagination, but I am concern about the performance of this solution. I also tried with depth = 2 but they hated it. I've … -
How to change the renaming pattern when there are duplicate files
Let's say I upload a file to my Django App (A.pdf) Over time I realize that that file contains an error. I want to upload that file back to my website and keep the old file, but I want the file name to change to A(1).pdf I implemented a drag & drop system with Dropzone.js and everything is working but, when a file is duplicated the system assigns new names randomly. This is an example: How can I get rid of the _QXjmarl string and replace it with (N) pattern? E.g. (1), (2), (3)...(45), (N) Dropzone.js: var Drop = Dropzone.options.DidDropzone = { autoProcessQueue: false, //stops from uploading files until user submits form paramName: "filename", // The name that will be used to transfer the file maxFilesize: 1024, // Maximum size of file that you will allow (MB) clickable: true, // This allows the dropzone to select images onclick acceptedFiles: '.psd, .csv, .doc, .docx, .xls, .xlsx, application/csv, application/docx, application/excel, application/msword, application/pdf,application/vnd.ms-excel, application/vnd.msexcel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, text/anytext, text/comma-separated-values, text/csv, text/plain, image/*, video/*,', //accepted file types maxFiles: 20, //Maximum number of files/images in dropzone parallelUploads: 20, previewTemplate: '<div class="dz-preview dz-image-preview">'+ '<div class="dz-image">'+ '<img data-dz-thumbnail />'+ '</div>'+ '<div class="dz-details">'+ '<div class="dz-filename"><span data-dz-name></span></div>'+ '<div class="dz-size" data-dz-size></div>'+ '</div>'+ … -
On adding a Model using the Admin Panel in Django, is there a way to implement altering other Models?
I am using the standard Admin Panel in Django that has a Model, Product, that contains its information. the Product has a TextField() Summary of words. I would like to implement a Keyword model that has a single word. The idea is that the Keyword would be applied to multiple Products if the Product has the Keyword's word in its Summary. I am trying to implement that when the Admin in the Admin panel adds a Keyword model, the server would automatically assign each Product that Keyword. The issue is that I do not know how to edit the Admin Panel's add function to edit other models upon adding one model. My current understanding in Django is that you could create a custom view to add a Keyword, but I would like to have the option to implement it in the Django Admin Panel as well. -
Using manytomany field as foreignkey in the other class under model in Django
Models.py Here I am trying to use the attribute: working_hours which is manytomany - as a foreignkey in other model please help me sort the concern if possible class AvailableTime (models.Model): available_time = models.CharField(max_length=100) def __str__(self): return str(self.available_time) class AttendantAvailability(models.Model): attendant_name_choices=[('AN1',"Ipsum Lorem"), ('AN2',"Lorem Lorem"),] attendant_name = models.CharField(max_length=3, choices=attendant_name_choices) def attendant_name_lookup(self): for choice in self.attendant_name_choices: if choice[0] == self.attendant_name: return choice[1] return '' booked_date = models.DateField(null=True, blank=True) working_hours = models.ManyToManyField(AvailableTime) def __str__(self): return str(self.working_hours) class ServiceDetail(models.Model): name = models.ForeignKey(ServiceName, null=True, on_delete=models.CASCADE,) category_name = models.ForeignKey(Category, default = None,on_delete=models.CASCADE,) preferred_time = models.ForeignKey(AttendantAvailability) def __str__(self): return str(self.preferred_time) This isn't working for me !! I need to use the Manytomany field "working_hours " as the foreignkey in other class ERROR: self.models_module = import_module(models_module_name) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\User\Service_Management\Salon_Services\models.py", line 45, in <module> class ServiceDetail(models.Model): File "C:\Users\User\Service_Management\Salon_Services\models.py", line 122, in ServiceDetail preferred_time = models.ForeignKey(AttendantAvailability) NameError: name 'AttendantAvailability' is not defined Please help! -
trouble with Django Channels and connecting with Flutter
Problem: When trying to connect to channels, I get an error in flutter: WebSocketChannelException: WebSocketException: Connection to 'http://"###my ip ###":8000/ws/joingroup/8598969d-3dfa-4017-849c-dcbb71c1f9f0/#' was not upgraded to websocket I am using the websocket channel package and in a flutter controller I have: WebSocketChannel? channel; //initialize a websocket channel bool isWebsocketRunning = false; void startStream() async { if (isWebsocketRunning) return; //check if socket running var url = 'ws://${ip}:8000/ws/joingroup/${Get.parameters['groupid']}/'; this.channel = WebSocketChannel.connect( Uri.parse(url), //connect to a websocket ); channel!.stream.listen( (event) { print(json.decode(event)); }, onDone: () { isWebsocketRunning = false; }, onError: (error) { debugPrint('ws error $error'); } ); } question 1) why does it say 'http://..." when I clearly outlined it as a ws url. in the back end I am using django channels. app routing:: from django.urls import re_path from django.urls import path #this is utilizing relative paths. this is more advanced paths. # from . import consumers websocket_urlpatterns = [ path('ws/joingroup/<slug:groupid>/', consumers.ChatConsumer ) ] and routing for project: # mysite/routing.py from channels.auth import AuthMiddlewareStack #hooking into auth that django provides^ from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator import myapp.routing from django.core.asgi import get_asgi_application # the allowedhosts is for what ever is in your allowehost in setting.py application = ProtocolTypeRouter({ # (http->django … -
Timestamps are added to the model with a different timezone
I am aware that thousands of similar questions have been asked on SO, but after researching a few hours I did not find any solution that worked. I am using Django 3.2.8 I have checked many StackOverflow questions and answers, none have worked for me. For example this one I also checked the official docs like ten times. Here is my models.py: from django.db import models from django.contrib.auth.models import User class FileHistory(models.Model): filename = models.FileField(null=True, blank=True, upload_to="project_files/") user = models.ForeignKey( User, null=True, blank=True, on_delete=models.SET_NULL, ) timestamp = models.DateTimeField(auto_now_add=True, blank=True) And my settings.py (truncated), following the suggested configuration (L10N false and Time_Zone changed to 'Asia/Tokyo': TIME_ZONE = 'Asia/Tokyo' USE_I18N = True USE_L10N = False USE_TZ = True