Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
improve django queryset performance
I have a set of products that I need to fetch from my API, along with their respective discounts. Initially, I used the subqueries approach to achieve this, but it has led to significant performance issues as the dataset has grown. I'm looking for suggestions on how to refactor the queryset to improve the performance. Any ideas or alternative methods to efficiently retrieve product discounts would be greatly appreciated. This is the QuerySet: active_vouchers = Voucher.dal.get_active_vouchers( voucher_kind=VoucherKindChoices.Static_based ).prefetch_related('voucher_ranges__packs__expense') is_discounted_subquery = active_vouchers.filter( voucher_ranges__packs__product__id=OuterRef('pk'), min_basket_value=0 ) voucher_type = is_discounted_subquery.filter(voucher_ranges__packs__product__id=OuterRef('pk')).\ values('voucher_type')[:1] voucher_kind = is_discounted_subquery.filter(voucher_ranges__packs__product__id=OuterRef('pk')).\ values('voucher_kind')[:1] voucher_fixed_amount = Voucher.bll.convert_voucher_fixed_price_currency(active_vouchers, currency.code).\ filter(voucher_ranges__packs__product__id=OuterRef('pk'), ).values('converted_fixed_price')[:1] voucher_percent_amount = is_discounted_subquery.filter( voucher_ranges__packs__product__id=OuterRef('pk'), ).values('value_percentage_based')[:1] qs = self.annotate( is_discounted=Case( When( Q(Exists(is_discounted_subquery)), then=True, ), default=False ), voucher_kind=Case( When( Q(is_discounted=True), then=Subquery(voucher_kind) ), default=Value('no_voucher') ), voucher_type=Case( When( Q(is_discounted=True), then=Subquery(voucher_type) ), default=Value('no_voucher') ), fixed_static_discount=Case( When(Q( is_discounted=True, voucher_kind=VoucherKindChoices.Static_based, voucher_type=VoucherTypeChoices.Fixed_price_based ), then=Subquery(voucher_fixed_amount) ), default=0, output_field=MoneyCurrencyOutput(currency) ), percentage_static_discount=Case( When(Q( is_discounted=True, voucher_kind=VoucherKindChoices.Static_based, voucher_type=VoucherTypeChoices.Percentage_based ), then=Subquery(voucher_percent_amount) ), default=0, ), price_after_static_discount=Case( When( Q( is_discounted=True, voucher_kind=VoucherKindChoices.Static_based, voucher_type=VoucherTypeChoices.Fixed_price_based), then=ExpressionWrapper( F('default_pack_price') - F('fixed_static_discount'), output_field=MoneyCurrencyOutput(currency), ) ), When( Q( is_discounted=True, voucher_kind=VoucherKindChoices.Static_based, voucher_type=VoucherTypeChoices.Percentage_based), then=ExpressionWrapper( F('default_pack_price') * (100 - F('percentage_static_discount')) / 100, output_field=MoneyCurrencyOutput(currency), ) ), default=0, output_field=MoneyCurrencyOutput(currency) ), ) return qs This the QuerySet explain and the query in SQL: https://explain.depesz.com/s/xIgD#source Im not sure why planning time is … -
Design approach for quiz application with different types of questions and response types
I am trying to implement this functionality along with the ability of a user to select if the question is a multiple choice question with options, a short answer question stem with an answer field, and an image video question where the stem can be an image with fields to respond. So far: class Question(models.Model): QUESTION_TYPE_CHOICES = [ ('MCQ', 'MultipleChoiceQuestion'), ('SAQ', 'ShortAnswerQuestion'), ('IVQ', 'ImageVideoQuestion'), ] id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) paper = models.ForeignKey(Paper, on_delete=models.CASCADE, null=True) question_type = models.CharField(max_length=200,choices=QUESTION_TYPE_CHOICES, null=True) # MultipleChoiceQuestion, ShortAnswerQuestion, EssayQuestion, ImageVideoQuestion question_text = models.CharField(max_length=200) def __str__(self): return self.question_text class Meta: abstract = True class MultipleChoiceQuestion(Question): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) paper = models.ForeignKey(Paper, on_delete=models.CASCADE, null=True) # multiple_choice_question_text = models.CharField(max_length=200) multiple_choice_option_text = models.CharField(max_length=200, default=None) def __str__(self): return self.question_text class MultipleChoiceOption(models.Model): multiple_choice_question = models.ForeignKey(MultipleChoiceQuestion, on_delete=models.CASCADE, null=True) multiple_choice_option_text = models.CharField(max_length=200, default=None) is_correct = models.BooleanField(default=False) def __str__(self): return self.multiple_choice_option_text # applies to short answer questions and essays class ShortAnswerQuestion(Question): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) paper = models.ForeignKey(Paper, on_delete=models.CASCADE, null=True) # short_answer_question_text = models.TextField() # Text of the question answer_text = models.TextField() # Answer to the question discussion = models.TextField(blank=True) # Discussion or additional information about the question (optional) def __str__(self): return self.question_text # applies to OSCEs, POTS or other question with … -
how to perform the validation on django html form
View def Checkout(request): amount_str = request.POST.get('amount') amount = int(float(amount_str) * 100) cart = request.session.get('cart') tax = sum(i.get('tax', 0) for i in cart.values() if i) payment = client.order.create( { "amount": amount, "currency": "INR", "payment_capture" : "1" } ) order_id = payment['id'] context = { 'tax' : tax, 'order_id' : order_id, 'payment' : payment, } return render(request, 'checkout/checkout.html', context) html <div class="container"> <form method="post" action="{% url 'placeorder' %}"> {% csrf_token %} <div class="row"> <div class="col-lg-6"> <div class="checkbox-form mt-30"> <h3>Billing Details</h3> <div class="row"> <div class="col-md-6"> <div class="checkout-form-list"> <label>First Name <span class="required">*</span></label> <input type="text" value="{{user.first_name}}" name="first_name" placeholder="" readonly> <input type="text" value="{{order_id}}" name="order_id" placeholder="" hidden> <input type="text" value="{{payment}}" name="payment" placeholder="" hidden> </div> </div> <div class="col-md-6"> <div class="checkout-form-list"> <label>Last Name <span class="required">*</span></label> <input type="text" value="{{user.last_name}}" name="last_name" placeholder="" readonly> </div> </div> <div class="col-md-12"> <div class="checkout-form-list"> <label>Address <span class="required">*</span></label> <input type="text" name="address" placeholder="Street address"> </div> </div> </form> </div> Not adding all the fields this is my checkout page. if I click the continue button I want to perform the validation like all the fields are required. but in this case, I did not add any validation so I got the page error how can I add the validation in this code -
how does django oscar register the user model in the admin?
my custom User rom django.db import models from oscar.apps.customer.abstract_models import AbstractUser class User(AbstractUser): phone = models.CharField(max_length=32, blank=True, null=True) # new class Meta: db_table = 'auth_user' my extra settings 'users.apps.UsersConfig' AUTH_USER_MODEL = 'users.User' The model works correctly in the dashboard, but I didn't find the code that register user and user groups in admin panel. How oscar do that? -
Python Django from channels.generic.websocket import WebsocketConsumer
Python Django WebSocket connection to 'ws://192.168.3.12:8000/room/74b38da601c8d3bce0dcfd269d72fc4c0c5c63d7abe0d74599a6c0cc39a110f9/' failed:enter image description here [20/Jul/2023 11:13:34] "GET /room/0ab774881c5b30fc126ad1a0acc4d4202228982ddbbeb44cfaf92f2cc952e141/ HTTP/1.1" 404 6463 I checked the urls,find there don't have /room; But,routing.py: websocket_urlpatterns = [re_path(r'room/(?P<group>\w+)/$',consumers.ChatConsumer.as_asgi()),re_path(r'enroom/(?P<group>\w+)/$',consumers.ChatEnConsumer.as_asgi()),re_path(r'chart/(?P<group>\w+)/$',consumers.ChartConsumer.as_asgi()),re_path(r'user_actual_line/(?P<group>\w+)/$', consumers.UserActualLineConsumer.as_asgi()),] So I suspect something is wrong with websocketconsumer -
Command line not recognizing 'djstripe_sync_plans_from_stripe' or 'djstripe_sync_plans'
Has anyone else encountered / solved this issue? We've found no insight into this from the web. But as far as we can tell, I have to run at least one of these commands to sync our Stripe account with our Django database models. The CLI command that's worked for all our other teammates has been: python3 manage.py djstripe_sync_plans_from_stripe The expectation, as I understand, is that this command should sync Django models from relevant data on the Stripe account, however my terminal doesn't recognize this command. This is the first time the team has experienced this while onboarding a new collaborator. One command that is recognized is: python3 manage.py djstripe_sync_models This command produces a number of funky errors which may or may not be related to the issue at hand, but it does run. This illustrates that some of these "djstripe" commands are recognized, just not the one that we need. Bottom line, we need to find a fix or a workaround. -
Django form image field mandatory error even when filled
I have a form that works both for when creating a new instance or editing one, on django. The problem is that no matter what scenario, even when I fill the input file fields, it always returns error that fields are mandatory. The models.py: class Images(models.Model): background_image = models.ImageField(upload_to='images/') user_image = models.ImageField(upload_to='images/user/') other_model = models.OneToOneField( "OtherModel", on_delete=models.CASCADE ) forms.py file: class ImagesForm(forms.ModelForm): background_image = forms.ImageField( widget=CustomImageInputWidget(attrs={"id": "background_input", "title": _("Background")}) ) user_image = forms.ImageField( widget=CustomImageInputWidget(attrs={"id": "logo_input", "title": _("Logo")}) ) class Meta: model = Images fields = "_all_" views.py file: if request.POST: images_form = ImagesForms(request.POST, request.FILES, instance=image_forms_instance) else: images_form = ImagesForms(initial={"other_model": other_model}, instance=customizable_instance) template file: <form method="POST" enctype="multipart/form-data" id="my-form"> {{ csrf_input }} {{images_form.as_p()}} {{images_form.errors}} <div class="tools-card-footer"> <span class="tools-icon-share"> <input type="submit" name="custom" value="Start"> </span> </div> </form> custom widget file: {% if widget.is_initial %}{{ widget.initial_text }}: <a href="{{ widget.value.url }}">{{ widget.value }}</a>{% if not widget.required %} <input type="checkbox" name="{{ widget.checkbox_name }}" id="{{ widget.checkbox_id }}"{% if widget.attrs.disabled %} disabled{% endif %}> <label for="{{ widget.checkbox_id }}">{{ widget.clear_checkbox_label }}</label>{% endif %}<br> {{ widget.input_text }}:{% endif %} <input type="{{ widget.type }}" name="{{ widget.name }}"{% include "django/forms/widgets/attrs.html" %}> <div class="dropzone" id="{{widget.attrs.id}}-div"> <input accept="image/png, image/gif, image/jpeg" type="file" name="file" id="{{widget.checkbox_id}}" {% for name, value in widget.attrs.items() %}{% if value is not … -
Can't import django_heroku
I'm currently trying to deploy a django-react application to heroku, I'm following a guide and it tells me to install django-heroku package (as well as psycopg2, psycopg2-binary, whitenoise, etc). All of those are installed on my virtual environment (env) requirements.txt asgiref==3.7.2 botocore==1.31.5 cachetools==5.3.1 certifi==2023.5.7 cffi==1.15.1 charset-normalizer==3.1.0 colorama==0.4.6 cors==1.0.1 dj-database-url==2.0.0 Django==4.2.2 django-cors-headers==4.1.0 django-heroku==0.3.1 django-storages==1.13.2 djangorestframework==3.14.0 djangorestframework-simplejwt==5.2.2 filelock==3.12.2 future==0.18.3 gcloud==0.18.3 gevent==22.10.2 googleapis-common-protos==1.59.1 greenlet==2.0.2 gunicorn==21.2.0 httplib2==0.22.0 idna==3.4 jmespath==1.0.1 jws==0.1.3 oauth2client==4.1.3 oauthlib==3.2.2 packaging==23.1 Pillow==9.5.0 protobuf==4.23.4 psycopg2==2.9.6 psycopg2-binary==2.9.6 pyasn1==0.5.0 pyasn1-modules==0.3.0 pycparser==2.21 pycryptodome==3.18.0 PyJWT==2.7.0 pyparsing==3.1.0 Pyrebase4==4.7.1 PySocks==1.7.1 python-dateutil==2.8.2 python-dotenv==1.0.0 python-jwt==2.0.1 pytz==2023.3 requests==2.29.0 requests-file==1.5.1 requests-oauthlib==1.3.1 requests-toolbelt==0.10.1 rsa==4.9 s3transfer==0.6.1 six==1.16.0 sqlparse==0.4.4 tldextract==3.4.4 typing_extensions==4.7.1 tzdata==2023.3 uritemplate==4.1.1 urllib3==1.26.16 whitenoise==6.5.0 zope.event==5.0 zope.interface==6.0 But when I try to import django-heroku it says "Import "django_heroku" could not be resolved".Issue. File structure: image. What should I try? I want the installed packages to work (dj_database_url doesn't work too). I tried reinstalling the necessary packages (also the whole environment), but it simply doesn't work. I'm sure I'm using my virtual environment (env) -
PostgreSQL/Django: target >2 Billion (2.000.000.000) Limit/Advice
I developed an R&D database to store machine time data. From this raw time I calculate/extract statistics. Suggestions/advice is needed regarding data size limits. Setup: Django (Python) backend with PostgreSQL database. Concept: Every machine: stores about 300.000 records split over two tables: index_table and data_table. An index_table contains machine info (setting, labels, operator). The data_table has 7 fields (index*, step*, datetime, value, setpoint, comment, active) where index* is an foreign key to index table and step* an foreign key to measurement settings. Comment field (text) about 30 chars. Workflow: Normally raw data (300.000 records) is uploaded to data_table and statistics are calculated/extracted. Typical user: Zero: Upload and extract datafile to database (index_table, data_table). Every time about 300.000 records in data_table. After that user "initiates calculate statistics". First: "production" report request is to collect statistics (no problems relative small tables). Second: "R&D" report request raw data (300.000 records) and server make some transformations and plots (Plotly) over HTML Status: Currently I uploaded 400 machines. The data_table has 30.000.000 (30 million) records and the database size is: 10Gb. The server is running on a low end workstation. Performance is fine and smooth. And above my expectation (last large database experience 20 years … -
How do I create multiple different types of POST requests in Django that can each be handled in a different way?
In my django project, I have a page which allows users to add a task through clicking a button and entering the details of the task(in a modal window). Users are also able to edit/delete tasks by clicking a button next to each respective task. I've run into the issue of not being able to submit different types of post requests that can handle each operation individually. Here is an image of the page for clarity: User interface I'm not sure how to create two different "types" of POST requests that can handle these two cases. One "type" of POST request for adding a task and another for editing/deleting it. Just for reference, this is what the modal window would look like to add a task: add task Right now this is the URL I want both of them to redirect to when the form is submitted(which is just the original page after the modal window is removed after submission) is: path('team/<str:team>/', views.team_view) This is the team_view function currently: def team_view(request, team): connection.connect() team_url = team[4:] if(team[4] == '1'): team_num = team[4:] else: team_num = team[5] tasks = Task.objects.filter(team_id=team_num) context = { 'task_list' : tasks, 'team_id' : team_num, 'team_id_url': team_url … -
django ajax send data from view to template and display these value
I would like to know how I can display data in django template like {{data}} from ajax post request. This is how I handled the ajax request in the views let say that I have a context data dict context = {'value1': Model.objects.filter(field=value), 'value2': request.POST.get('valu') } if request.is_ajax(): I would like to have the same data and display data into the template when the request is ajax return JsonResponse(context) I would like to display the same data in template as {{value1}} {{value2}} but when its ajax request the data is not displayed anymore. Please help to understand. Thank you for all. -
Django: Setting default value of model field to an attribute of a OneToOneField of a ForeignKey object
I am trying to set Report.branch to Report.user.profile.branch, however I receive the error: AttributeError: 'ForeignKey' object has no attribute 'profile". I understand this is happening because user is a ForeignKey object and not an actual User object, but I am not sure how to resolve it. Here is the code I am using: accounts/models.py from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver class Branch(models.Model): id = models.AutoField(primary_key=True) manager = models.ForeignKey(User, on_delete=models.DO_NOTHING) address = models.CharField(max_length=50) city = models.CharField(max_length=30) def __str__(self): return self.city class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) branch = models.ForeignKey(Branch, on_delete=models.DO_NOTHING) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): ''' Creates Profile when User is created ''' if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): ''' Saves Profile when User is saved ''' instance.profile.save() otherapp/models.py from django.db import models from django.contrib.auth.models import User from django.utils import timezone from accounts.models import Branch class Report(models.Model): user = models.ForeignKey(User, on_delete=models.DO_NOTHING) branch = models.ForeignKey(Branch, default=user.profile.branch) report_num = models.AutoField(primary_key=True) If you have anything to point me in the right direction that would be appreciated. -
django form.save() leads to encoding errors
When saving German Umlaute to my database I end up with the unicode representation of the letters. Saving the word Nüsse in my postgrey database reads as N\u00fcsse. The form is simply saved by: class ProductUpdateView(UpdateView): template_name = ... form_class = ProductForm def form_valid(self, form, *args, **kwargs): try: form.save() except IntegrityError: return self.form_invalid(form) return HttpResponse(...) Product(models.Model): data = models.JSONField() number = models.PositiveIntegerField() So I thought I need a customized JSON field, whereas I altered my code: class myJSONField(models.JSONField): def get_prep_value(self, value): if value is None: return value return json.dumps(value, ensure_ascii = False) class Product(models.Model): data = models.myJSONField() number = models.PositiveIntegerField() but this lead to a database entry that read "{\"name\": \"Nüsse\" ...}" where all of the '"' where escaped by '\'. I evaluated the problem using SQLite and the error prevails. My idea would be to use the form's clean method: def clean(self, *args, **kwargs): cleaned_data = super().clean() for key in cleaned_data.keys(): cleaned_data[key] = encoded(cleaned_data[key]) return cleaned_data but I am unsure on how encoded should look like here, or if I should still use the myJSONFieldapproach. The database collation says its utf8mb4_general_ci: -
pip install virtualenvwrapper-win not working
pip install virtualenvwrapper-win after this above command these errors are shown ERROR: Could not find a version that satisfies the requirement virtualenvwrpper-win (from versions: none) ERROR: No matching distribution found for virtualenvwrpper-win I cann't solve this problem. i tried to create a virtual environment wrapper. -
product.reviews undefined in react ProductScreen
In my Django + react + redux ecommerce project reviews are not visible on product screen. models.py: class Product(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200, null=True, blank=True) image = models.ImageField(null=True, blank=True, default='/placeholder.png') brand = models.CharField(max_length=200, null=True, blank=True) category = models.CharField(max_length=200, null=True, blank=True) description = models.TextField(null=True, blank=True) rating = models.DecimalField( max_digits=7, decimal_places=2, null=True, blank=True) numReviews = models.IntegerField(null=True, blank=True, default=0) price = models.DecimalField( max_digits=7, decimal_places=2, null=True, blank=True) countInStock = models.IntegerField(null=True, blank=True, default=0) createdAt = models.DateTimeField(auto_now_add=True) _id = models.AutoField(primary_key=True, editable=False) def __str__(self): return self.name class Review(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200, null=True, blank=True) rating = models.IntegerField(null=True, blank=True, default=0) comment = models.TextField(null=True, blank=True) createdAt = models.DateTimeField(auto_now_add=True) _id = models.AutoField(primary_key=True, editable=False) def __str__(self): return str(self.rating) everything is migrated, I checked it. product_views.py: @api_view(['POST']) @permission_classes([IsAuthenticated]) def createProductReview(request, pk): user = request.user product = Product.objects.get(_id=pk) data = request.data # review already exists alreadyExists = product.review_set.filter(user=user).exists() if alreadyExists: content = {'details':'Product already reviewed'} return Response(content, status=status.HTTP_400_BAD_REQUEST) # no rating or 0 stars elif data['rating'] == 0: content = {'details': 'Please select a rating'} return Response(content, status=status.HTTP_400_BAD_REQUEST) #create review else: review = Review.objects.create( user=user, product=product, name=user.first_name, rating=data['rating'], comment=data['comment'], ) reviews = product.review_set.all() product.numReviews = len(reviews) # calulate rating: total … -
ImportError: cannot import name 'name' from partially initialized module 'app.models' [closed]
У меня два приложения Users и Main для работы с пользователями и с основным ядром соответственно, в main реализованы модели в которых храниться пользователь. из-за чего я не могу импортировать основные сущности которые относятся к приложению main в users и наоборот, суть ошибки я понимаю но, что делать? Единственное её решение это идти наперерез логике и реализовывать функции там, где им не место, например, я хочу показать сколько пользователь получил лайков на свои посты, и этот метод я реализую в модели Card(мое название для модели постов) хотя по логике должен был в моделе User все это просто по тому что я не могу импортировать нужные мне модели в приложение Users. Пока что все функции я реализовал где это максимально приближенно к логике (не считая модель User) подскажите можно ли как то обойти это ошибку и может это не ошибка вовсе -
Can't use django Form.clean() method
I'm trying to add some extra validation to a form overriding it's clean method but the error doesn't raises, a ValueError exception saying "The view apps.orders.views.view didn't return an HttpResponse object. It returned None instead." raises instead, but if I make an else clause in the if condition to check if the form is valid or not and print form.errors it prints the error created in the clean method. For the record, I'm usin the form along with a formset. Thanks beforehand. Here the form: class OrderForm(forms.ModelForm): """ModelForm Class for Orders objects.""" class Meta: model = Order fields = '__all__' widgets = { 'executor_signature_date': forms.DateInput( format=('%Y-%m-%d'), ), 'customer_signature_date': forms.DateInput( format=('%Y-%m-%d'), ), } def clean(self): cleaned_data = super().clean() check_diagnosis = cleaned_data.get("check_diagnosis") repair = cleaned_data.get("repair") install = cleaned_data.get("install") maintenance = cleaned_data.get("maintenance") if (not check_diagnosis) and (not repair) and (not install) and (not maintenance): self.add_error(None, "At least one modality option must be checked.") else: return cleaned_data The check_diagnosis, repair, install and maintenance fields are BooleanField. Here the view: def post(self, request, **kwargs): order = Order.objects.get(pk=kwargs['pk']) form = self.form_class(request.POST, instance=order) ItemTimesFormSet = modelformset_factory(ItemTimes, exclude=['order']) formset = ItemTimesFormSet(request.POST) if form.is_valid() and formset.is_valid(): order.items.clear() form.save() for form in formset: if form.cleaned_data.get('item'): item = form.cleaned_data.get('item') times = … -
Best way to process images
I have a project that I am using django for backend and flutter for the frontend.The project involves uploading many images to the the backend through the mobile app which is the flutter.I want to know what is the best way to process the images like compression,resize e.t.c.Should I do it in the backend after they are uploaded or in the frontend during the time they are uploaded Also as a follow up question,if I decide to do it in the backend how do I go about it.I'm thinking about using signals to process and save the images after the model is created or celery to do same.Also which is best in this case signals or celery? -
How do I order a many to many relationship based on a field in the intermediary table?
I am writing a django application that tracks ranked statistics for a player in a video game. When I define the "through" field of a many to many relationship, I expect the resulting query to be ordered using the "ordering" meta field of the intermediary object. I cannot get the test below to pass. My db is fully migrated. Where am I misunderstanding things? Model Code from django.db import models class Player(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, unique=True, editable=False) name = models.CharField(max_length=255) class GameMode(models.Model): name = models.CharField(max_length=30) leaderboard = models.ManyToManyField(Player, through="ELO", related_name="game_modes") class ELO(models.Model): player = models.ForeignKey(Player, related_name="elos", on_delete=models.PROTECT) game_mode = models.ForeignKey(GameMode, related_name="elos", on_delete=models.PROTECT) current = models.PositiveIntegerField(default=0) peak = models.PositiveIntegerField(default=0) class Meta: unique_together = ["player", "game_mode"] ordering = ("-current",) Test Code def test_leaderboard_works_okay_with_different_game_modes(db): # checks that creating player elos will have them sorted on the game_mode leaderboard game_mode1 = GameMode.objects.create() game_mode2 = GameMode.objects.create() player1 = Player.objects.create() player2 = Player.objects.create() ELO.objects.create(game_mode=game_mode1, player=player1, current=1500) ELO.objects.create(game_mode=game_mode2, player=player1, current=1000) ELO.objects.create(game_mode=game_mode1, player=player2, current=1000) ELO.objects.create(game_mode=game_mode2, player=player2, current=1500) assert game_mode1.leaderboard.first() == player1 assert game_mode2.leaderboard.first() == player2 Error Log The leaderboard has the list of players, but they aren't correctly ordered and the assertion fails. > assert game_mode2.leaderboard.first() == player2 assert <Player: Player object (30a9670a-28de-4027-b7c0-70cec65ec08e)> == <Player: Player object … -
Carousel Navigation icon in Django
{% extends 'shop/basic.html' %} {% block css %} .col-md-3 { display: inline-block; margin-left:-4px; } .carousel-indicators .active { background-color: blue; } .col-md-3 img{ width: 170px; height: 200px; } body .carousel-indicator li{ background-color: blue; } body .carousel-indicators{ bottom: 0; } body .carousel-control-prev-icon, body .carousel-control-next-icon{ background-color: blue; } .carousel-control-prev, .carousel-control-next{ top: auto; bottom: auto; padding-top: 222px; } body .no-padding{ padding-left: 0, padding-right: 0; } {% endblock %} {% block body %} {% load static %} <div class="container"> <!--Slideshow starts here --> {% for product, range, nSlides in allProds %} <h5 class="my-4">Flash Sale On {{product.0.category}} - Recommended Items</h5> <div class="row"> <div id="demo{{forloop.counter}}" class="col carousel slide my-3" data-ride="carousel"> <ul class="carousel-indicators"> <li data-target="#demo{{forloop.counter}}" data-slide-to="0" class="active"></li> {% for i in range %} <li data-target="#demo{{forloop.parentloop.counter}}" data-slide-to="{{i}}"></li> {% endfor %} </ul> <div class="container carousel-inner no-padding"> <div class="carousel-item active"> {% for i in product %} <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card align-items-center" style="width: 18rem;"> <img src='/media/{{i.image}}' class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title" id="namepr{{i.id}}">{{i.product_name}}</h5> <p class="card-text">{{i.desc|slice:"0:53"}}...</p> <span id="divpr{{i.id}}" class="divpr"> <button id="pr{{i.id}}" class="btn btn-primary cart">Add To Cart</button> </span> <a href="/shop/products/{{i.id}}"><button id="qv{{i.id}}" class="btn btn-primary cart">QuickView</button></a> </div> </div> </div> {% if forloop.counter|divisibleby:4 and forloop.counter > 0 and not forloop.last %} </div> <div class="carousel-item"> {% endif %} {% endfor %} </div> </div> </div> <!-- left … -
Object has no attribute issue
I've followed a tutorial on how to create a CRM via Python, Django and came across an issue in the end result. When I attempt to convert a lead into a client, I am faced with 'Lead' object has no attribute 'comment'. This is present if the lead has comments under it and if it does not. But once I get back to the lead list, I notice that the lead has been converted and duplicate 4 times. Has anyone else come across this issue? And how would I go about fixing it? Below is the models.py file class Lead(models.Model): LOW = "low" MEDIUM = "medium" HIGH = "high" CHOICES_PRIORITY = ((LOW, "Low"), (MEDIUM, "Medium"), (HIGH, "High")) team = models.ForeignKey(Team, related_name="leads", on_delete=models.CASCADE) name = models.CharField(max_length=255) email = models.EmailField() number = models.CharField(max_length=255) description = models.TextField(blank=True, null=True) priority = models.CharField(max_length=10, choices=CHOICES_PRIORITY, default=MEDIUM) converted_to_client = models.BooleanField(default=False) created_by = models.ForeignKey( User, related_name="leads", on_delete=models.CASCADE, default="Admin" ) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) class Meta: ordering = ("name",) def __str__(self): return self.name class Comment(models.Model): team = models.ForeignKey( Team, related_name="lead_comments", on_delete=models.CASCADE ) lead = models.ForeignKey(Lead, related_name="comments", on_delete=models.CASCADE) content = models.TextField(blank=True, null=True) created_by = models.ForeignKey( User, related_name="lead_comments", on_delete=models.CASCADE ) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.created_by.username This is … -
CSS Background Image Not Being Applied To Django Project Correctly
I'm attempting to develop a rather simple playlist directory and when working on the frontend, I encountered an issue creating a blur and hover effect for the cards. I originally started with the template from App Seed: Template Code, which I attempted to add some css on. The issue is that although all the other css is being applied, the background and hover seem to be conflicted by something and are not being applied, instead its just the card with the correctly formatted texts. This is the template I'm attempting to apply the CSS to: {% extends "layouts/base.html" %} {% block title %} Basic Elements {% endblock %} <!-- Specific Plugin CSS goes HERE --> {% block plugin_stylesheets %} <!-- Plugin css for this page --> <link rel="stylesheet" href="/static/assets/vendors/select2/select2.min.css"> <link rel="stylesheet" href="/static/assets/vendors/select2-bootstrap-theme/select2-bootstrap.min.css"> <!-- End plugin css for this page --> {% endblock plugin_stylesheets %} <link rel="stylesheet" href="/static/assets/css/playlist.css"> <!-- Specific CSS goes HERE --> {% block stylesheets %}{% endblock stylesheets %} {% block content %} **Unrelated Code*** <div class="row"> <div class="col-md-3"> <div class="card playlist-card"> <div class="card-body bg-blur"> <!-- Content of the first playlist card --> <h5 class="card-title">Playlist Title 1</h5> <h6 class="card-subtitle">Subtitle 1</h6> <p class="card-description">Description of the first playlist.</p> </div> </div> </div> … -
How to handle a file which has been passed as a string from backend in react?
in my react app, i have a button that triggers a request to backend Django. In the response of that request, there is a excel file but it has passed as a string like the image I added in the bottom. do you have any idea how should i handle that file to be downloaded on users system? picture of the response i'm getting -
Django email sends multiple times when attachment is bigger in size
We are using Django and use EmailMultiAlternatives library of django core mail to send email. we are facing issue that we are getting multiple same email when we attach attachment with bigger size. test case: when attachment size is around 1 MB get one email 1 times when attachment size is around 5 MB get one email 4 times when attachment size is around 8 MB get one email 5 times As we are sending mail once after adding all attachments but getting same email multiple times when attachment size is bigger. -
Multi level Drop Down with a gap
I have built a nav bar which has a dropdown and inside this dropdown when each item is hovered, another drop down appears in tree view. I don't want it to be in tree view, I want to be at same starting height. What I mean is when I select the second item the second dropdown at right appears with a gap above, I don't want it. Please ignore other errors. Here is the code: * { margin: 0; padding: 0; } .header-bottom { height: 8vh; background-color: #283045; position: relative; } .navigation-menu { height: 100%; /* Set the navigation menu's height to 100% of its parent (.header-bottom) */ display: flex; align-items: center; justify-content: space-between; padding-top: auto; padding-left: 13%; padding-right: 9.5%; font-size: 15px; } .navigation-menu ul { list-style: none; height: 100%; margin: 0; /* Remove default margin */ padding: 0; /* Remove default padding */ display: flex; align-items: center; text-align: center; } .navigation-menu .nav-content { height: 100%; display: flex; align-items: center; } .navigation-menu .nav-content .nav-link{ display: inline-block; display: flex; align-items: center; padding: 10px 30px; position: relative; height: 100%; } .navigation-menu .nav-content li a { color: aliceblue; text-decoration: none; text-transform: uppercase; } .navigation-menu .nav-content li a .arrow-down{ position: relative; left: 10px; } …