Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Watchtower connection refused when running server localhost
I am using Django [watchtower][1] to log events to Cloudwatch and have configured my logging in my settings file. development.py boto3_session = Session( aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY, region_name=AWS_REGION) LOGGING = { 'version': 1, 'disable_existing_loggers': False, # 'root': { # 'level': 'INFO', # 'handlers': ['console'], # }, 'formatters': { 'simple': { 'format': "%(asctime)s [%(levelname)-8s] %(message)s", 'datefmt': "%Y-%m-%d %H:%M:%S" }, 'aws': { # you can add specific format for aws here 'format': "%(asctime)s [%(levelname)-8s] %(message)s", 'datefmt': "%Y-%m-%d %H:%M:%S" }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, 'watchtower': { 'level': 'INFO', 'class': 'watchtower.CloudWatchLogHandler', 'boto3_session': boto3_session, 'log_group': 'StagingBeagleApi', 'stream_name': 'ApplicationLogStream', 'formatter': 'aws', }, }, 'loggers': { 'django': { 'level': 'INFO', 'handlers': ['watchtower'], 'propagate': True, }, }, } However when I run my server, I don't get any error in the console but my site is not accessible anymore via locahost:3000, I get an ERR_CONNECTION_REFUSED Please help! [1]: https://pypi.org/project/watchtower/ -
Get user object from token string in DRF Token In Django using Knox Token
I have question related with Django . I am using Knox Token Authentication to generate tokens for every user when he log in on the page. Now I want to use that token for every request that will send so I can get the corresponding user for the token. Also I am using custom function example def dashboard(request) in Django for every URL route. I have see on youtube that there are option to get user from token but is not with functions class UserAPI(generics.RetrieveAPIView): permission_classes = [ permissions.IsAuthenticated, ] serializer_class = UserSerializer def get_object(self): return self.request.user So is there a whey to get the corresponding user from a token within a custom function -
Django model string representation
I know that a model object string representation can be achieved by adding class Company(models.Model): name = models.CharField() email = models.EmailField(unique=True) def __str__(self): return self.name But this is the representation of an object of Company but not the model class itself. Meaning if I create an object obj = Company(name='string_repr', email='example@example.com') print(obj) would result in 'string_repr' which is as expected since Im getting the string representation of the object, not the class/ model. However I noticed that during a CreateView form validation in case if there already is an object of the model with the same email Django returns an error message that the there already is a Company with such an email (picture is not in English but the underlined section is the only relevant part). I suppose the error message is taking the class name and inputting it in the message, but is there a way how to alter the string representation of the model (class) name? Its needed for translation purposes. I guess I could just rename the class names to local language but that doesn't seem right. -
How to effficiently get count of foreign keys in Django model?
I have three models like this: class House(models.Model): name = models.CharField(max_length=150) def get_house_count(self): fetchs = 0 for fetch in self.fetchs.all(): fetchs += 1 return fetchs class Person(models.Model): house = models.ForeignKey(House, related_name="persons", on_delete=models.PROTECT) first_name = models.CharField(max_length=150) def get_person_count(self): person_fetchs = 0 for fetch in self.person_fetchs.all(): person_fetchs += 1 return person_fetchs class Fetch(models.Model): number = models.CharField(max_length=150) house = models.ForeignKey(Hourse, related_name="fetchs") person = models.ForeignKey(Person, related_name="person_fetchs") What I want to achieve is to get the total number of each model instance in the Fetch class. But this operation is very expensive(over 500 duplicates) as it creates multiple SQL duplicates when I use the django_debug_tool library. Is there an efficient way to do this? My view.py file is like this: class HomeView(ListView): queryset = Fetch.objects.select_related( 'house', 'person', ) template_name = "index.html" paginate_by = 100 And in my template I have something like this: {% for obj in object_list %} <tr> <td>{{ obj.company.name }}</td> <td>{{ obj.house.get_house_count }}</td> <td>{{ obj.person.get_person_count }}</td> I have also tried to use the django's annotate method like this: queryset = Fetch.objects.select_related( 'house', 'person', ).annotate( get_count=Count('house', distinct=True), get_contact_count=Count('person', distinct=True) ) while making changes to my template using {{obj.get_count}} and {{obj.get_contact.count}} respectively. But it returns a count of 1 which is wrong. Any help … -
How can I add translate attribute in the below code. I am gonna provide translation in .po file
<th rowspan="2" class="text-center">a1</th> <th rowspan="2" class="text-center"> a2</th> <th rowspan="2" class="text-left">a3</th> <th rowspan="2" class="text-center">a4</th> How can I add translate attribute in the below code. I am gonna provide translation in .po file. -
I keep getting this error ModuleNotFoundError: No module named 'template'
I keep getting the error ModuleNotFoundError: No module named 'template'. I have no idea what to do or where this error is coming from. I think it might be coming from the setting file but I do not know what to change. If anyone knows how to fix this your help would be much appreciated. I have the error and my settings file down below. Error: Traceback (most recent call last): File "C:\Users\sekoc\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\sekoc\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) File "C:\Users\sekoc\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\sekoc\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management\commands\runserver.py", line 68, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "C:\Users\sekoc\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\conf\__init__.py", line 82, in __getattr__ self._setup(name) File "C:\Users\sekoc\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\conf\__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "C:\Users\sekoc\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\conf\__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2032.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "C:\Users\sekoc\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\conf\__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "C:\Users\sekoc\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\conf\__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2032.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, … -
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?