Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Can't save file to FileField
According to Django Docs, I'm trying to save File or ContentFile to FileField. When I access FileField it doesn't give me a FieldFile proxy, so I don't have a save method like all examples. Can I use djangonic :) way to solve this? (Django 3.2) Model: class Report(InModelFileStorageMixin, models.Model): ... class InModelFileStorageMixin: file = models.FileField( _('Report File'), blank=True, null=True, ) My exception is: ipdb> obj.file.save *** AttributeError: 'FileField' object has no attribute 'save' -
How to avoid Django NoReverseMatch Error?
I am confused with Django redirect. The idea is to redirect users to an external URL, but I always get the NoReverseMatch Error. My urls.py from django.urls import path from . import views from django.views.generic.base import RedirectView path('home', views.home_view, name="home"), # redirect user from home to go-to-django path('go-to-django/', RedirectView.as_view(url='https://www.djangoproject.com/'), name='go-to-django'), # some dummy url my views.py from django.urls import reverse from django.shortcuts import redirect, render def home_view(request): return redirect(reverse('go-to-django')) -
Django - multiple queries with pagination
After updating from Django 1.9 to 3.2.5 my advanced search function doesn't work with pagination anymore. I have two search functions. One which is always available in the header to search for project names and is included in my base.html template. The other one is an advanced search function which allows to search for specific criterias e.g. department, project name, status, etc. all works fine as long as there is no pagination. the normal search function works with pagination but the advanced doesn't. The problem seems the return of the query, which returns one list for mutliple queries starting with q=['','','']. Because my form fields in my advanced search have different names e.g. qD,qS, etc. the parts of the list can't be properly assigned. url return when doing advanced search before changing page: http://127.0.0.1:8000/advanced_search/?csrfmiddlewaretoken=rzIvrOJdUMHwwxaSR18hy48mPTNCORXjaMYigqELXKRlKzNhBpEjbVSueQGHs7yl&qD=corporate&qC=&qN=&qT=&qS=&qA=&qCD= url return when doing advanced search after changing page: http://127.0.0.1:8000/advanced_search/?page=2&q=(None,%20%27corporate%27,%20%27%27,%20%27%27,%20%27%27,%20%27%27,%20%27%27,%20%27%27) here my django and html code: views.py # normal search def search(request): template = 'MAR_Projects/projects.html' query = request.GET.get('q') if query: filtered_projects = table_projects.objects.filter(Q(Project_Code__icontains=query) | Q(Project_Name__icontains=query)) else: filtered_projects = table_projects.objects.all().order_by('-Project_Creation') searchResultCount = filtered_projects.count pages = pagination(request, filtered_projects) context = {'items': pages[0], 'page_range': pages[1], 'query': query, 'searchResultCount':searchResultCount } return render(request, template, context) #advanced search def advanced_search(request): template = … -
The complaints on the view complaints page are not showing up
I am creating a complaint management system where users can enter their complaints as well as view and edit them and also view other users complaints. On the page where the users can view others complaint, no complaints or data is showing up. What do I do? This should be showing up : But this is what is showing up: My models.py: class Profile(models.Model): user = models.OneToOneField(User,null= True , blank = True, on_delete= models.CASCADE) profile_pic = models.ImageField(default = "msi.jpg", null = True, blank= True, upload_to= 'static/profileimages') first = models.CharField(max_length=500, null=True) last = models.CharField(max_length=500, null=True) email = models.CharField(max_length=500, null=True) mobile_number = models.IntegerField(null=True) location = models.CharField(max_length= 500, null= True) postal = models.IntegerField(null=True) def __str__(self): return self.first class Complaint(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) id = models.AutoField(blank=False, primary_key=True) reportnumber = models.CharField(max_length=500 ,null = True, blank= False) eventdate = models.DateField(null=True, blank=False) event_type = models.CharField(max_length=300, null=True, blank=True) device_problem = models.CharField(max_length=300, null=True, blank=True) manufacturer = models.CharField(max_length=300, null=True, blank=True) product_code = models.CharField(max_length=300, null=True, blank=True) brand_name = models.CharField(max_length = 300, null=True, blank=True) exemption = models.CharField(max_length=300, null=True, blank=True) patient_problem = models.CharField(max_length=500, null=True, blank=True) event_text = models.TextField(null=True, blank= True) document = models.FileField(upload_to='static/documents', blank=True, null=True) def __str__(self): return self.reportnumber views.py: class OtherPeoplesComplaints(TemplateView): model = Complaint form_class = … -
Django makemigrations show no changes detected after table rename in mysql
I have a Django application with a My-SQL database. recently I alter the table_name with the help of MySQL query in the MySQL-shell, after this when I run makemigration and migrate command terminal says "No changes detected". how can i reolve this issue and create again this table with help of django makemigration and migrate. -
how to change booleanfield to use bootstrap switch toggle
I want to change booleanfield model to use bootstrap switch toggle. # model blank_on_off = models.BooleanField(default=False) If i click on the button like above, then blank_on_off which is false changes to true and if i click one more time then changes again false. I think I should use JavaScript, how should I approach it? Thanks. -
DateTime picker in pure Django
I need to have a picker for DateTimeField, but I dont really know how to do it. Ive tried admin widget but I think I did it wrong. The closest thing to a solution was: models.py class MyModel(models.Model): myfield = models.DateTimeField() forms.py class MyModelForm(forms.ModelForm): class Meta: widgets = {'myfield': forms.widgets.SplitDateTimeWidget( date_attrs={'type': 'date'}. time_attrs={'type': 'time'})} It shows me a working picker, but when I try to press save button it says me an error: AttributeError: 'list' object has no attribute 'strip' -
Why serialization in djano rest framework is costly in terms of performance?
class SalesDataSummaryViewSet(viewsets.ReadOnlyModelViewSet): queryset=SalesDataSummary.objects.all() serializer_class=SalesDataSummarySerializer response = writeSerializedDataToCSV(response, headers, fieldnames,serializer_class.data) I am trying to convert response into csv and it takes around 5 minutes for 25k records, Where as the below code takes around 15-18 seconds, Here I am manually looping and creating a json. class SalesDataSummaryViewSet(viewsets.ReadOnlyModelViewSet): queryset=SalesDataSummary.objects.all() queryset_list=[] for data in queryset: queryset_dict={} queryset_dict['number']=data.number queryset_dict['name']=data.name queryset_dict['time']=data.time queryset_dict['code']=data.code queryset_dict['uuid']=data.uuid queryset_list.append(queryset_dict) response = writeSerializedDataToCSV(response, headers, fieldnames,queryset_list) -
Combine the huge amount of model in Django Rest
I have 2 models and an abstract class of model. models.py class TimeStampedModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_at = models.DateTimeField( verbose_name='Created At', auto_now_add=True ) is_deleted = models.BooleanField(default=False) modified = models.DateTimeField(auto_now=True) deleted = models.DateTimeField(null=True, blank=True) objects = NoDeleteManager() objects_with_deleted = models.Manager() class Meta: abstract = True ordering = ['created_at'] class ScentData(TimeStampedModel): name = models.CharField( max_length=64, blank=False, null=False, # unique=True, default='' ) class RawData(TimeStampedModel): scent = models.ForeignKey( 'ScentData', on_delete=models.CASCADE, related_name='rawdata_scent' ) # sensorvalue store as dicttionary # Example: {"s1":1, "s2":2, "s3":3} sensorvalue = JSONField() But now I want to combine the sensorvalue that has the same scent of RawData and delete the RawData that already combined. """ Example: after combine the value of sensorvalue will be store as list [{"s1":1, "s2":2, "s3":3}, {"s1":1, "s2":2, "s3":3}, {"s1":1, "s2":2, "s3":3}, ...] """ sensorvalue = JSONField() I have written the ViewSet to combine the RawData. Because I have 10M of rows, so my server can not handle the big times to execute. views.py class ScentDataViewSet(viewsets.ModelViewSet): queryset = ScentData.objects.all() @action(detail=False, methods=['GET'], url_path="combine_rawdata") def combine_rawdata(self, request, pk=None, **kwargs): scent_data = ScentData.objects.all() list_rawdata = list() for scent in scent_data: # call rawdata that has same scent using related_name all_rawdata = scent.rawdata_scent.all() # put all sensorvalue in list … -
Django getting related objects maintaining parent's order in a queryset
I have the following structure in a django application class Course(models.Model): name = models.CharField(_("Course Name"), max_length=50) class Module(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) name = models.CharField(_("Module Name"), max_length=50) number = models.IntegerField(_("Module Number")) class Chapter(models.Model): module = models.ForeignKey(Module, on_delete=models.CASCADE) name = models.CharField(_("Chapter Name"), max_length=50) number = models.IntegerField(_("Chapter Number")) I wanted to fetch all Chapters that is contained in a course, with the order of the module (based on module number) and the order of chapter ( based on chapter number ) for example the hierarchy can be like this Course 1 has Module 1 -- Chapter number=1 (1.1) -- Chapter number=2 (1.2) -- Chapter number=3 (1.3) Module 2 -- Chapter number=1 (2.1) -- Chapter number=2 (2.2) -- Chapter number=3 (2.3) Course 2 has, Module 1 -- Chapter 1 -- Chapter 2 -- Chapter 3 Module 2 -- Chapter 1 -- Chapter 2 -- Chapter 3 I would like to fetch All chapters in Course 1 such in the order [ (1.1), (1.2), (1.3), (2.1), (2.2), (2.3) ] and so on... When i fetch all chapters with the query Chapter.objects.filter(module__in=Course1.module_set.all()) I'm getting the chapters ordered by [ (1.1), (2.1), (1.2), (2.2), (3.1), (3.2) ]... As the chapter number is 1 2 3 etc... … -
Filtering Characters in HTML - Python - Django
So I am building a website and needed to be able to filter by a prefix on a model field I have in Django on my website. Now when I display this I need the prefix to be gone. The simplest way to do this seems to be in the HTML itself with something that says to not include the first 4 characters or before such as [4:]. This seems simple but I can't get it to work and I can get this to work |truncatechars:"10" which was a recommended solution. I need something in either my views or in my HTML that says when you print don't display the first 4 characters but display everything beyond that. Thanks for any help! HTML: {{ form.title }} Models: class DocPost(models.Model): user = models.ForeignKey(User, default=True, related_name="Doc", on_delete=models.PROTECT) title = models.CharField(max_length=100) content = HTMLField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-pk'] def __str__(self): return self.title def get_absolute_url(self): return reverse('doc-post-list') Django Views: def docpostnewview(request, pk): obj = get_object_or_404(DocPost, id=pk) form = DocPostForm(request.POST or None, instance=obj) if form.is_valid(): form.save() return HttpResponseRedirect("/" + id) context = {"form":form} #context['title'] = DocPost.objects.all().filter(title='title') return render(request, "my_app/use_template.html", context) -
Can a custom manage.py command know the server domain?
I'm writing a custom manage.py command, and I need the base URL of the site. Is it possible to dynamically determine it, or do I have to hardcode it somewhere? I tried using django.contrib.sites.shortcuts.get_current_site, but it needs a request. I found this example to "get site without request": from django.contrib.sites.models import Site current_site = Site.objects.get_current() but I get this error: RuntimeError: Model class django.contrib.sites.models.Site doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS I'm not sure what I should put in INSTALLED_APPS to make this work. Should I do something completely different? Or it this not even possible? -
How to set db model fields to just read-only even a superuser should be able to edit it
I tried this way like we do with primary keys But it's not working they as I want. I want Some fields to not editable from Django Admin We can manage it with permissions but I want it for all even superuser shouldn't be able to change values I tried this way #models.py class Payments(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, verbose_name="Payment Made By",) paymentForOrderID = models.CharField(max_length=200, null=True, blank=True,editable=False, verbose_name="Payment For Order ID") paymentMethodUsed = models.CharField(max_length=200, null=True, blank=True, verbose_name="Method Used") aproxTimeAndDateOfPayment = models.CharField(max_length=200, null=True, blank=True,editable=False, verbose_name="Approx Date/Time Of Payment") totalAmountPaid = models.CharField(max_length=200, null=True, blank=True,editable=False, verbose_name="Amount Paid") paymentDetails = models.TextField(null=True, blank=True,editable=False,verbose_name="Details") createdAt = models.DateTimeField(auto_now_add=True) _id = models.AutoField(primary_key=True,editable=False, verbose_name="Entry ID") def __str__(self): return str(self.createdAt) Doing this when I open it it only shows editable fields but not the others. -
Retrieving None as an entry_set django
profile class SeekerProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) current_salary = models.IntegerField() currency = models.CharField(max_length=25) photo = models.ImageField(upload_to='applicants') resume = models.FileField(upload_to='applicants/documents') def __str__(self): return self.user.first_name Skillset model class Seekerskillset(models.Model): skill_set = models.ForeignKey(Skillset, on_delete=models.CASCADE) seeker = models.ForeignKey(SeekerProfile, on_delete=models.CASCADE) skill_level = models.CharField(max_length=25) class Meta: verbose_name = 'Seeker skill set' But when i am trying to get the entry set i am receiving None even though i am clearly having entries for amir >> from seekerbuilder.models import SeekerProfile >>> obj = SeekerProfile.objects.get(id=1) >>> print(obj) amir >>> print(obj.seekerskillset_set) seekerbuilder.Seekerskillset.None >>> for val in obj.seekerskillset_set: ... print(val) ... Traceback (most recent call last): File "<console>", line 1, in <module> TypeError: 'RelatedManager' object is not iterable >>> -
What is the correct settings for static files in django
I just started using django and I got confused over the static files. As per this post correct static files setting I understand that STATIC_URL is just like the name. STATICFILES_DIRS is the place where django will look for static files and STATIC_ROOT where the static files will be collected to. For my project I had the following file sys rest |__ rest |__ settings.py pages static |__admin |__images |__vendor |__bootstrap templates manage.py I decided to go for a project based approach when having my folders instead of a per app one. Some stuff was not working with the website landing page I had and I saw that I needed to collectstatic and so I did but I set the path to my already existing static file which did not let me at first but somehow ended up working. Out of nowhere my static folder had admin on it which I assume is from the admin app that comes with django, and my project finally started to work properly which is the confusing part. I decided to follow the post and included in my settings the following STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/') … -
URL loading the wrong view - Django
Really struggling with this one. For some reason I can't get my URL to load the correct view. The site loads the home page correctly but then when I add on the extesion to acess another one of my apps, it just reloads the home page. It doesnt throw any errors or anything, it just wond direct to the correct page. This is my base URL file: path('admin/', admin.site.urls), path('', blog_views.home), path('<username>/', include('blog.urls')), path('community/', include('community.urls')), Start of the Blog URL file: path('', LogListView.as_view(), name='log'), This is the Blog views file: @login_required def home(request): user_name = request.user.username return HttpResponseRedirect(f'{user_name}/') class LogListView(LoginRequiredMixin, ListView): model = Post template_name = 'blog/log-main.html' login_url = 'login/' context_object_name = 'posts' ordering = ['-date_added'] def get_context_data(self, **kwargs): context = super(LogListView, self).get_context_data(**kwargs) context['posts'] = Post.objects.filter(user = self.request.user) return context The home function above sutomatically directs each user to thier specific home page by placing thier username at the start of the URL path. Then here is my Community app URL file: path('', CommunityListView.as_view(), name='community'), And the Community view file: class CommunityListView(LoginRequiredMixin, ListView): model = Post template_name = 'community/community.html' context_object_name = 'postss' ordering = ['-date_added'] def get_queryset(self): qs = super().get_queryset() active_user = self.request.user active_user_following = active_user.following.values_list('user_id', flat=True) following_user_objects = [] … -
Not allowed to load local resource error when trying to add custom CSS stylesheet to HTML document
I am writing a project with Django, Bootstrap, HTML and CSS. The code I found provided a bootstrap stylesheet. When I run the program on developer server 127.0.0.1:8000 the bootstrap styles are applied. I am trying to add a stylesheet to my HTML file with custom styles. I am receiving a "Not allowed to load local resource: file:///C:/Users/Keith/OneDrive/DjangoProjects/django_forms/myapp/templates/formstyles.css" in the Chrome console when I try to run the project. form.html \\ {% load crispy_forms_tags %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"> <!-- <link rel="stylesheet" href="C:/Users/Keith/OneDrive/DjangoProjects/bootstrap-5.0.2-dist/bootstrap-5.0.2-dist/css/bootstrap.min.css"> --> <link rel="stylesheet" type="text/css" href="C:\Users\Keith\OneDrive\DjangoProjects\django_forms\myapp\templates\formstyles.css"> </head> <body style="padding: 20px;"> {% crispy form form.helper %} </body> </html> \\ Custom CSS style sheet formstyles.css \\ input { `color: #683aa4 !important; `margin-top: 100px !important; `} \\ the HTML file and CSS file are in the same directory thank you, -
python script load file via post on django
I'm testing this script to load a document to a webpage in django The GET and POST request return 200 but the file is not loaded. If the answers are 200 why don't load the file I'm doing wrong? code: import requests url='http://localhost:8000/' files = {"docfile": open('test.txt', "rb")} s = requests.Session() resp1 = s.get(url) print(resp1.text) csrf_token = resp1.cookies['csrftoken'] resp2 = s.post(url, data={'csrfmiddlewaretoken': csrf_token,"file":files}) print(resp2.text) resp POST: This is the message from the POST request. <ul class="errorlist"><li>This field is required.</li></ul> -
Can't change font-family in main.css
Currently using Django with bootstrap 4. For whatever reason, I cannot get the font-family to change through my main.css file. I can change other attributes, but font does not seem to work. If I change the font-family in my other files, it works. I just cannot change it through my main.css. What am I doing wrong? base.html {% load static %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'css/main.css' %}"> ... main.css body { font-family: "Times New Roman", Georgia, serif !important; } -
Django: Find which object a BaseManager or QuerySet comes from
I'm passing BaseManager and QuerySet to a function to perform exclude statements. Can I find out which class the BaseManager comes from? This is to properly give keyword arguments to exclude. The current method only works when called on something from Fragment. class Sampler: @staticmethod def exclude_one(query: BaseManager, element: Union[Fragment, Model]): if isinstance(element, Fragment): return query.exclude(kind=element.kind, number=element.number) elif isinstance(element, Model): return query.exclude(model__name=element.name) Here is models.py. class Fragment(models.Model): kind = models.CharField(max_length=50) number = models.IntegerField(blank=True, null=True) model = models.ForeignKey('Model', models.DO_NOTHING, db_column='model', blank=True, null=True) unique_id = models.AutoField(primary_key=True, blank=True, null=False, default=0) def __str__(self): return f"{self.model}_{self.kind}{self.number}" class Model(models.Model): name = models.CharField(primary_key=True, blank=True, null=False, max_length=50) classes = models.IntegerField(blank=True, null=True) relations = models.IntegerField(blank=True, null=True) def __str__(self): return self.name -
deploy django + channels to heroku
I'm using python 3.9.1 , django 3.2.5 , redis 5.0.7 and channels 3.0.4 this is my first time using channels so forgive me if this was an easy question for you I'm building a chat app so my app is running locally with no problems at all (windows 10 and wsl 2 with ubuntu 20.04 ) trying to upload to heroku gives me app crached for multiple different reasons after each doc I read and tutorial I tried to follow this is my procfile release: python3 manage.py migrate web: daphne online_chat.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: python3 manage.py runworker channel_layer --settings=online_chat.settings -v2 asgi.py import os import django from channels.routing import ProtocolTypeRouter, URLRouter, get_default_application from channels.auth import AuthMiddlewareStack from django.core.asgi import get_asgi_application from main.routing import websocket_urlpatterns from .wsgi import * os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'online_chat.settings') django.setup() django_asgi_app = get_asgi_application() application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": AuthMiddlewareStack( URLRouter(websocket_urlpatterns) ) }) also tried different mixes between # application = get_default_application() django_asgi_app = get_asgi_application() # ASGI_APPLICATION = get_asgi_application() setting.py WSGI_APPLICATION = 'online_chat.wsgi.application' ASGI_APPLICATION = 'online_chat.asgi.application' REDIS_URL = os.environ.get('REDIS_URL', ('127.0.0.1', 6379)) CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [REDIS_URL], } }, } also tried to use asgi_redis but this caused more problems as it … -
TypeError: orderTimelocation() got an unexpected keyword argument 'order'
I have the models order and orderTimelocation. Order has a one to many relationship with orderTimelocation: class Order(models.Model): customer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='customer') retailer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='retailer') date_publish = models.DateField() date_available = models.DateField() weight = models.DecimalField(decimal_places=2, max_digits=5) class orderTimelocation(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='ordertimelocation'), longitude = models.DecimalField(decimal_places=8, max_digits=12) latitude = models.DecimalField(decimal_places=8, max_digits=12) And trying to serialize the order model, that should receive ordertimelocation's. For that I'm using Writable nested serializers, as described on DRF documentation class OrderSerializer(serializers.ModelSerializer): ordertimelocation = orderTimelocationSerializer(many=True) class Meta: model = Order fields = ['customer', 'retailer', 'date_publish', 'date_available', 'weight', 'ordertimelocation'] def create(self, validated_data): timelocations_data = validated_data.pop('ordertimelocation') order = Order.objects.create(**validated_data) for timelocation_data in timelocations_data: orderTimelocation.objects.create(order=order, **timelocation_data) return order I think my code is similar to the one on the documentation but the following erro happens: Traceback (most recent call last): File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/rest_framework/views.py", line 506, … -
Is there a faster way to use django-taggit?
I am attempting to use django-taggit to tag client images. I didn't notice the problem at first, but things have started to slow way down, now that there are more images to load. Is there a better way to handle this so that it isn't making as many calls to the db? TIA manage_images.html {% for tag in image.tags.all|dictsort:"name" %} <label class="label label-purple" style="font-size: 14px;">{{ tag }}</label> {% endfor %} models.py class Image(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE, null=True) image = models.ImageField(null=True, blank=True, upload_to=get_image_upload_path) thumbnail = models.ImageField(null=True, blank=True, upload_to=get_thumbnail_upload_path) filename = models.CharField(max_length=100, null=True, blank=True) width = models.IntegerField(null=True, blank=True) height = models.IntegerField(null=True, blank=True) size = models.IntegerField(null=True, blank=True) active = models.BooleanField(default=0) tags = TaggableManager() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now_add=False, auto_now=True) -
Django Translate Templates String Filter
I have read the documentation and a created a tag <div>{{ site_name|default:_("It works!") }}</div>. In order to translate the "It works!" string, I just configured the django.po file as shown bellow and the translation was successful: msgid "It works!" msgstr "Funciona!" However, trying to translate the "No" string in the index.html, I configured the django.po file as shown bellow and I got no translation: msgid "No" msgstr "Sem" Would anyone point me if I missing any configuration for translating the "No" string in the index.html file. -
Trying to Deploy Django App Through Elastic Beanstalk, Module not found error
I'm trying to deploy a Django application AWS Elastic Beanstalk. I followed this guide: https://medium.com/@justaboutcloud/how-to-deploy-a-django3-application-on-elastic-beanstalk-python3-7-and-amazon-linux-2-bd9b8447b55 but when I attempt to deploy I have a 502 error when I go to the site page, and when I look through the logs the error I have is ModuleNotFoundError: No module named 'django3.wsgi' My code is stored like this: django3 |--- manage.py |--- requirements.txt |--- .ebextensions |--- 01_python.config |--- django3 |--- __init__.py |--- asgi.py |--- settings.py |--- urls.py |--- wsgi.py And my 01_python.config file has: option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "django3.settings" "PYTHONPATH": "/var/app/current:$PYTHONPATH" "aws:elasticbeanstalk:container:python": WSGIPath: django3.wsgi:application NumProcesses: 3 NumThreads: 20 My requirements.txt file is asgiref==3.4.1 Django==3.2.5 gunicorn==20.1.0 pytz==2021.1 sqlparse==0.4.1 I'm not sure what I have that is wrong, if someone could help me out that would be great. I've tried messing around with the formatting of the 01_python.config file but nothing is helping fix the issue.