Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom user model object not created after allauth signup
I'm trying to create a custom user object (Author model) right after a new user signs up using allauth's signal, the signup works fine and the User is created but the object (Author) is not being created. This is my Author (custom user) model: class Author(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.first_name + ' ' + self.user.last_name This is what I have in my view: @receiver(user_signed_up) def after_user_signed_up(request, user): author = Author.objects.create(user=user) Any idea what I might be doing wrong? Should I be setting the custom user differently to make this work? I'll be adding more fields to the Author model later on and I saw that doing a one-to-one relation should be the way to go, but not sure why this isn't working. Thanks in advance! -
Composite primary key in Django and unique_together
I have a database which has table order_details with composite primary key of two fields: order and product. So one order can have many order_details, in other words: one product can have many products related to it. When I add new entries in db it works fine. In my project I use Django auto-generated models based on database's schema. The problem is, it seems that this particular model OrderDetails doesn't work like intended. It prevents me from adding new OrderDetails for Order after I add first one. It says Order details with this Order already exists. I wonder how to prorperly write a model to fulfill my intention. I tried to replace unique_together with models.UniqueConstraint, but that didn't help. I think it's all about order field being OneToOne correct me if it's not. Here's SQL create script and models. CREATE TABLE IF NOT EXISTS public.order_details ( order_id smallint NOT NULL, product_id smallint NOT NULL, unit_price real NOT NULL, quantity smallint NOT NULL, discount real NOT NULL, CONSTRAINT pk_order_details PRIMARY KEY (order_id, product_id), CONSTRAINT fk_order_details_orders FOREIGN KEY (order_id) REFERENCES public.orders (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION, CONSTRAINT fk_order_details_products FOREIGN KEY (product_id) REFERENCES public.products (id) MATCH SIMPLE … -
How Django evaluates object managers when we have multiple ones?
Consider the following objects in Django ORM: class Post(models.Model): ... published = PublishedPostManager() objects = models.Manager() Now in the Django admin, only the published ones are shown. Could we change the behavior, so the Django ORM uses objects by default without any order? -
django multiple choice field
I am trying to display virtual machines that have an associated with task. I have a vm table that lists all the virtual machines another table task which list the tasks created associated with the vms and the pivot table that links the two. In short class VirtualMachine(models.Model): //...fields class VmSchedule(models.Model): //...fields vms = models.ManyToManyField(VirtualMachine, blank=True) I can already display the list of vms and the list of associated tasks except that the display is in this form: list of VMs I would like to remove the [] and what is empty. I am new to django and I don't know how to do it. here is the code associated with this display. <table class="table" id="vm_table"> {% for value, text in form.fields.vms.choices %} <tr> <td class="clickable_vm">{{ text.0 }} <label> <input type="checkbox" name="vms" value="{{ value }}" class="displaynone"> {{ text.1 }} </label> </td> </tr> {% endfor %} class VmGroupModelMultipleChoiceField(ModelMultipleChoiceField): def label_from_instance(self, obj): list_sch = list() for j in obj.vmschedule_set.all(): list_sch.append(j.schedule) return [obj.name, list_sch] and my class form class VmScheduleForm(forms.ModelForm): vms = VmGroupModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple( attrs={'class': 'displaynone'}), queryset=VirtualMachine.objects.exclude(lock=True).order_by( 'name'), required=False, label="Choice VMs" ) //... class Meta: model = VmSchedule fields = ('schedule', 'action', 'dow', 'dom', 'mon', 'h', 'm', 'vms') widgets = { 'schedule': forms.TextInput( attrs={'class': … -
I have to call multiple webpages to extract information for a django application and then display it but I don't know how to display properly
My issue is that when I have called an external webpage and displayed as {{ html }} in the for loop it prints for all of them is there a way to print just for one. The part after b'{"carpark_name": "multi-storey", "date": "01-11-21 12:46:55", "spaces_available": 332}' this is the webpage This is my views.py from django.shortcuts import render from .models import Carpark, Campus from urllib.request import urlopen def index(request): campus_list = Campus.objects.all() carpark_list = Carpark.objects.all() noparking = Campus.objects.filter(carpark=None) html = urlopen("https://mbezbradica.pythonanywhere.com/carparks/multi-storey").read() context = {'carpark_list': carpark_list, 'campus_list': campus_list, 'noparking': noparking, 'html' : html } return render(request, "parkatdcu/index.html", context) And this is my index.html code <h1>Welcome to ParkAtDCU</h1> {% for campus in campus_list %} <h2> {{ campus }} </h2> {% if campus in noparking %} No carparks found {% else %} <ul> {% for carpark in carpark_list %} {% if campus == carpark.campus_id %} <li> {{ carpark.name }}: {{ carpark.spaces}} spaces, {{carpark.disabled_spaces}} spaces for people with disabilities, {{ html }}</li> {% endif %} {% endfor %} {{ url }} </ul> {% endif %} {% endfor %} -
Django Rest Framework Summarize Nested Object Data By Distinct Month
I'm trying to create a Category Serializer that will total the Transaction amounts by month for each category for the following models models. class Category(models.Model): description = models.CharField(max_length=255) class Transaction(models.Model): description = models.CharField(max_length=255) amount = models.FloatField() date = models.DateField() category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='transactions', blank=True, null=True ) I was able to get a list of distinct months and total amounts with the following serializer and View but when I try to use the serializer in the Category serializer I get the error at the bottom class TransactionMonthTotalSerializer(serializers.Serializer): month = serializers.CharField() totalAmount = serializers.FloatField() class CategoryMonthTotalSerializer(serializers.ModelSerializer): transactionMonth = TransactionMonthTotalSerializer(many=True) class Meta: model = Category fields = ['description','transactionMonth'] class TransactionMonthTotalViewSet(views.APIView): def get(self,request): data = Transaction.objects.filter(owner=request.user) .annotate(month=TruncMonth('date')) .values('month') .distinct() .annotate(totalAmount=Sum('amount')) results = TransactionMonthTotalSerializer(data, many=True).data return Response(results) class CategoryMonthTotalViewSet(viewsets.ModelViewSet): serializer_class = CategoryMonthTotalSerializer permission_classess = [IsAuthenticated] def get_queryset(self): return Category.objects.filter(owner=self.request.user) Got AttributeError when attempting to get a value for field transactionMonth on serializer CategoryMonthTotalSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Category instance. Original exception text was: 'Category' object has no attribute 'transactionMonth'. -
how to specify "excluded_fields" when using diff_against in simple_history in Django
I am using diff_against in simple_history in django. See "history diffing" in simple_history docs: https://django-simple-history.readthedocs.io/en/latest/history_diffing.html I have this all working, but it states: "diff_against also accepts 2 arguments excluded_fields and included_fields to either explicitly include or exclude fields from being diffed." I can't figure out how to pass these fields. Here is what I have that is working (without any include or exclude fields): def historical_changes(qry, id): changes = [] if qry is not None and id: last = qry.first() for all_changes in range(qry.count()): new_record, old_record = last, last.prev_record if old_record is not None: delta = new_record.diff_against(old_record) changes.append(delta) last = old_record return changes and I call it in a detail view using: changes = historical_changes(hpn.history.all(), hpn.pk) This all works. I then tried to incldue the "exclude_field". These are what I tried, but none worked: delta = new_record.diff_against(old_record, excluded_fields('geom')) or delta = new_record.diff_against(old_record).excluded_fields('geom') or delta = new_record.diff_against(old_record.excluded_fields('geom')) This is likley something quite simple, but I'm not figuring it out. Any help would be great. Thanks. -
Single model multiple tables: Django ORM vs SQL query
How to make multiple tables with Single model I know this has been answered before.. but like 6 year ago and lot of things been uncovered about it. Like how to handle migrations, admin panel, serializing data? and all CRUD method I have tried with sql query(i mean literally writing sql query in view.py) and its working fine.. but I want to know Django way of doing this Also, If SQL query is preferred over Django ORM please suggest me better code then what I tried before Views.py class categoryProduct(generics.GenericAPIView): def post(self, request): params = request.query_params stock_id = request.data.get("pharmacy_id") sort_by = request.data.get("sort_by") page = int(params.get("page", 1)) per_size = params.get("per_size", 10) category = params.get("category") sub_category = params.get("sub_category") cursor = connection.cursor() query = "SELECT c.id AS c_id,c.parent_id, c.category,c.image AS category_image,c.is_active, d.id AS sc_id,d.sub_category,d.is_active AS is_active2, b.id AS p_id,b.group_id,b.product_name, b.is_prep_needed,b.product_description, b.product_keypoint,b.product_type,b.image AS product_image,b.pack, b.pack_unit,b.hsn,b.company,b.brand_id,b.composition,b.d_details,b.uses,b.side_effects, b.cside_effects,b.how_it_works,b.safety_advice,b.what_if_forget,b.general_idea,b.created_at, b.created_by,b.modified_at,b.modified_by, a.id as product_id,a.expiry_date,a.quantity,a.mrp,a.selling_price,a.gst, a.featured FROM stock_" + str(stock_id) + " a JOIN product b ON a.product_id = b.id JOIN category c ON b.category = c.id JOIN sub_category d ON b.sub_category = d.id WHERE b.category=" + str( category) + " AND b.sub_category=" + str(sub_category) cursor.execute(query) records = cursor.fetchall() fields = [field[0] for field in cursor.description] all_response = [dict(zip(fields, … -
How can I perform sorting on browsed items in Django
As in title. I have a problem becasue I am not able to sort items which I browsed. Or should I use Javascript than pure Django to perform things like these? views.py def searchView(request): if request.method == "GET": context = request.GET.get('search') if not context: context = "" items = Item.objects.all().filter(title__icontains=context) try: sorting_method = request.GET.get('select') if sorting_method == 'v1': items = items.order_by('price') elif sorting_method == 'v2': items = items.order_by('-price') else: return render(request, 'shop/search.html', {'items': items}) return render(request, 'shop/sort.html', {'items': items}) except UnboundLocalError: return redirect('home-page') HTML : <form action="{% url 'search-page'%}" class="navbar__search-form" method="GET"> <input name="search" class="navbar__search-text" type="text" placeholder="Search for an item."> </form> <form action="{% url 'search-page'%}" class = "sort__form" method="GET"> <h1 class="sort__header"> SORT ITEMS </h1> <select class= "sort__select" name="select"> <option disabled selected> Sorting method</option> <option value="v1">Price: low to high</option> <option value="v2">Price: high to low</option> </select> <button class="sort__submit">SORT</button> </form> -
Allauth email verification link still works after verification and doesn't invalidate
I'm using allauth to handle my verification and I'm receiving verification emails to confirm signup. The verification email gets sent fine and works, but my problem is that even after I'm done with verification, the else statement in the html provided by allauth doesn't get triggered and the verification email still works and asks me to verify the user when I click on it, although it's already verified. email_confirm.html {% if confirmation %} {% user_display confirmation.email_address.user as user_display %} <p>{% blocktrans with confirmation.email_address.email as email %}Please confirm that <a href="mailto:{{ email }}">{{ email }}</a> is an e-mail address for user {{ user_display }}.{% endblocktrans %}</p> <form method="post" action="{% url 'account_confirm_email' confirmation.key %}"> {% csrf_token %} <button type="submit">{% trans 'Confirm' %}</button> </form> {% else %} {% url 'account_email' as email_url %} <p>{% blocktrans %}This e-mail confirmation link expired or is invalid. Please <a href="{{ email_url }}">issue a new e-mail confirmation request</a>.{% endblocktrans %}</p> {% endif %} Anyone face something similar or know a fix to this? Thanks! -
Celery ignores Django settings.py variables
I have setup a test Django environment for production on an Ubuntu 20.04 Sever using following this guide: Deploying Django. Specifically, I have placed the Django project in: /opt/mydangoproject/ celery.py celery_config.py settings.py etc and I have an additional 'override' settings.py which holds the 'secrets' specifically in this case the celery login variable RABBITMQ_BROKER it is located in: /etc/opt/mydangoproject/ settings.py I have tested this configuration and I have confirmed the settings in /etc/opt/mydangoproject/ are available to the Django environment, however, they are not picked up by celery. I have confirmed this by placing the RABBITMQ_BROKER login variable in the main settings.py (/opt/mydangoproject/) and celery is able to access it. My celery.py file: import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mydangoproject.settings') app = Celery('mydangoproject') default_config = 'mydangoproject.celery_config' app.config_from_object(default_config) app.autodiscover_tasks() The settings.py in /etc/opt/mydjangoproject/ : from mydangoproject.settings import * ALLOWED_HOSTS = [‘blah’] RABBITMQ_BROKER = 'amqp://wabbitadmin:somepassword@somepassword@webserver:5672/mydangoproject' DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': ‘blah’, 'USER': ‘blah’, 'PASSWORD': ‘somepassword', 'HOST': 'localhost', 'PORT': 5432, } } STATIC_ROOT = '/var/cache/mydangoproject/static/' STATIC_URL = '/static/' MEDIA_ROOT = '/var/opt/mydangoproject/media/' MEDIA_URL = '/media/' My questions are: why can't celery access the RabbitMQ login variable. How do I fix it? -
Understanding the requirement for the related field to provide a queryset
Consider: class CouponSerializer(serializers.ModelSerializer): courses = serializers.PrimaryKeyRelatedField( many=True, read_only=True) class Meta: model = Coupon exclude = ['users'] If I remove read_only=True, I get the error: AssertionError: Relational field must provide a `queryset` argument, override `get_queryset`, or set read_only=`True`. The documentation states: The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set read_only=True What is the logic underlying this requirement? Why is there no such requirement for StringRelatedField? -
How to create a view for details of a single post and url with two slugs in django?
I am creating a website with a blog application in django 3.2. I only have a problem with the last step, which is to create a view for a single post. Unfortunately, I don't know how to finish it.some error coming again and again I created the simplest view I can, but after entering it, I get a 500 error from the server. urls.py path('resent-post', views.resentpost, name="resentpost"), path('category', views.category, name="category"), path('en/<str:slugcat>/<slug:slug>', views.slink, name="slink"), path('hi/<str:slugcat>/<slug:slug>', views.shlink, name="shlink") views.py def slink(requst, slug, slugcat): lpost = get_object_or_404(singlepost, slug=slug) kpost = get_object_or_404(homecategory, cslug=slugcat) singlepost1 = singlepost.objects.filter('-created_date') homecategory1 = homecategory.objects.filter(category='Resent Post') data = { 'lpost': lpost, 'kpost': kpost, 'singlepost1': singlepost1, 'homecategory1': homecategory1 } return render(requst, 'webpages/single-post.html', data) def shlink(requst, slug, slugcat): lpost = get_object_or_404(singlepost, slug=slug) kpost = get_object_or_404(homecategory, cslug=slugcat) data = { 'lpost': lpost, 'kpost': kpost } return render(requst, 'webpages/single-post.html', data) models.py # Create your models here. class homecategory(models.Model): category = models.CharField(max_length=255) cslug = models.SlugField(max_length=255,unique=True, null=True, blank=True) created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.category class singlepost(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=255,unique=True, null=True, blank=True) who = models.CharField(max_length=255) board_name = models.CharField(max_length=255) posts_of = models.CharField(max_length=255) photo = models.ImageField(upload_to='media/post/%Y/%m/%d') created_date = models.DateTimeField(auto_now_add=True) from django.db.models.signals import pre_save from django.dispatch.dispatcher import receiver from .make_slug import unique_slug_generator @receiver(pre_save, sender=singlepost) def pre_save_receiver(sender, … -
Invalid format string, though did not specify any format
I am getting and "Invalid format string" error when testing the following view: class CouponListView(generics.ListAPIView): permission_classes = [IsAuthenticated, ] queryset = Coupon.objects.all() def list(self, request, format=None): queryset = request.user.coupons.all() serializer = CouponSerializer(queryset, many=True) return Response(serializer.data) Here is CouponSerializer: class CouponSerializer(serializers.ModelSerializer): courses = serializers.PrimaryKeyRelatedField( many=True, read_only=True) class Meta: model = Coupon exclude = ['users'] Finally, here is the Coupon model: class Coupon(models.Model): token = models.CharField(max_length=30) users = models.ManyToManyField(CustomUser, related_name='coupons') courses = models.ManyToManyField(Course, related_name='coupons') discount = models.IntegerField() created = models.DateTimeField() expiry = models.DateTimeField() class Meta: ordering = ['token'] def __str__(self): return self.token As far as I understand, a standard date/time format should be used for created and expiry. However, I get the following: Internal Server Error: /content/coupons/ Traceback (most recent call last): File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\rest_framework\generics.py", line 199, in get … -
How can I use Celery and get start time from user?
I need to make a celery task where a user has to enter time when he wants to start the process and after that at this exact time the task should be repeating every 24 hours. For example, I entered time 00:00 and when it is 00:00 the program will start running. And after that it will repeat every 24 hours. I have a code for celery where it already makes it run every 24 hours, I just don't know how to add the exact time when code needs to run. (Sorry for bad English, English is not my native) -
how to display the specific field seperately ?as shown in below output
Models.py class DiscountType(GeneralFields): name = models.CharField(max_length=255) description = models.TextField(null=True,blank=True) country_id = models.IntegerField() class DiscountTypeSerializer(serializers.ModelSerializer): class Meta: model = DiscountType fields = "__all__" class DiscountTypeDetailView(APIView): def get_object(self, pk): try: return DiscountType.objects.get(pk=pk) except DiscountType.DoesNotExist: raise Http404 def get(self, request, pk, format=None): discount_type = self.get_object(pk) serializer = DiscountTypeSerializer(discount_type) return Response(serializer.data) Currently i got output like this { "name": "discount 2", "discount_type": "xxx", "description": "Discount 2 updated", "maximum_limit": 1, "location_id": 1, "country_id": 1, "created_by_id": { "id": 1, "username": "john" }, "updated_by_id": { "id": 1, "username": "john" } } But i want like this { "name": "discount 2", "discount_type": "xxx", "description": "Discount 2 updated", "maximum_limit": 1, "location_id": 1, { "country_id": 1, } "created_by_id": { "id": 1, "username": "john" }, "updated_by_id": { "id": 1, "username": "john" } } -
Django - Query_set returns an empty arraylist when it is ran in the test
I am trying to run a TestCase on my model. I already have a MySQL database (specifically MariaDB through a HeidiSQL GUI) created and connected with the respective data inside for this project. My test.py code is as follows: class TestArrivalProbabilities(TestCase): def test_get_queryset_test(self): print("Hello Steve!") i = 1 self.assertEqual(i, 1) l = [3, 4] self.assertIn(4, l) def test_get_queryset_again(self): query_set = ArrivalProbabilities.objects.all() print(query_set) n = len(query_set) print(n) # Print each row bin_entries = [] bin_edges = [] for i in range(n): print(query_set[i]) if query_set[i].binEntry is not None: bin_entries.append(query_set[i].binEntry) bin_edges.append(query_set[i].binEdge) print(bin_entries, bin_edges) hist = (numpy.array(bin_entries), numpy.array(bin_edges)) However, the output in the terminal is this: (venv) C:\Users\Steve\uni-final-project>python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). <QuerySet []> 0 [] [] .Hello Steve! . ---------------------------------------------------------------------- Ran 2 tests in 0.016s OK Destroying test database for alias 'default'... I have tried to figure out why the MySQL database I built isn't being used. I read up that Django creates a Test 'dummy database' to use on a test and then tears it down after but am I missing something really obvious? I don't think it is a connection issue as I have pip installed mysqlclient. And I have … -
How to get number of records in a model in django rest framework?
I am using GenericAPIView and in model serializer to get data from tables. Now I can't understand how can I get the number of records from table in my rest api. below is my sample code where I am getting records urls.py urlpatterns = [ path('ContactList/<int:user>/',views.ContactList.as_view()), ] views.py class ContactList(GenericAPIView, ListModelMixin): def get_queryset(self): username = self.kwargs['user'] return Contacts.objects.filter(user=username).order_by('-last_message') serializer_class = ContactSerializer permission_classes = (AllowAny,) def get(self, request , *args, **kwargs): return self.list(request, *args, **kwargs) Serializers.py class ContactSerializer(serializers.ModelSerializer): class Meta: model = Contacts fields = ['id','user','Contact_id','last_message'] in above code I am getting all the contacts of some specific user. now How can I get number of records(contacts) related to this user. for example if I send user 11 in URL I should get the number of records where user=11 -
Django FIlter Alll Children Categories
I have models.py class Category(models.Model): headline = models.CharField(max_length=100) parent_category = models.ForeignKey('self', on_delete=models.CASCADE, related_name='children', null=True, blank=True) admin.py main_cat = Category.objects.filter(pk=1) And now im trying to filter all children categories of main_cat how am i going to do that? -
How do I get translated word in template in django-parler?
On my frontend detail page, in templates I want to get translated words. Since translated fields is located inside translations block class UsefulLinks(TranslatableModel, BaseModel): translations = TranslatedFields( name=models.CharField(verbose_name=_('Useful Link Name'), max_length=255) ) icon = models.ImageField(verbose_name=_('Link Icon'), upload_to='') I don't know how to get translated words in template. <input value="{{ object.name.en }}" name="title_uz" type="text" class="form-control" id="exampleInputEmail1"> I tried to get like with above method, but this doesn't seem to work. Are there any ways to get translated words directly in template just by specifity language code? The only solution I tried is on the backend to use get_context_data in order to get translated words by specifying langauge code like this def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) obj_id = self.object.id lang_uz = Menu.objects.language('uz').get(id=obj_id) context['title_uz'] = lang_uz.title and passed word to frontend template. But I want to get translated words directly from template just by specifying langauge code. -
Run a django app inside a docker container
I am running succesfully a django app that is hosted inside a docker container. I change something on my code on purpose in order for my code to break. What I need is somehow to see the log of the running code as if I was running this locally on my computer. For example I forgot to import a library and when I run this locally I get a message on the terminal like "ModuleNotFoundError: No module named 'somemodule'". But when i run the same code from inside the container I get no log, just the container fails to start. My question is: How can I get a log for my script from inside the container, so I can debug my code? -
How ListCreateAPIView works?
I am just a new in Django Rest Framework, and i want to clearly understand how ListCreateAPIView works. We just can provide a queryset, serializer_class and it will create read-write end point. I was looking for info on official doc, but didnt`d find what i want. Any information will be helpful for me. -
How to perform Django email threading?
Can someone please share how I can do threading to send an email on a shared hosting service for my Django app? I have tried python threading which works perfectly on localhost but doesn't send an email on cloud hosting. Moreover, I tried looking for celery broker but couldn't find anything on the shared hosting. Can someone suggest how to send an email on the Django app in the background so that the user doesn't have to wait? N.B: Changing the hosting service is not an option. Currently using Namecheap shared hosting. -
Get or Create function, not working in Django
maca = Maca.objects.get_or_create(maca_id=request.POST['maca_id'], defaults={ "maca1": request.POST['maca1'], "maca_id": request.POST['maca_id'], }) this create my object but when I try to access the object created like this maca.id I don't get the id. I want to access the id of the object that is got or that is created. Can someone help me please? -
Make Django ORM automatically fetch properties
Say I have a Post model like this: class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) text_content = models.CharField() @property def comment_count(self): return self.comments.count() Say I need to get all the data for the post with ID 3. I know that I can retrieve the user along with the post in one query, by doing Post.objects.select_related('user').get(pk=3), allowing me to save a query. However, is there a way to automatically fetch comment_count as well? I know I could use Post.objects.annotate(comment_count=Count('comments')) (which will require me to remove the property or change the name of the annotation, as there would be an AttributeError), however is it possible to make the ORM do that part automatically, since the property is declared in the model? Although I could just add the .annotate, this can get very tedious when there are multiple properties and foreign keys that need to be fetched on multiple places.