Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is Django 4 async faster then sync queries
I'm trying to do an exercise to evaluate the value of upgrading to Django 4 and changing some of the queryset to async. To try and assess performance, I've created a couple of views to assess sync vs async and at present I can't see any performance improvement when communicating with the database. Firstly, I intentionally created two inefficient views where the db is supposed to be hit hard: Sync def some_validation(post): """Check that number of tags > 5""" return post.tags.count() > 5 @api_view(["GET"]) def posts_with_tags(request): start_time = time.monotonic() posts = [] for post in Post.objects.all(): tags = [] for tag in post.tags.all(): tags.append(tag.name) post_data = { "id": post.id, "title": post.title, "content": post.content, "tags": tags, "validation_passed": some_validation(post), } posts.append(post_data) end_time = time.monotonic() time_elapsed = end_time - start_time return Response( { "posts": posts, "time_elapsed": time_elapsed, "num_queries": len(connection.queries), } ) Async async def some_validation_async(post): """Check that number of tags > 5""" return await post.tags.acount() > 5 @api_view(["GET"]) async def posts_with_tags_async(request): start_time = time.monotonic() post_data = [] async for post in Post.objects.all(): post_tags = [] async for tag in post.tags.all(): post_tags.append(tag.name) validation_res = await some_validation_async(post) post_data.append( { "id": post.id, "title": post.title, "content": post.content, "tags": post_tags, "validation_passed": validation_res, } ) end_time = time.monotonic() time_elapsed … -
neomdel nodes not deleting through APIs on hosted system
we have signals for create and delete of neomodel node instances based on creation and deletion of mysql instance. when hosted system, when calling functions through shell or custom management commands its working perfectly fine and signals are called and nodes are created but when called our API endpoints. it returns the following error Cannot resolve address 09f3562c.databases.neo4j.io:7687 code for signals @receiver(post_save,sender=settings.AUTH_USER_MODEL) def create_personNode(sender,instance=None,created=None,**kwargs): if created: if not instance.is_internal: personNode = Person(did=instance.id,uid=instance.uid) # personNode.created_at = instance.created_at personNode.save() if instance.email: personNode.email = instance.email personNode.save() if instance.phone: personNode.phone = instance.phone personNode.save() else: pass else: if not instance.is_internal: personNode = Person.nodes.get(did=instance.id) if instance.email: personNode.email = instance.email personNode.save() if instance.phone: personNode.phone = instance.phone personNode.save() @receiver(post_delete,sender=Users) def deletePersonNode(sender,instance=None,**kwargs): if instance is not None: #and (not instance.is_superuser) and (not instance.is_staff): try: personNode = Person.nodes.get(did=instance.id) except: personNode = None if personNode is not None: personNode.total_delete() I am using latest versions of neomodel and neo4j neo4j 5.8.0 neobolt 1.7.17 neomodel 5.0.0 Django 4.0.2 djangorestframework 3.13.1 -
How to leave the 1st inline object when trying to delete all inline objects on "Change" page in Django Admin?
I have Person model and Email model which has the foreign key of Person model as shown below: # "models.py" class Person(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Email(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) email = models.EmailField() def __str__(self): return self.email And, I have Person admin which has Email inline as shown below: # "admin.py" class EmailInline(admin.TabularInline): model = Email @admin.register(Person) class PersonAdmin(admin.ModelAdmin): inlines = (EmailInline,) And, there are 3 inline objects on Change page as shown below: Now, I want to leave the 1st inline object when trying to delete all inline objects as shown below. *By default, all inline objects are deleted if trying to delete all inline objects: So, how can I leave the 1st inline object when trying to delete all inline objects on Change page in Django Admin? -
Elastic DSL DRF create a document and include a queryset so not all records from the model are indexed
I have certain records in my table which I do not want to appear in my elasticsearch index at all. Is this possible to do inside the Document? I have tried overriding get_queryset (see below) but that isn't working. Does anyone know what the best approach is here? @registry.register_document class MyDocument(Document): parent_id = fields.IntegerField() title = fields.KeywordField() class Django: # Models to include in the document model = MyModel # Fields to index for each model fields = [ "id", ... ] def get_queryset(self): # Ensure we exclude certain records from being pushed to Elastic return super(MyDocument, self).get_queryset().exclude(exclude_me=True) class Index: # Define Elasticsearch index name = ( f'{os.environ.get("CS_DEPLOYMENT", "development")}_my_document' ) # Set default settings settings = {"number_of_shards": 1, "number_of_replicas": 0} -
Django: Get childset of childset from parent
I'm trying get all the comments and replies count received by a post, I've only one model for Post, Comment and Reply. How to get the child set of a child set from a parent set in Python? I have a parent set that contains some child sets as its elements. My code is: from django.db import models from django.contrib.auth.models import User from tld import get_fld from django.db.models import Q from django.utils import timezone class QuestionManager(models.Manager): def get_questions(self): stories = self.filter(story_type='story') stories = self.filter(Q(title__endswith='?')) return stories class JobsManager(models.Manager): def get_jobs(self): stories = self.filter(story_type='story') stories = self.filter(Q(title__icontains='hiring') | Q(title__icontains='hire')) return stories class NewestManager(models.Manager): def get_newest(self): stories = self.filter(story_type='story', created_at__day=str(timezone.now().day)) return stories class Story(models.Model): STORY_TYPE = ( ('story', 'Story'), ('comment', 'Comment'), ('reply', 'Reply') ) parent = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(max_length=255, null=True, blank=True) body = models.TextField() url = models.URLField(null=True, blank=True) story_type = models.CharField(choices=STORY_TYPE, default='story', max_length=10) created_by = models.ForeignKey(User, related_name='story', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) ask = QuestionManager() jobs = JobsManager() new = NewestManager() objects = models.Manager() class Meta: verbose_name_plural = 'stories' def __str__(self): return f'{self.title} - {self.created_by.username}' def get_tld(self): return get_fld(self.url) def get_total_comments_count(self): pass def get_root(self): root = self while root.parent is not None: root = root.parent return root I'm unsure … -
Django template not including a static css file?
I have a simple django app and I'm trying to load a static css file, but it doesn't appear to be working. I can navigate to the css file in my browser. Here's the beginning of my template file: {% extends '_base.html' %} {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'datasets/css/styles.css' %}"> {% block content %} <div class="container"> <div class="row"> <div class="col-md-12"> <h1 class="mb-4">Datasets</h1> <table class="table"> <thead> <tr> <th>Title</th> <th>Description</th> </tr> </thead> <tbody> {% for dataset in datasets %} <tr> <td> And here is my settings.py: """ from pathlib import Path from environs import Env env = Env() env.read_env() # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "whitenoise.runserver_nostatic", # new "django.contrib.staticfiles", "django.contrib.sites", # Third-party "crispy_forms", "crispy_bootstrap5", "allauth", "allauth.account", "debug_toolbar", # Local "accounts.apps.AccountsConfig", "pages.apps.PagesConfig", "books.apps.BooksConfig", 'datasets' ] MIDDLEWARE = [ "django.middleware.cache.UpdateCacheMiddleware", "django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", # new "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "debug_toolbar.middleware.DebugToolbarMiddleware", "django.middleware.cache.FetchFromCacheMiddleware", ] ROOT_URLCONF = "django_project.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [BASE_DIR / "templates"], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, }, ] WSGI_APPLICATION = "django_project.wsgi.application" # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { "default": env.dj_db_url("DATABASE_URL", default="postgres://postgres:postgres@db/postgres") } # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_URL = "/static/" … -
How to set timeout a django function to specific time intervel?
Actually i want to find out where is my code is laging their for i tried many ways to solve it. i used to signals but buildin in SIGMA error. i need to use like decorator model timeout function .i can use anywhere. -
In wagtail, how to include a ForeignKey for a snippet with a panel that lets you add/create new items?
Having a snippet "Scientist" and another snippet "Country". When editing Scientist, it shows a dropdown with all the countries. I'm trying to find a way to also show an "Add new" so the editor can add a new country directly from the Scientist's change form. Currently, they should first go to the Country snippet panel, add a new one, and then go back to the Scientist and create the new one. Here's a simplification of the code: class Country(models.Model): name = models.CharField( _("name"), max_length=25, ) panels = [ FieldPanel("name"), ] class Scientist(DraftStateMixin, RevisionMixin, ClusterableModel): name = models.CharField(_("name"), max_length=25) country = models.ForeignKey( Country, on_delete=models.PROTECT, ) panels = [ FieldPanel("name"), FieldPanel("country"), ] Scientist is extending ClusterableModel because in the real code there's another field that's a ParentalManyToManyField. Using Wagtail 5.0. Thanks a lot! -
How to list all files associated by the employee?
need help on how to render to django html template the list of files associated in the employee model please help me with my problem., thanks here is my Document model: class Document(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE) filename = models.CharField(max_length=250, blank=True) file = models.FileField(upload_to=employee_file_path) uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.employee.fullname this is my views.py def employee_documents(request, pk): employee = get_object_or_404(Employee, pk=pk) documents = employee.document_set.all() context = {'employee': employee, 'documents': documents} return render(request, 'hris/document/employee_documents.html', context) this is my html template <div class="card mb-4"> <div class="card-body"> <h5 class="my-3 text-center">Uploaded Files</h5> {% if documents %} {% for docs in documents %} <div class="row"> <div class="col-sm-3"> <p class="mb-0">{{ docs.filename }}</p> </div> <div class="col-sm-9"> <p class="text-muted mb-0">{{ docs.file.url }}</p> </div> </div> {% empty %} <p>No Uploaded Documents</p> {% endfor %} {% endif %} <div class="d-flex justify-content-center mb-2"> <a href="{% url 'document-upload' slug=employee.slug pk=employee.pk %}" class="btn btn-md btn-outline-primary ms-1">Upload File</a> </div> </div> this is the image i want to replicate goal output I already tried using the generic Class Based Views, but it didn't render in the html page. I already tried the same method of rendering the image file but it failed. -
catch fail cases during bulk_update Django
I have an input file of 10k entries & I divide it into smaller chunks. for each chunk I want to perform a bulk_update operation in Django. However, I also want to log if there is any failed update case, due to any reason, and let the update continue. How can I achieve that? Also, does django stop the bulk update query upon encountering an error in the input chunk or does it ignore & continue? -
Getting Scopes of user without logging in
I am new to django rest framework and oauth I am trying to get user scopes with the user id without actually logging in as that user in django. Is there any way to acheive that. I am using o-auth for the authentication and authorization. I am having a Scope model, which has group field with ForeignKey relationship class Scope(models.Model): name = models.Charfield(max_length=64) applications = models.ManytoManyField(oauth2_settings.APPLICATION_MODEL) group = models.ManytoManyField(Group) Ideal way to solve my problem def function(self, request): ... user = User.object.get(id=id) scopes = some_magic_function(user) ... I have looked so many answers, almost all involved token or authentication as that particular user. Is there any way to acheive this, or to create a token without logging in. -
Limit a specific task in Celery
I have a Django function my_func() that parallelizes it's execution in threads. The function is launched it a scheduled job. In the server, the threads are executed in Celery. The server celery configuration file, conf, is set tu use 8 nodes * 8 threads each. CELERYD_NODES=4 CELERYD_OPTS="--concurrency=8" I want to restrict the function my_func to use 1 node and 4 threads maximum. For that, I added this lines to the file. [task:ad.tasks.my_func] --concurrency=1 --max-threads=4 But it doesn't work. The function still launches all the workers and threads available (32 parallel processes). How must I configure it? -
can anbody write the same logic using update_or_create method in Django and Django Rest Framework
This is the code I want to write it using update_or_create logic and want to remove transaction.atomic and select for update. remember async_handle_invoice_payment_failed and async_handle_invoice_payment_action_required will be triggered multiple times but for these specific values i want the values of failed_payment.first_payment_action_required_triggered_at and failed_payment.first_Payment_failure_triggered_at only when they are first created or the logic used in the code. This is my model class FailedPaymentLog(TimeStampedModel): account = models.ForeignKey(Account, on_delete=models.CASCADE) invoice_id = models.CharField(max_length=255) retry_count = models.PositiveIntegerField(default=0) last_retry_time = models.DateTimeField(null=True, blank=True) first_Payment_failure_triggered_at = models.DateTimeField(null=True, blank=True) #this is the time when the payment of invoice failed for the first time first_payment_action_required_triggered_at = models.DateTimeField(null=True, blank=True) class Meta: indexes = [ models.Index(fields=['account', 'invoice_id'], name='account_invoice_idx'), ] this is the code i want to change-: @transaction.atomic() def update_failed_payment_log(event, action_required=False): invoice = event['data']['object'] stripe_customer_id = invoice['customer'] account_billing = AccountBilling.objects.get(stripe_customer_id=stripe_customer_id) account = account_billing.account invoice_id = invoice['id'] try: subscription = Subscription.objects.filter(payment_identifier=event['data']['object']['subscription']).first() subscription.payment_status = db_choices.BillingPaymentStatusChoices.declined subscription.save() except Subscription.DoesNotExist: return failed_payment, created = FailedPaymentLog.objects.select_for_update().get_or_create(account=account, invoice_id=invoice_id) failed_payment.retry_count = invoice['attempt_count'] failed_payment.last_retry_time = timezone.make_aware(timezone.datetime.fromtimestamp(event['created'])) if created: if action_required: failed_payment.first_payment_action_required_triggered_at = timezone.make_aware(timezone.datetime.fromtimestamp(event['created'])) else: failed_payment.first_Payment_failure_triggered_at = timezone.make_aware(timezone.datetime.fromtimestamp(event['created'])) else: if action_required and not failed_payment.first_payment_action_required_triggered_at: failed_payment.first_payment_action_required_triggered_at = timezone.make_aware(timezone.datetime.fromtimestamp(event['created'])) elif not action_required and not failed_payment.first_Payment_failure_triggered_at : failed_payment.first_Payment_failure_triggered_at = timezone.make_aware(timezone.datetime.fromtimestamp(event['created'])) failed_payment.save() @shared_task def async_handle_invoice_payment_failed(event): update_failed_payment_log(event) @shared_task def async_handle_invoice_payment_action_required(event): update_failed_payment_log(event, action_required=True) I am expecting you … -
How to replace @action decorator when changing from ViewSet to ListApiView?
I have to rewrite certain view that is ReadOnlyModelViewSet ("GroupViewSet") to ListApiView. The ReadOnlyModelViewSet has two methods with @action decorators. Since @action decorators do not work within ListApiView views, what is the best way to achive the same rerouting functionality within ListApiView? ReadOnlyViewSet view: class GroupViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = GroupSerializer queryset = Group.objects.all() filterset_class = GroupFilter permission_classes = (permissions.AllowAny,) @action(detail=False, methods=['get']) def specs(self, request): queryset = self.filter_queryset(self.get_queryset()) specs_id = queryset.values_list('spec_id', flat=True) specs = DictSpec.objects.filter(id__in=specs_id) serializer = DictSpecSerializer(specs, many=True) return Response(serializer.data) @action(detail=False, methods=['get']) def subspecs(self, request): queryset = self.filter_queryset(self.get_queryset()) subspecs_id = queryset.values_list('subspecs__id', flat=True) subspecs = DictSubSpec.objects.filter(id__in=subspecs_id) serializer = DictSubSpecSerializer(subspecs, many=True) return Response(serializer.data) -
How to change file name in Django pre_save?
Is there a way to change the file name before saving it in Django? class Foo(models.Model): name = models.CharField(max_length=50, blank=True) file = models.FileField( upload_to='foo', null=True, max_length=500) At signals, I can intercept the instance during pre_save: @receiver(pre_save, sender=Foo) def change_file_name(sender, instance, **kwargs): file_name = "TEST_" + instance.name + ".pdf" # save name as file name for the file field in Foo I am hosting the app in the cloud so would be nice not to use saving to local machine file solutions. -
i don't get data and show in React admin
Please help us find a solution to this problem. We want to get some data from the database and show it in the list section in the React admin. But we face problems in giving the address of the database and resources.[enter imagenter image description heree description here](https://i.stack.imgur.com/i1Zc9.jpg) please solve this problem -
how to give both and ,or condition in django ORM
I have one sql query as select * from sample_table where (istatus = 1 AND ((iCategory = 2 and iType=1) or (iType in (2,3,5))); how can i write the same in Django ORM using filter? -
Deploying Django App to Azure Storage Error
I've been following this tutorial on deploying my django app on Azure: https://testdriven.io/blog/django-azure-app-service/ Everything was working fine until I added Azure storage. Now my webpage is giving me an error saying Could not find backend 'core.azure_storage.AzureStaticStorage': No module named 'core' When seeing something like this I instantly thought to check my requirements.txt, they are updated with the required installs (django-storages, azure-core, and azure-storage-blob). At a loss with where to even start here. Re checked the tutorial and all my settings are properly set. -
Django filter and annotate confusion
I have two models model A: cid = ... rating = ... model B: id = ... (this id is same as cid in model A. But no foreign key directly) name = .... now I need the list of all modelB objects whose rating is greater than 3. I also need the rating field to be available in the result queryset. I have done the following, good_rating_A_queryset = A.filter(rating__gt=3) good_rating_B_queryset = B.filter( id__in = good_rating_A_queryset.values("cid") ) Now I have all B objects whose ratings are greater than 3. Now I want to retain the rating field from good_rating_A_queryset in good_rating_B_queryset so that I can serialize it and send to front-end. I am using DRF to serialize. I want to access the rating like good_rating_B_queryset.first().rating I thought I could use annotate but can't figure out how to map the field pls help -
DRF how to set my model_object_value as key for my object
I need the serializer where i can take my file versions with path_to_file like 1:path_to_file, 2: path_to_file, .... : .........., n_verison: path_to_file }``` models.py class Report(models.Model): employee = models.ForeignKey(Worker, on_delete=models.SET_NULL, null=True) file_name = models.CharField(max_length=20, null=True) datetime = models.DateTimeField(auto_created=True) class ReportVersionInfo(models.Model): report = models.ForeignKey(Report, on_delete=models.CASCADE) version = models.IntegerField() file = models.FileField() def save(self, *args, **kwargs): # This means that the model isn't saved to the database yet if self._state.adding: # Get the maximum display_id value from the database last_id = self.objects.all().aggregate(largest=models.Max('version'))['largest'] # aggregate can return None! Check it first. # If it isn't none, just use the last ID specified (which should be the greatest) and add one to it if last_id is not None: self.version = last_id + 1 serializer.py from rest_framework import serializers from django.utils import timezone from worker.models import Worker from report import models class FileVersionSerializer(serializers.ModelSerializer): class Meta: model = models.ReportVersionInfo fields = ['version', 'file'] read_only_fields = ['version'] class ReportsSerializers(serializers.ModelSerializer): report_file = serializers.SerializerMethodField() class Meta: model = models.Report fields = ['employee','file_name', 'report_file',] views.py class ReportsViewSet(viewsets.ModelViewSet): queryset = models.Report.objects.all() serializer_class = serializers.ReportsSerializers -
Compiling "en_US" gets "ValueError: invalid token in plural form: EXPRESSION" in Django
In settings.py, by default, en-us is set to LANGUAGE_CODE so I also set en-us to LANGUAGES as shown below, then there is no error. *I'm learning Translation with Django 4.2.1: # "settings.py" MIDDLEWARE = [ # ... 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', # ... ] # ... LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True LOCALE_PATHS = [ BASE_DIR / 'locale', ] from django.utils.translation import gettext_lazy as _ LANGUAGES = ( ('en-us', _('English')), # Here ) Then, I ran makemessages below to create django.po in locale/en_US/LC_MESSAGES/: django-admin makemessages -l en_US But, after I ran compilemessages below to create django.mo in locale/en_US/LC_MESSAGES/: django-admin compilemessages I got the error below even though I could create django.po and django.mo in locale/en_US/LC_MESSAGES/: ValueError: invalid token in plural form: EXPRESSION So following the answer, in django.po, I replaced the code below: "Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\n" With the code below: "Plural-Forms: nplurals=2; plural=(n != 1);\n" Then, I ran compilemessages below again: django-admin compilemessages But, I still got the error below: ValueError: invalid token in plural form: EXPRESSION Next, I removed en_US folder which has django.po and django.mo from both locale/ folder and django/conf/locale/ folder but I still got the error below: ValueError: invalid token in … -
How to get fields name from Django QuerySet, even when it's an empty set?
A cool binding between Django and Pandas is the ability to construct a DataFrame directly from a QuerySet using: queryset = models.A.objects.filter(...).annotate(...) frame = pd.DataFrame(queryset.values()) Which wonderfully works as long as there is at least one record returned by the QuerySet. Acting at the QuerySet level is interesting because there we can have the benefit of all annotations as well as native columns. But this method will return a totally empty DataFrame (without columns defined), let's say from something like: queryset = models.A.objects.filter(id__lt=0).annotate(...) frame = pd.DataFrame(queryset.values()) The DataFrame is totally empty: Empty DataFrame Columns: [] Index: [] While we want something like instead: Empty DataFrame Columns: ["id", "key", "prop1", ...] Index: [] Where columns names are preserved in order to get this frame able to merge with another frames seamlessly. The pandas way to do this is to force columns names at the DataFrame creation using the columns switch. queryset = models.A.objects.filter(...) frame = pd.DataFrame(queryset.values(), columns=queryset.get_fields()) Unfortunately it seems that this get_fields or similar is not implemented or obvious at the first glance for the QuerySet object. I already know that I can fetch column names from a QuerySet that exists() using this dirty one: frame = pd.DataFrame( queryset.values(), columns=queryset[0].__dict__.keys() … -
Django and elasticsearch, search results are not highlighted
I have implemented the blog using, django and elasticsearch, it works correctly as I expect, but I want the search results that match to be highlighted with bold and the below is my implementation but does not seem to work, I need help. def search(request): query = request.GET.get('query') posts = [] if query: q = Q('multi_match', query=query, fields=['title', 'body'], fuzziness='auto') search = Search().query(q) search = search.highlight('title', 'body') search = search.highlight_options(pre_tags='<b>', post_tags='</b>') hits = search.execute() for hit in hits: postId = hit.meta.id postById = Post.published.get(id=postId) highlight = hit.meta.highlight.to_dict().get(postId, {}).get('title', '') highlightBody = hit.meta.highlight.to_dict().get(postId, {}).get('body', '') post = { 'title': hit.title, 'body': hit.body, 'link': postById.get_absolute_url(), 'highlight': highlight, 'highlightBody': highlightBody, } posts.append(post) return render(request, 'search/search.html', {'posts': posts, 'query':query}) and in my template I accessed the variable like:-{{post.highlightBody|default:post.body}} -
Djnago Rest-Framework JWT Authentication
This is register api I am using for the token creation on jwt class RegisterView(APIView): def post(self, request): serializer = RegisterSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() print(user) refresh = RefreshToken.for_user(user) return Response( { 'status':200, 'message':'Phone Number Registered Successfully', 'refresh':str(refresh), 'access': str(refresh.access_token) } ) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Then I want to update that record through this api but while using IsAuthenticated it is giving me user_not_found. @api_view(['PUT']) @permission_classes([IsAuthenticated]) def set_mpin(request): phone_number = request.data.get('phone_number') print(phone_number) if not phone_number: return Response({'status': 400, 'message':'phone number required'}) try: registered_phone = Register.objects.get(phone_number=phone_number) print(registered_phone) except Register.DoesNotExist: return Response({'status': 400, 'message':'invalid phone number'}) serializer = SetMpinSerializer(registered_phone, data=request.data) print(serializer) if serializer.is_valid(): serializer.save() return Response({'status':200, 'message':'MPIN Successfully Created'}) else: return Response({'status':400, 'message':'Invalid'}) Anyone can solve this problem? I want to update that record. -
I always face this problem Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['post/(?P<post_id>[0-9]+)/\\Z']
I am Malek I am working on a blog using django but I am facing this problem with the url and pk Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['post/(?P<post_id>[0-9]+)/\Z'] I hope someone can help me solve this problem enter image description here here are my django codes for each file views.py from django.shortcuts import render, get_object_or_404 from .models import AboutUs, Name, Skills, Portfolio, Navlink, Contact, Blog from django.http import HttpResponse # Create your views here. def index(request): if request.method == "POST": contact = Contact() user_name = request.POST.get('name') email = request.POST.get('email') subject = request.POST.get('subject') contact.name = user_name contact.email = email contact.message = subject contact.save() return render(request, 'sent.html', context={'link': Navlink.objects.first()}) return render(request, 'index.html', context= { 'about_us': AboutUs.objects.first(), 'name': Name.objects.first(), 'skills': Skills.objects.all(), 'image' : Portfolio.objects.all(), 'link': Navlink.objects.all(), 'blog': Blog.objects.all(), }) def post_details(request, id): post = get_object_or_404(Blog, pk= id) details = { 'post_id' : post, 'title' : 'title', } return render(request, 'post.html', details) def home(request): return render(request, 'index.html') def posts(request): return render(request, 'posts.html', context={'posts': Blog.objects.all()}) """def post(request): return render(request, 'product.html')""" urls.py from django.urls import path from . import views urlpatterns = [ #path('', views.home, name='home'), path('', views.index, name='home'), path('', views.home, name='home'), path('post/<int:post_id>/', views.post_details, name='detail'), path('posts/', views.posts, name='posts'), ] models.py …