Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Django URL pattern to manage creation and update in the same view - NoReverseMatch error
I'm facing a 'NeReverseMatch' error that I'm not able to solve, even if I'm quite convinced it's probably a stupid error, something I missed... as I reproduce a pattern I implemented earlier in the same app. The context is the following: I have the same view for creating and updating an object. The difference is that in the second case, I have the id. Thus, related urls look like this (I put the whole file to ensure there is no mismatch with other urls): app_name = "polls" urlpatterns = [ path("", views.index, name="index"), path("get_chart_data/", views.get_chart_data, name="chart_data"), path("set_proxy/", views.set_proxy, name="set_proxy"), path("accept_proxy/", views.accept_proxy, name="accept_proxy"), path("cancel_proxy/", views.cancel_proxy, name="cancel_proxy"), path("sign_up/", views.new_user, name="sign_up"), path("login/", views.login_user, name="login"), path("logout/", views.logout_user, name="logout"), path("<slug:comp_slug>/", views.company_home, name="company_home"), path("<slug:comp_slug>/admin_users/", views.adm_users, name="adm_users"), path("<slug:comp_slug>/admin_load_users/", views.adm_load_users, name="adm_load_users"), path("<slug:comp_slug>/admin_profile/", views.adm_user_profile, name="adm_create_user"), path("<slug:comp_slug>/admin_profile/<int:usr_id>", views.adm_user_profile, name="adm_user_profile"), path("<slug:comp_slug>/change_password/", views.change_password, name="change_password"), path("<slug:comp_slug>/admin_delete_user/<int:usr_id>", views.adm_delete_user, name="adm_delete_user"), path("<slug:comp_slug>/admin_events/", views.adm_events, name="adm_events"), path("<slug:comp_slug>/admin_create_event/", views.adm_event_detail, name="adm_create_event"), path("<slug:comp_slug>/admin_update_event/<int:evt_id>/", views.adm_event_detail, name="adm_event_detail"), path("<slug:comp_slug>/admin_delete_event/<int:evt_id>", views.adm_delete_event, name="adm_delete_event"), path("<slug:comp_slug>/admin_groups/", views.adm_groups, name="adm_groups"), # ===== THE 2 FOLLOWING LINES ARE THE ISSUE ===== path("<slug:comp_slug>/admin_group_detail/", views.adm_group_detail, name="adm_create_group"), path("<slug:comp_slug>/admin_group_detail/<int:grp_id>/", views.adm_group_detail, name="adm_group_detail"), path("<slug:comp_slug>/admin_delete_group/<int:grp_id>", views.adm_delete_group, name="adm_delete_group"), path("<slug:comp_slug>/admin_options/", views.adm_options, name="adm_options"), path("<slug:comp_slug>/<slug:event_slug>/", views.event, name="event"), path("<slug:comp_slug>/<slug:event_slug>/<int:question_no>", views.question, name="question"), path("<slug:comp_slug>/<slug:event_slug>/<int:question_no>/vote", views.vote, name="vote"), path("<slug:comp_slug>/<slug:event_slug>/results", views.results, name="results"), ] The pattern is the same for users management (adm_user_profile view) with no issue. Here is … -
Override a model's DELETE method from real delete to setting a property in Django RESTful framework
We are using a django-rest-framework as our backend. I have a model Product which is the Foreign Key of another Order model, which acts as both a order and an audit log. Now suppose we are not going to sell this Product anymore. We need to apply DELETE method on the Product; and we still want to preserve everything in Order. However, if the Product is really deleted and the on_delete method on it is SET_NULL, then all info that is related to Product is lost. Which is not what I wanted. class Order(models.Model): product = models.ForeignKey(Product, blank=True, null=True, on_delete=models.SET_NULL) So my question is: A common practice in other framework is using soft-delete, i.e. adding a "delete=0" property on Product. And the DELETE method only change the property to "delete=1" rather than real delete. Is it do-able when using django-rest-framework? And how? Is there any other good practices to realize this requirement, i.e. to delete the foreign key while perserving the foreign key's metadata? -
Django Form retrieve data from database
I have a form in Django that enables me to post data to the database. I'd like to create a dropdown button that shows me the previous entries from the database, which I can select re-render the data in the original form, allowing me to update and post back to the database. I'm just starting out with Python, which I think is amazing, but I've not really grasped it yet. So I'm probably doing it completely wrong but here goes. I'm starting with just populating the dropdown. So within my models.py, I have. class Investor(models.Model): investor_name = models.CharField(max_length=255, blank=False) investor_website = models.URLField(max_length=255, blank=False) investor_portfolio = models.URLField(max_length=255, blank=False) investor_comment = models.TextField() def __str__(self): return str(self.investor_name) class showInvestor(models.Model): investorName=models.CharField(max_length=100) class Meta: db_table="apps_investor" Then within my views.py def showInvestor(request): results=showInvestor.objects.all() return render(request,"add_investor.html",{"showInvestor":results}) And then within my HTML template, i have: <div class="col-lg-2"> <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-expanded="false">Update Existing Investor <i class="mdi mdi-chevron-down"></i></button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> {% for results in showInvestor %} <option> {{results.investor_name}} </option> {% endfor %} </div> </div> </div><!-- end col --> but when I click the drop-down I don't get any entries. What am I doing wrong here? Thanks -
Object doesn't exist in DB after consequential calls
I have the following flow for object creation: A user wants to create an object on a webservice. In order to do it - I check if the user is eligible to pay a fee for it. We make a request to know how much the user should pay. If 0 - user will see the regular Create button, if >0 he will see the PayPal button. User fills in data and in the second case presses the PayPal button. We make 2 consequential API requests: Create an object with the parameter is_draft=True. Return its id. Create an order object and use the id from the previous step. Sometimes we cannot create an order, because the object doesn't exist in DB yet. Django setting: DATABASES["default"]["ATOMIC_REQUESTS"] = True Django models: class Object1(models.Model): name = models.CharField() ... class Object2(models.Model): name = models.CharField() ... class Order(models.Model): user = models.ForeignKey(User) amount = models.DecimalField() #naive polymorphism object1 = models.ForeignKey(Object1) object2 = models.ForeignKey(Object2) # An object will be created after PayPal's call to the webhook endpoint class OrderPayment(models.Model): ... order = models.ForeignKey(Order) The problem is that I cannot call transaction.commit() after any object creation (Object1 or Object2) because I use atomic request and it leads to … -
Import ckeditor could not be resolved
I am trying to use RichTextFields through ckeditor in my django project. What I initially thought would be an easy task has caused me nightmares. I am able to pip install django-ckeditor easily. I have followed all the required steps as per https://pytutorial.com/django-ckeditor including adding to settings.py, adding MEDIA_ROOT etc etc. I have collected static and ran migrations and still nothing seems to be working. I get to the final step where I am importing in my models.py but I get a squiggly yellow underline that says "Import "ckeditor_uploader.fields" could not be resolved". settings.py file: INSTALLED_APPS = [ 'projects.apps.ProjectsConfig', 'users.apps.UsersConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', 'ckeditor_uploader', ] STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') CKEDITOR_UPLOAD_PATH = "uploads/" urls.py: from projects.views import projects from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include ('projects.urls')), path('users/', include ('users.urls')), path('ckeditor/', include('ckeditor_uploader.urls')), ] urlpatterns += static (settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py: from django.db import models import uuid from users.models import Profile from *ckeditor_uploader.fields* import RichTextUploadingField class Project (models.Model): owner = models.ForeignKey( Profile, null=True, blank=True, on_delete=models.SET_NULL) title = models.CharField(max_length=200) description = models.TextField(null=True,blank=True) … -
get_queryset in ListAPIView retuns blank list
In my app I have two types of users i.e. company and employees. I am trying to filter the queryset based on this like the following: class ProductListAPIView(generics.ListAPIView): serializer_class = ProductSerializer # pagination_class = StandardResultsSetPagination permission_classes = (permissions.IsAuthenticated, ) def get_queryset(self): if self.request.user.is_company == 'True': user_company = self.request.user.id emp = list(Employee.objects.filter(company=user_company).values_list('pk', flat=True)) emp.append(user_company) queryset = Product.objects.filter(owner__in=emp).order_by('-pk') return queryset elif self.request.user.is_employee == 'True': com = Company.objects.filter(pk=self.request.user.id).pk emp = list(Employee.objects.filter(company=com).values_list('pk', flat=True)) emp.append(com) queryset = Product.objects.filter(owner__in=emp).order_by('-pk') return queryset I tried the URL with both employee and company credentials but it always return an empty list but when I use the company code independently it works perfectly. -
How to call file-send API which use FileUploadParser
I am using file upload API with this document https://www.django-rest-framework.org/api-guide/parsers/#fileuploadparser I made the class in view.py class FileUploadView(APIView): parser_classes = [FileUploadParser] def put(self, request, filename, format=None): file_obj = request.data['file'] # ... # do some stuff with uploaded file # ... return Response(status=204) and then make url in urls.py urlpatterns += [ re_path(r'^upload/(?P<filename>[^/]+)$', FileUploadView.as_view()) ] Now I can access http://localhost:8008/upload/test.mp3 OK GET is not allowed , but there is not file upload form, how can I test this?? or is there any way to send post request with file by curl or something ?? -
What is best from creating API from mongoDb [closed]
So i have to create a Api from existing mongo Database where we send json request to it like {"dateFrom": "2021-10-01 00:00:00", "dateTo": "2021-10-15 23:59:59", "STATUS":"Pending","AMOUNT":"100"} and api should filter data from mongodb on base of request. and then respond with matching json data back sometime i have to send sum of all the AMOUNT and total results back too as json data. i was using django + pymongo. but i am having issue with speed. i am not sure that django + python + mymongo is right tools for it . i wanna know what else options do i have.i have make +50 api from more then hundred thousand entry's. someone told me express.js is also a good option. but i am confused. -
Error: redefinition of group name 'pk' as group 2; was group 1 at position 38
Using Django Rest Framework, I am creating endpoints for doctor model in my app app_api using ModelViewSet. I am encountering the following error on adding an extra action for updating the is_verified field with verify method having @action decorator. error at /app_api/viewset/doctor/6/ redefinition of group name 'pk' as group 2; was group 1 at position 38 Please find the code below. urls.py router = DefaultRouter() router.register('doctor', views.DoctorViewSet, basename='doctor') urlpatterns = [ path('viewset/', include(router.urls)), path('viewset/<int:pk>', include(router.urls)), ] model.py # Doctor Model class Doctor(models.Model): name = models.CharField(max_length=100) designation = models.CharField(max_length=100) description = models.TextField(blank=True, default='') is_verified = models.BooleanField(default=False, blank=True) serializer.py # Doctor Model Serializer class DoctorModelSerializer(serializers.ModelSerializer): class Meta: model = Doctor fields = '__all__' read_only_fields = ('is_verified',) # Doctor Partial Update Model Serializer class DoctorUpdateVerifyModelSerializer(serializers.ModelSerializer): class Meta: model = Doctor fields = ('id', 'name', 'is_verified') read_only_fields = ('name',) views.py class DoctorViewSet(viewsets.ModelViewSet): serializer_class = DoctorModelSerializer queryset = Doctor.objects.all() def get_serializer_class(self): serializer_class = self.serializer_class if self.request.method == 'PATCH' and self.action == 'verify': serializer_class = DoctorUpdateVerifyModelSerializer return serializer_class @action(methods=['patch'], detail=True) def verify(self, request, pk=None): serializer = self.get_serializer(self.get_object(), data=request.data, partial=True) serializer.is_valid(raise_exception=True) self.perform_update(serializer) return Response(serializer.data) Now when I am adding an extra action for routing the method verify with the @action decorator, I am getting the following error … -
Django ORM group by date and get total value
This is the model: class Transaction(models.Model): date = models.DateTimeField(auto_now_add=True) amount = models.DecimalField(max_digits=10, decimal_places=2) This is the query: end_date = timezone.now() start_date = end_date - timedelta(days=7) Transaction.objects.filter( date__range=[start_date, end_date], ) .values("date__date") .annotate(expenditure=Sum("amount")) .values("expenditure", date=F("date__date")) .order_by("date") This is the output: [ { "expenditure": 70.0, "date": "2021-10-28" }, { "expenditure": 20.0, "date": "2021-10-30" } ] But I want something like this as the output: [ { "expenditure": 0.0, "date": "2021-10-26" }, { "expenditure": 0.0, "date": "2021-10-27" } { "expenditure": 70.0, "date": "2021-10-28" }, { "expenditure": 0.0, "date": "2021-10-29" }, { "expenditure": 20.0, "date": "2021-10-30" }, { "expenditure": 0.0, "date": "2021-10-31" }, { "expenditure": 0.0, "date": "2021-11-01" }, ] I know I can process the data after the query but I wanted to know if it is possible to get this output using Django ORM? -
How to make uWSGI main thread not serve requests for the Django web application?
In my Django application, in the __init__.py, I have a class which spins up an event loop. class X: def __init__(self): self.__loop = asyncio.get_event_loop() async def foo(self): ... def do_stuff(self): # some logic here self.__loop.run_until_complete(foo()) In the __init__.py I just have x = X() In my Django views, I do from myapp import x def example_view(request): result = x.do_stuff() return JsonResponse({"result": result}) But the problem is that with uWSGI, if the thread that serves the request is same as that was used during initialization, I get the Django's SynchronousOnlyOperation exception as it detects a running event loop in that particular thread. So my question is, is there a way not to use that initializing thread for serving requests or some other alternative to fix this issue? uwSGI is configured to run multiple processes and multiple threads, with --enable-threads -
django registerForm.is_valid() Does not allow the rest of my code to work
My custom user uses the mobile number as username But when the user wants to get the verification code for his number again, he encounters an error I do not even know where this error came from because I did not write this error views def account_register(request): if request.user.is_authenticated: return redirect("store:home") registerForm = RegistrationForm(request.POST) if request.method == "POST": print(registerForm) if registerForm.is_valid(): registerForm.save(commit=False) username = registerForm.cleaned_data["user_name"] phone_number = registerForm.cleaned_data["phone_number"] password = registerForm.cleaned_data["password"] user = User.object.filter(phone_number=phone_number) if user.count() == 0: new_user = User(phone_number=phone_number) new_user.username = username new_user.phone_number = phone_number new_user.set_password(password) new_user.is_active = False new_user.save() otp_user = f"{new_user.otp}" print(otp_user) send_sms(otp_user, new_user.phone_number) elif not user.phone_number_verified: otp_user = f"{user.otp}" print(otp_user) send_sms(otp_user, user.phone_number) return render(request, "account/verificationpage.html", {"form": registerForm}) else: registerForm = RegistrationForm() return render(request, "account/authentication.html", {"form": registerForm}) forms class RegistrationForm(forms.ModelForm): user_name = forms.CharField( min_length=4, max_length=50, help_text='Required' ) phone_number = forms.CharField(max_length=11, help_text='Required', validators=[RegexValidator(regex=r'09(\d{9})$')], ) password = forms.CharField(widget=forms.PasswordInput) def clean_phone_number(self): phone_number = self.cleaned_data['phone_number'] if User.objects.filter(phone_number=phone_number, is_active=False).exists(): raise forms.ValidationError( 'Please use another phone number, that is already taken') return phone_number error User with this Phone number already exists