Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django nested html Forms
I have a template to create/modify a model, the way I do it is with one model form and three modelformset_factory, this is necessary because the original model has 3 many to many thorugh relationships. I have achivied the task previously mention, my problem is that I use a java script code that add formset dynamically by the user (still missing the dynamically remove). The javascript code only works by adding a new html form, and thats the main reason why i need to nest html forms, I know that it can't be achieved via html. So, what I'm asking is, if there is a work around? The next code gives an formset Validation Error: missing management form, I can fix it by combining all the forms into one, but I need the multiple forms to add dynamically the formsets my template: <body> <form class="main-form" method="POST" action="" id="main-form"> {% csrf_token %} {{dtCrearMbl.management_form}} <div class="main-form"> <table> {{dtCrearMbl.as_table}} </table> </div> <form id="form-container-panel" method="POST" > {% csrf_token %} {{dtCrearPnl.management_form}} {% for lpFormset in dtCrearPnl %} <div class="panel-form" form="main-form"> {{lpFormset.as_p}} </div> {% endfor %} <button id="add-form-panel" type="button">Add Another Panel</button> </form> <form id="form-container-panel" method="POST"> {% csrf_token %} {{dtCrearComp.management_form}} {% for lpFormset in dtCrearComp %} <div … -
Django find all model objects with more than x related foreign objects
So say I have two Django model objects with a one-to-many relationship like: class A(models.Model): id = models.AutoField(primary_key=True) attribute = models.CharField(max_length=30) related = models.ForeignKey(B, on_delete=models.CASCADE) class B(models.Model): id = models.AutoField(primary_key=True) username = models.CharField(max_length=30) year_created = models.IntegerField() and I need to find all the instances of B that were created after year x that have more than 3 instances of A How would I structure this filter? Something like: dealership.objects.filter(year_created__gte=1999) but only include objects with more than x related A's -
how to configure wsgi file properly with gunicorn
i can't recognise in whole scale what i am doing wrong nginx is working and bad gateway is not shown its been 30 day i am trying to fix main_website - is folder with django_project and manage.py static media django_project - is with settings.py and wsgi.py another_user-i make another user with password to upload by git and www/html/main_website/ user is another_user but i give group www-data thanks so much gunicorn.service /etc/systemd/system [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] Type=notify User=www-data Group=www-data WorkingDirectory=/var/www/html/main_website/ ExecStart=/home/another_user/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ django_project.wsgi:application [Install] WantedBy=multi-user.target gunicorn.socket /etc/systemd/system [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target nginx.conf user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; gzip on; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } default config /sites-available server { listen 80; listen [::]:80 default_server; server_name example.com; (i change here only example.com) charset utf-8; # max upload size client_max_body_size 75M; # Django media location /media { alias /var/www/html/main_website/media; } location /static { alias /var/www/html/main_website/home; } … -
Why does the images in Django are not rendering?
I'm trying to build a Stripe checkout, but the images on the preview are not rendering correctly. The images aren't appearing. settings.py: MEDIA_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/images/' urls.py: urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) payments.html: <div class="header"> <h1>Order Summary</h1> </div> {% for order in items %} <div id="order-items"><div class="line-item"> <img class="image" src="{{ order.image.url }}" alt="Stripe Pins"> <div class="label"> <p class="product">{{ order.item.title }}</p> <p class="sku">Collector Set</p> </div> {% if order.item.discount_price %} <p class="count">{{ order.quantity }} x {{ order.item.discount_price }}€</p> {% else %} <p class="count">{{ order.quantity }} x {{ order.item.price }}€</p> {% endif %} {% if order.item.discount_price %} <p class="price">{{ order.get_total_discount_item_price }}€</p></div> {% else %} <p class="price">{{ order.get_total_item_price }}€</p></div> {% endif %} {% endfor %} -
Update SerializerMethodField in Django REST Framework
I have a serializer+models like this: class Dates(models.Model): date: date = models.DateField(verbose_name='Datum') indicator: str = models.CharField(max_length=1, null=True, default=None, blank=True, verbose_name='Indikator') entry: Entry = models.ForeignKey(Entry, on_delete=models.PROTECT, related_name='dates') class Entry(models.Model): pass class EntrySerializer(serializers.ModelSerializer): bookings = SerializerMethodField() # implicitly `get_dates` class Meta: model = Entry fields = ( 'id', 'dates', ) read_only_fields = ('id',) def get_dates(self, instance): try: start = self.context.request.query_params.get('start') start = datetime.strptime(start, '%Y%m%d') except: start = None d = { date.strftime('%Y%m%d'): indicator for (date, indicator) in instance.dates.all().values_list("date", "indicator") } dates = start.date_range(start) # just returns a list of dates for date in dates: d.setdefault(date.strftime('%Y%m%d'), '') return d I am using SerializerMethodField to create empty "padding" dates, should an Entry not have a Date object assigned for a certain date within the given date range. The output JSON looks like this: [ { "id": 1, "bookings": { "20210203": "D", "20210204": "D", "20210205": "2", "20210201": "", "20210202": "", "20210206": "", "20210207": "", "20210208": "", "20210209": "", "20210210": "", "20210211": "", "20210212": "", "20210213": "", "20210214": "", "20210215": "", "20210216": "", "20210217": "", "20210218": "", "20210219": "", "20210220": "", "20210221": "", "20210222": "", "20210223": "", "20210224": "", "20210225": "", "20210226": "", "20210227": "", "20210228": "" }, }, ...] I am trying to now actually … -
Web Data Sync between multiple devices(PC, Laptop, Mobile, Tablet) for a same user using multiple browsers
I am looking for a working approach to sync data between different sessions that the user might use - (With different sessions or with multiple devices). Step 1. User1 logins to webapp from a PC1, Browser1 and starts to edit a form/file(F1). Step 2. User1 Logins to the same webapp from PC2, Browser2 and starts to edit a file(F1). Step 3. User1 goes back to edit the form from PC1. Step 4. User1 moves to PC2 to edit the form. For any of the step above, the user needs to always access the updated form. FrontEnd - React JS backend Node/Django Thanks, Garima -
How to automatically set a foreignkey that cannot be edit for users django
I would like an advice. I am creating a django application where users can register comments, what I want to do is that when a user registers a comment, the user is automatically registered as its author because it does not make sense that a user can register a comment in the name of another user, In order to do this, I have defined my model and views like this models.py from django.contrib.auth.models import User from django.forms import ModelForm, widgets class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) description = models.CharField(max_length=30) class my_form(ModelForm): class Meta: model = Comment fields = '__all__' widgets = {'author': widgets.Select(attrs={'disabled': True}),} views.py from django.shortcuts import HttpResponse from .models import Comment, my_form def my_view(request): user = User.objects.get(username=request.user) if request.method == 'POST': form = my_form(request.POST, request.FILES) request.POST._mutable = True form.data['author'] = user # As the form field is disabled the view has to complete it if form.is_valid(): form.save() return HttpResponee("Success") else: return HttpResponse("Fail") else: form = my_form(initial={'author':user}) return render(request, "my_app/my_template.html", {"form":form}) my_template.html <div class="container"> <section> <form enctype="multipart/form-data" action="/new_comment/" method="POST">{% csrf_token %} <div class="form-row"> <div class=" form-group col-md-4"> {{form.author|as_crispy_field}} </div> <div class=" form-group col-md-4"> {{form.description|as_crispy_field}} </div> </div> <br> <button type="submit" class="btn btn-outline-dark">Submit</button> </form> <br> </section> </div> So as the form´s … -
When i want to add a product to my cart i have a keyerror
When i click add to cart i have the following error in views.py: "In updateItem, productId = data['productId'] KeyError: 'productId' " views.py line 70 where i have my error: def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('Action:', action) print('productId:', productId) customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(order = order, product = product) if action == 'add': orderItem.quantity = (orderItem.quantity +1) elif action == 'remove': orderItem.quantity = (orderItem.quantity -1) orderItem.save() if orderItem.quantity <=0: orderItem.delete() return JsonResponse('El item fue agregado', safe=False) carrito.js: function updateUserOrder(productId, action){ console.log('Usuario logeado y enviando data...') var url = '/update_item/' fetch (url, { method: 'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken': csrftoken, }, body:JSON.stringify({'productId': productId, 'action':action}) }) .then((response) =>{ return response.json() }) .then((data) =>{ console.log('data:', data) location.reload() }) } My template carrito.html: When i click on the button Add to cart i have the issue. {% extends 'tienda/index.html' %} {% load static %} {% block content %} </div> {% for item in items %} <div class="cart-row"> <div style="flex:2"><img class="row-image" src="{{item.product.imageURL}}"></div> <div style="flex:2"><p>{{item.product.name}}</p></div> <div style="flex:1"><p>{{item.product.price|floatformat:2}}</p></div> <div style="flex:1"> <p class="quantity">{{item.quantity}}</p> <div class="quantity"> <img data-product={{item.product.id}} data-action="add" class="chg-quantity update-cart" src="{% static 'images/arrow-up.png' %}"> <img data-product={{item.product.id}} data-action="remove" class="chg-quantity update-cart" src="{% static 'images/arrow-down.png' %}"> </div> … -
Django queryset join two or more models that use the same foreign key or have nested relationships
I want to get an aggregated data related to each Tree entry. from django.db import models class Tree(models.Model): tree_name = models.CharField(max_length=100, unique=True) class Branch(models.Model): tree = models.ForeignKey(Tree, on_delete=models.CASCADE) branch_type = models.ForeignKey(BranchType, on_delete=models.CASCADE) branch_health = models.ForeignKey(AppConfig, on_delete=models.CASCADE) last_checked = models.DateTimeField(null=False) class BranchType(models.Model): type_name = models.CharField(max_length=30, unique=True) class Stump(models.Model): tree = models.OneToOneField(Tree, on_delete=models.CASCADE) stump_info = models.ForeignKey(StumpInfo, on_delete=models.CASCADE) class StumpInfo(models.Model): scientific_term = models.CharField(max_length=100, unique=True) class AppConfig(models.Model): key = models.CharField(max_length=100, unique=True) value = models.CharField(max_length=100) The output I am looking for is something like this: [ { "tree": "ucxdfg", "branch": {// The tree can have a lot of branches, but I only target branches from past 24 hours. "branch_type_1": "average",// The health is coming from app_config ["good","average", "poor"] "branch_type_2": "good" }, "stump_info": { "scientific_term": "xyz" } }, { "tree": "awerdf", "branch": { "branch_type_1": "good" }, "stump_info": { "scientific_term": "xyz" } }, { "tree": "powejf", "branch": { "branch_type_2": "poor" }, "stump_info": { "scientific_term": "abc" } }, ... ] I am not sure how I would design the queryset to do this. -
Dynamic Queryset Based on Special Model Django
I would like to have a page that contains product and related competitor products with it. I tried, but all the times competitor products stay same. Would you please help me? models: class Product(models.Model): created_by = models.ForeignKey(User, on_delete=models.CASCADE) category = models.CharField(max_length=120) brand = models.CharField(max_length=120) product = models.CharField(max_length=120) price = models.DecimalField(decimal_places=2,max_digits=100) class Comp_Product(models.Model): product = models.ForeignKey(Product,on_delete=models.CASCADE) competitor = models.URLField() price = models.DecimalField(decimal_places=2,max_digits=100) change = models.FloatField() stock = models.BooleanField() last_update = models.DateField(auto_now_add=True) views: class ProductListView (ListView): model = Comp_Product context_object_name = 'comp_products' template_name = 'products.html' class ProductDetailView (LoginRequiredMixin,DetailView): model = Product template_name = 'product.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comp_products'] = Comp_Product.objects.all() return context urls.py: path('product/<int:pk>/', ProductDetailView.as_view(),name='product_detail'), path('comp_products/', ProductListView.as_view(),name='comp_products'), -
Django rest-framwork [views]: users can update only modules they created
So I have a view for my Django app that is used to update/delete user profiles. I'm wondering is there a better way to check if the person who's requesting the change is the same one that's in the url. request url looks like this /profile/<str:username> class UserDetail(RetrieveUpdateDestroyAPIView): queryset = User.objects.all() serializer_class = UserSerializerFull permission_classes = [IsAuthenticated] lookup_field = "username" def put(self, request, *args, **kwargs): if str(request.user) == kwargs.get("username"): return super().put(request, *args, **kwargs) return Response( data={"msg": "unauthorized request"}, status=status.HTTP_403_FORBIDDEN ) def patch(self, request, *args, **kwargs): if str(request.user) == kwargs.get("username"): return super().patch(request, *args, **kwargs) return Response( data={"msg": "unauthorized request"}, status=status.HTTP_403_FORBIDDEN ) def delete(self, request, *args, **kwargs): if str(request.user) == kwargs.get("username"): return super().delete(request, *args, **kwargs) return Response( data={"msg": "unauthorized request"}, status=status.HTTP_403_FORBIDDEN ) As all of the methods are repeating the same code is there a way to write something just for once and use it everywhere. Also for other models that are made by the User profile i have the same issue as a lot of the code is repeating itself. -
How to use Django iterator in this case
I want to show 20 reviews per page on my website. Unfortunately whole reviews count is about 260,000, It takes 3~4sec to show at page 10,000~ I used to use queryset like this: reviews = Review.objects.all()[(page_num-1)*20:20*page_num] . . . obj['reviews'] = reviews Now I think using iterator(chunk_size=) is better than upper one for efficiency. But I dont know how to use iterator() properly. I definitely need your helps Please let me know... -
store.models.CartQuantity.DoesNotExist: CartQuantity matching query does not exist
Hi I'm trying to get the newest/latest number in a query set: I use this codeline for that: CartQuantity.objects.filter(customer=customer).values_list('cquantity', flat=True).get(pk=-1) This is how the queryset looks like: <bound method QuerySet.last of <QuerySet [4, 4, 4, 2, 4, 4, 5, 6, 5, 14, 10, 12]>> # need last number(12) I tried the code above but I get an Error message: store.models.CartQuantity.DoesNotExist: CartQuantity matching query does not exist. This is my models: class CartQuantity(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) cquantity = models.IntegerField(default=0, null=True, blank=True) Does anyone know how to fix the error or another way of getting the newest number(in this case number 12 in the query set)? -
AWS Elastic Beanstalk Python Django S3 Access Denied cannot upload / read file
I have deployed Python Django server on AWS Elastic Beanstalk. This is how my settings.py file looks like: # aws settings AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME') AWS_DEFAULT_ACL = None AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} # s3 static settings STATIC_URL = '/staticfiles/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # s3 public media settings PUBLIC_MEDIA_LOCATION = 'media' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/' DEFAULT_FILE_STORAGE = 'hello_django.storage_backends.PublicMediaStorage' # s3 private media settings PRIVATE_MEDIA_LOCATION = 'private' PRIVATE_FILE_STORAGE = 'hello_django.storage_backends.PrivateMediaStorage' In AWS I created IAM user with AmazonS3FullAccess permission, and I use his AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in settings. The problem is that when I try to read media file from the file link I always get "Access denied" error, even if I specify PublicMediaStorage and give all public access on S3 bucket. Also, when I upload file, the folder (e.g 'media') in bucket does not get created. Do you have idea what could the problem ? -
Django: How to get an object with a file name
Let's say I have a model with a FileField: class Foo(models.Model): file = models.FileField( upload_to='files' ) What would be the best approach for getting an object from the model with the name of the file? Something like: try: foo = Foo.objects.get( file__name='bar.csv', ) except Foo.MultipleObjectsReturned: return something() except Foo.DoesNotExist: return something_else() process(foo) I guess I could add a file_name field into the model, but that seems cumbersome..? -
Error while running server in django after connecting djangorestframework
This error happens after adding rest_framework (pip install djangorestframework) to project but i dont know the reason in this framework or not. Error log, i think, is not enough informative for me. If need to share any file just let me know. Note: I am new in django web api so any your advice would be valuable. Thank you in advance. Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'rest_framework' Traceback (most recent call last): File "manage.py", line 22, in … -
Am using drf-spectacular for my Django rest api documentation, how to override our own endpoint
In below code am not able to generate schema for 2 endpoints admin/ and payslip/ urlpatterns = [ # YOUR PATTERNS path('admin/', admin.site.urls),, path('payslip/',include('payslip.urls')) path('api/schema/', SpectacularAPIView.as_view(), name='schema'), # Optional UI: path('api/schema/swagger-ui/', SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'), path('api/schema/redoc/', SpectacularRedocView.as_view(url_name='schema'), name='redoc'), ] -
Django-filter, multiple fields search overriding other parameters! (django-filter)
I am having a spot of trouble making a search box that looks through both the title, and the description of the model, without it over riding everything. I took my example from this: Django-filter, how to make multiple fields search? (with django-filter!) so my current filter looks something like: class QuestionSetFilter(django_filters.FilterSet): search = CharFilter(method='my_custom_filter', label='search') o = OrderingFilter( fields = ( ('date_posted', 'date_posted') ), choices = [ ('date_posted', 'Old first'), ('-date_posted', 'New first'), ] ) class Meta: model = QuestionSet exclude = ['image', 'user', 'date_posted', 'question_set_description', 'question_set_title'] def my_custom_filter(self, queryset, name, value): return QuestionSet.objects.filter( Q(question_set_title__icontains=value) | Q(question_set_description__icontains=value) ) How can I change my custom filter to still chain with the other parameters I want to search with? -
Django urls "overlapping"
Ok. Hi guys. I googled this problem and didn't find anything that would help. Ok so this is my project structure: -myproject -controlpanel -urls.py -views.py -templates -controlpanel -index.html -include -navbar.html -main -urls.py -views.py -templates -main -index.html -partials -navbar.html -myproject -urls.py This is my controlpanel urls.py file: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('servers', views.servers, name='servers'), ] This is my main urls.py file: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('join', views.join, name='join'), path('rules', views.rules, name='rules'), path('services', views.services, name='services'), path('stats', views.stats, name='stats'), path('gdpr', views.gdpr, name='gdpr'), path('login', views.login, name='login'), ] This is myproject urls.py: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('', include('main.urls')), path('controlpanel/', include('controlpanel.urls')), path('admin/', admin.site.urls), ] Now when user doesn't specify any subdirectory he should be redirected to index.html in app main. The problem is that some {% url 'urlname' %} return urls from other projects. For instance when i used {% url 'index' %} in main apps navbar it used url controlpanel/index which it isn't supposed to do. This also happened to me when i was creating navbar for controlpanel and imported css but i solved it by renaming … -
How can i sort event by current user in Django calendar
I have a problem with sorting events in the Django calendar, namely, I would like to filter them not only by date but also by the user who created the event so that only his events are displayed on the calendar and not other users this is my utils.py file class Calendar(LocaleHTMLCalendar): def __init__(self, year=None, month=None): self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, events): events_per_day = events.filter(start_time__day=day) d = '' for event in events_per_day: d += f'<li> {event.get_html_url} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek, events): week = '' for d, weekday in theweek: week += self.formatday(d, events) print() return f'<tr> {week} </tr>' # formats a month as a table # filter events by year and month def formatmonth(self, withyear=True,): events = Event.objects.filter(start_time__year=self.year, start_time__month=self.month,) cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar">\n' cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n' cal += f'{self.formatweekheader()}\n' for week in self.monthdays2calendar(self.year, self.month): cal += f'{self.formatweek(week, events)}\n' return cal My problem is that I do not know how to apply filtering with the current user in the object … -
Django - How can I implement and ignore case-sensitivity within my model to make the fields unique by character only?
How can I implement a function or method for my username and email fields to ignore case-sensitivity. By current Django standard, both the name John and john are unique by default. I want the mentioned fields to be unique by characters only, ignoring any aspect of captial cases. Is there any simple way of doing this? I want to do this at the database level, so I don't have to constantly repeat hacky code whenever I want to implement. I found this thread: Case insensitive unique model fields in Django? The first answer, creating an SQL index option has me worried because indexes need to be maintained and an index is not always used for a query. Then there's another method that uses citext , the docs mention that this is only possible during first create table migration, that seems like the most simple option, but it requires the most maintaince if you already have a live db. The next option for ease would probably be this method referenced: class MyModelManager(models.Manager): def get_by_username(self, username): return self.get(username__iexact=username) class MyModel(models.Model): ... objects = MyModelManager() I would like to try and replicate that using my model: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), … -
Displaying fields not intended to be edited in ModelAdmin
I have a custom contact form for which I create a sent_time field using auto_now_add to save the time when the user had sent the message. I am able to list all the information on the listing view of the admin panel however when I try to enter a specific message I hit the following error: 'sent_time' cannot be specified for GeneralContact model form as it is a non-editable field My attempt to make the fields readonly in the ModelAdmin results in the same error class GeneralContactAdmin(ModelAdmin): """ Admin model for general correspondence via the main contact form on the information page """ model = GeneralContact list_display = GeneralContact.__all__ search_fields = GeneralContact.__all__ readonly_fields = GeneralContact.__all__ ordering = ('-sent_time',) list_filter = ('sent_time', 'has_response') Surely it is possible to be displayed only, perhaps I've done something incorrectly in my models? Here is the base model I use for the contact model class ContactFormBase(models.Model): __all__ = ( 'sent_time', 'sender_name', 'sender_email', 'sender_message', 'has_response', 'responded_on' ) sent_time = models.DateTimeField(auto_now_add=True) sender_name = models.CharField() sender_email = models.EmailField() sender_message = models.TextField() has_response = models.BooleanField( default=False, help_text='Select whether this message has been replied to by an admin.', ) responded_on = models.DateTimeField(blank=True, null=True) panels = [ FieldRowPanel([ FieldPanel('sender_name'), FieldPanel('sender_email'), ]), … -
Logging not working within WebSocketConsumer sub-classes
I have an issue where logging statements are not working in subclasses of WebsocketConsumer. Logger works in the entry point to the daphne application and even above the class declaration but not within the consumer. logger = logging.getLogger(name) logger.info("This log shows up") class TrackNotifyConsumer(WebsocketConsumer): """API Tracking Notifications Consumer""" def connect(self): logger.info("This log DOES NOT show up") async_to_sync(self.channel_layer.group_add)("track", self.channel_name) self.accept() Your OS and runtime environment, and browser if applicable Ubuntu 18.04.4 LTS A pip freeze output: freeze.txt This is deployed via Daphne, nginx -
Celery beat stuck on starting with Django and Redis
In my Django project I have two tasks in two different apps that I want to run periodically with Celery. The worker seems to collect the tasks and the beat seems to collect the schedular. However, the beat stuck on starting (it didn't synchronize the schedules) and never deliver the tasks to the worker. The celery --app=bozonaro worker --loglevel=debug --beat (bozonaro is my django project's name) command prompts the following to me: [2021-02-04 18:23:48,080: DEBUG/MainProcess] | Worker: Preparing bootsteps. [2021-02-04 18:23:48,103: DEBUG/MainProcess] | Worker: Building graph... [2021-02-04 18:23:48,104: DEBUG/MainProcess] | Worker: New boot order: {Timer, Hub, Pool, Autoscaler, StateDB, Beat, Consumer} [2021-02-04 18:23:48,257: DEBUG/MainProcess] | Consumer: Preparing bootsteps. [2021-02-04 18:23:48,257: DEBUG/MainProcess] | Consumer: Building graph... [2021-02-04 18:23:48,413: DEBUG/MainProcess] | Consumer: New boot order: {Connection, Events, Heart, Agent, Mingle, Gossip, Tasks, Control, event loop} -------------- celery@LAPTOP-E5L3SQ6N v5.0.5 (singularity) --- ***** ----- -- ******* ---- Linux-4.19.128-microsoft-standard-x86_64-with-glibc2.29 2021-02-04 18:23:48 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: bozonaro:0x7fc00b16d4c0 - ** ---------- .> transport: redis://localhost:6379// - ** ---------- .> results: redis://localhost:6379/ - *** --- * --- .> concurrency: 8 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- … -
Django DecimalField Formatting and Filtering Non-Responsive
The DecimalField output on my template is appearing like this; Total Cost: {'Cost__sum': Decimal('739.900000000000')} when it should appear like this Total Cost: 739.90. Despite my model only having 2 decimal places and trying the DecimalField filters the formatting does not change, it also includes my context variable 'Cost__Sum'. This has not happened in previous apps despite using the same code. Greatly appreciate if someone could point out what is going wrong here. Model.py class ComicInput(models.Model): Cost = models.DecimalField(max_digits=10, decimal_places=2, default='1.95') Value = models.DecimalField(max_digits=10, decimal_places=2, default='1.95') SoldAmt = models.DecimalField(max_digits=10, decimal_places=2, default='0.00') Views.py def home(self): """Renders the home page.""" #excludelist = ('Sold','Wish') if self.user.is_authenticated: DisplaySumCost=ComicInput.objects.all().filter( uid=self.user).aggregate(Sum('Cost')) DisplaySumValue=ComicInput.objects.all().filter( uid=self.user).aggregate(Sum('Value')) DisplaySumSoldAmt=ComicInput.objects.all().filter( uid=self.user).aggregate(Sum('SoldAmt')) assert isinstance(self, HttpRequest) return render( self, 'app/index.html', { 'title':'Kollector', 'year':datetime.now().year, 'DisplaySumValue': DisplaySumValue, 'DisplaySumCost': DisplaySumCost, 'DisplaySumSoldAmt': DisplaySumSoldAmt, } ) else: assert isinstance(self, HttpRequest) return render( self, 'app/index.html', { 'title':'Collector', 'year':datetime.now().year, } ) Template {% extends "app/layout.html" %} {% load humanize %} {% load l10n %} {% block content %} {% if request.user.is_authenticated %} <section style="border:1px solid black;background-color:lightyellow"> <h3 style="text-align:center"> Collection Summary for {{user.username}} </h3> <div class="row"> <div class="col-md-4"> <b>Total Cost: {{DisplaySumCost|localize}} </b> <b>Total Value: {{DisplaySumValue}} </b> <b>Total Sales: {{DisplaySumSoldAmt}} </b> </div> </div> </section> {% endif %} {% endblock %}