Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send email with cpanel in django
I'm trying to send email from a django app. Normally I use sendgrid but my client insists that there is no need for an extra service with Cpanel. Below are my settings after creating an email with cpanel according to this blog. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'mail.mydomain' EMAIL_PORT = 465 DEFAULT_FROM_EMAIL = 'email created as above' EMAIL_HOST_USER = 'email created as above' EMAIL_HOST_PASSWORD = 'the email's password' EMAIL_USE_TLS = True However, i get this error in development: gaierror at /contact-us/, [Errno -2] Name or service not known. Any suggestions are very welcome. -
Django on Google App Engine: how to connect to cloud database to run makemigrations?
I have been following this tutorial to create Django cloud app. I have been stuck on the 'Run the app on your local computer' part of the tutorial. Before running cloud_sql_proxy.exe command, I have created .env file and pasted its contents into Permissions on Google Cloud, so theoretically, after running set GOOGLE_CLOUD_PROJECT=PROJECT_ID, I could delete this .env file from repository as it would recognize it anyway. But for now, I left it. What is more, I activate env correctly in the project dir when I ran command in this location, gcloud sql instances describe INSTANCE_NAME it works OK and displays database info. Then, I have opened new Cloud SDK and ran command: cloud_sql_proxy.exe -instances="PROJECT_ID:REGION:INSTANCE_NAME"=tcp:5434. The result is: 2021/11/08 17:11:11 Listening on 127.0.0.1:5434 for PROJECT_ID:REGION:INSTANCE_NAME 2021/11/08 17:11:11 Ready for new connections 2021/11/08 17:11:11 Generated RSA key in 116.9931ms The reason behind why it is 5434 and not 5432 and 5433 as that these ports were busy. I must say that I have also downloaded postgresql and specified these: information. After running in env (Google SDK) respectively: set GOOGLE_CLOUD_PROJECT=PROJECT_ID set USE_CLOUD_SQL_AUTH_PROXY=true python manage.py makemigrations , this error occurs: C:\Users\User\Desktop\cloud\python-docs-samples\appengine\standard_python3\django\env\lib\site-packages\django\core\management\commands\makemigrations.py:105: RuntimeWarning: Got an error checking a consistent migration history performed for database connection … -
Django query, annotate a chain of related models
I have following schema with PostgreSQL. class Video(models.Model): title = models.CharField(max_length=255) created_at = models.DateTimeField() disabled = models.BooleanField(default=False) view_count = DecimalField(max_digits=10, decimal_places=0) class TopVideo(models.Model): videos = (Video, on_delete=models.CASCADE, primary_key=True) class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) video = models.ForeignKey(Video, related_name="comments", on_delete=models.CASCADE) The reason I have a TopVideo model is because I have millions of videos and querying them takes a long time on a cheap server, so I have a secondary model that is populated by a celery task, and flushes and re-populates on each run, which makes the homepage load time much faster. The task runs the query that you see next, and saves them into the TopVideo model. This way, the task may take long to run, but user doesn't have to wait for the expensive query anymore. Before having the TopVideo model, I ran this query for my homepage: videos = ( Video.objects.filter(created_at__range=[start, end]) .annotate(comment_count=Count("comments")) .exclude(disabled=True) .order_by("-view_count")[:100] ) This worked perfectly and I had access to "comment_count" in my template, where I could easily show the number of comments each video had. But now that I make this query: top_videos = ( TopVideo.objects.all().annotate(comment_count=Count("video__comments")) .select_related("video") .order_by("-video__view_count")[:100] ) and with a simple for-loop, videos = [] for video in top_videos: videos.append(video.video) … -
How to force a value when creating with django-rest-framework ModelViewSet?
I have an api where users can create different objects. If the user is part of the staff, he can create the object with all the values he wants. However, if the user is not part of the staff, I want to force the value of a particular field. I added the following code to a viewset that works well: @swagger_auto_schema(responses={201: CategoryProductSerializer}) def create(self, request, *args, **kwargs): if not self.request.user.is_staff: request.data['client']=request.user.profil.client.pk print(request.data) serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) def perform_create(self, serializer): serializer.save() How can I "generalize" this to all my modelviewsets? The important part of this create that must be common to all my viewsets is : if not self.request.user.is_staff: request.data['client']=request.user.profil.client.pk -
custom form error messages for too many images
I have a form that allows a user to upload bulk images. I Set a limit so the users can only upload a certain number of images. The code works but I use an exception, I want a custom error message in the template. From my research it seems that I need to use the clean method. However I cannot figure out how to use in in a function based view. How would I go about solving this issue. def createPostView(request): currentUser = request.user postForm = PostForm() if request.method == 'POST': postForm = PostForm(request.POST, request.FILES) if len(request.FILES.getlist('images')) > 3: raise Exception("Only three images allowed") else: if postForm.is_valid(): PostFormID = postForm.save(commit=False) PostFormID.author = request.user PostFormID.save() for f in request.FILES.getlist('images'): test = PostImagesForm(request.POST, request.FILES) if test.is_valid(): instance = test.save(commit=False) instance.post_id = PostFormID.id instance.images = f instance.save() return redirect('post-detail', PostFormID.pk) return render(request, 'blog/post_form.html', {'postForm': postForm, 'PostImagesForm':PostImagesForm}) -
Django Error: polls.Choice: (models.W042) Auto-created primary key
What should I do to fix this problem I am using vscode on Django 3.2 and I am currently following This project polls.Choice: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the PollsConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'. polls.Question: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the PollsConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'. -
How to update the one attribute of model once form is validated in Django?
I have a model class Tutor(models.Model): name = models.CharField(max_length=100) qualification = models.CharField(max_length=100) experience = models.CharField(max_length=200) tution_fee = models.CharField(max_length=100) about = models.CharField(max_length=1000) demo_classes_link = models.CharField(max_length=1000) contact_number = models.CharField(max_length=10) email_id = models.EmailField(null=True, blank=True) material = models.CharField(max_length=1000) status = models.BooleanField(null=True, blank=True) and a form class GeeksForm(forms.ModelForm): # specify the name of model to use class Meta: model = Tutor fields = "__all__" Now I have captured all the data using POST API form is validated. def registration(request) : form = GeeksForm(request.POST) # Check if the form is valid: if form.is_valid(): number = request.POST['contact_number'] print(number) r = requests.get('http://apilayer.net/api/validate?access_key=f29c72ac6f62b868e124651dc170a145&number=7042092067&country_code=+91&format=1', params=request.GET) if r.status_code == 200: form['status'] = 1 # I want to update this once is form is validated, django throws an error. form.save() return HttpResponse('Yay, it worked') currentID = form.auto_id print(currentID) # form = GeeksForm() else : print("Invalid") return render(request, 'Tutorform.html', {'form': form}) How do I update status parameter of model in django after form validation is successful ? -
Multiple Django variables in React
I am currently doing projct that includes Django and React. Post model in django models.py class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset()\ .filter(status='published') class Post(models.Model): STATUS = ( ('project', 'Project'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField( max_length=250, unique_for_date='publish') author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='messages') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=15, choices=STATUS, default='projekt') objects = models.Manager() published = PublishedManager() class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse("frontend.views.post_detail", kwargs={'year': self.publish.year, 'month': self.publish.month, 'day': self.publish.day, 'slug': self.publish.slug}) views.py def post_list(request): posts = Post.published.all() serializer = PostSerializer(posts, many=True) json_data = json.dumps(serializer.data) return render(request, 'frontend/index.html', {'posts': json_data}) def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) return render(request, 'frontend/index.html', {'post': post}) I want to get the 'posts' from post_list and 'post' from post_detail to index.html which is start point for React. index.html <!DOCTYPE html> <html lang="en"> <head> [..] <script> const posts = {{ posts|safe }}; const post = {{ post|safe }}; </script> <link rel="stylesheet" href="{% static "css/style.css" %}" type="text/css"> </head> <body> <div id="root"></div> <script src="{% static "frontend/main.js" %}"></script> </body> </html> The variables works perfectly fine when there's only one variable in script tag; … -
django rest framework return image url
I am trying to uplaod an image to the API and get the URL of the images back in response: Here is my views.py class ImageViewSet(viewsets.ModelViewSet): queryset = edited_image.objects.all() serializer_class = ImageSerializer @api_view(["POST"]) def manipulate_image(request): greenChannel, blueChannel= manip(request.data["picture"]) image = Image.objects.create(green=ContentFile(greenChannel.tobytes()), blue=ContentFile(blueChannel.tobytes()), ) return Response(data=image, status=status.HTTP_201_CREATED) TypeError: Object of type Image is not JSON serializable My model is: # Create your models here. class edited_image(models.Model): green= models.ImageField(upload_to="green_image", blank=True) blue= models.ImageField(upload_to="blue_image", blank=True) -
Django Graphene (GraphQL) Filter on ManyToMany
I am working on an application using Django. We've exposed the models using Graphene. We have the following models: class Agent(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) name = models.CharField( max_length=MAX_LENGTH, null=True, blank=True, help_text="Name of the agent" ) teams = models.ManyToManyField( 'Team', blank=True, help_text="The teams of which the user is part" ) class Team(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) name = models.CharField( max_length=MAX_LENGTH, help_text="Name of the team" ) Now I am trying to perform a filter on a ManyToMany field. But I can't seem to get it to work. I am trying to reproduce the following Django Query in GrapQL: teams = [ Team.objects.get(id="6d6d1d4d-c1b4-485a-9269-f7e9d06d862a"), Team.objects.get(id="7e082abf-584b-4858-b510-4c71fc295e2f"), ] agents = Agent.objects.filter(teams__in=teams).distinct() I tried to achieve this by enabling the 'in' filter on the node. class AgentNode(DjangoObjectType): class Meta: model = Agent filter_fields = { "teams": ["in"] } Then I tried to execute the following query, but that didn't work as expected: query getAllAgents{ allAgents(teams_In:["6d6d1d4d-c1b4-485a-9269-f7e9d06d862a, 7e082abf-584b-4858-b510-4c71fc295e2f"]) { id name teams { id name } } } This gives me the following error: { "errors": [ { "path": [ "allAgents" ], "message": "'list' object has no attribute 'split'", "locations": [ { "column": 3, "line": 2 } ] } ], "data": { "allAgents": null … -
Razorpay Django Integration with Callback URL (CSRF token missing or incorrect.)
I am trying to Class Based View with Razor Pay, Everything working Perfectly. But When i am POST data too same view it is giving error Forbidden (CSRF token missing or incorrect.): /buy-coin. I am having two question here How we can exempt CSRF Token for post method In Razorpay Javascript Code, can we add csrf token in callback url. Razorpay Python Integration Link - https://razorpay.com/docs/payment-gateway/server-integration/python/ View.py class BuyCoinPageView(LoginRequiredMixin, View): def get(self, request, *args, **kwargs): client = razorpay.Client(auth=("scretKey", "secretKey")) data = { "amount": 10000, "currency": "INR", "receipt": "order_rcptid_11" } payment = client.order.create(data=data) print('Razor Pay - ', payment['id']) return render(request, "pricing-page.html", {'payment': payment}) def post(self, request, *args, **kwargs): data = request.POST print(data) return render(request, "pricing-page.html") HTML FILE <a href="#" id="rzp-button1" class="btn-buy">Buy Now</a> <script src="https://checkout.razorpay.com/v1/checkout.js"></script> <script> var options = { "key": "rzp_test_hwAkAHZlKJdgee", // Enter the Key ID generated from the Dashboard "amount": "50000", // Amount is in currency subunits. Default currency is INR. Hence, 50000 refers to 50000 paise "currency": "INR", "name": "Acme Corp", "description": "Test Transaction", "image": "https://example.com/your_logo", "order_id": "{{payment.id}}", //This is a sample Order ID. Pass the `id` obtained in the response of Step 1 "callback_url": "{% url 'buy_coin' %}", "prefill": { "name": "Gaurav Kumar", "email": "gaurav.kumar@example.com", "contact": "9999999999" }, … -
DRF The serializer field might be named incorrectly and not match any attribute or key on the `str` instance
I am trying to make a multiple objects saving and i get the following error: AttributeError: Got AttributeError when attempting to get a value for field answer on serializer TestSerializer. The serializer field might be named incorrectly and not match any attribute or key on the str instance. I Checked the database , migrations are all correct. Below are my models , serializer and view. Model: class TestResponse(models.Model): id = models.AutoField(primary_key=True) answer = models.ForeignKey('Answer', on_delete=models.DO_NOTHING) View: @action(methods=['post'], detail=False) def create_multiple(self, request, *args, **kargs): serializer = self.get_serializer(data=request.data, many=True) serializer.is_valid(raise_exception=True) self.perform_create(serializer) return Response(serializer.data, status=status.HTTP_201_CREATED) Serializer: class TestResponseSerializer(serializers.ModelSerializer): class Meta: fields = ('id', 'answer') model = models.TestResponse Post body: [ { "answer": 1 }, { "answer": 2 } ] -
django.core.exceptions.ImproperlyConfigured: SQLite 3.9.0 or later is required (found 3.7.17) Error Observed in Apache Logs
I'm getting below error in apache error logs. ''' django.core.exceptions.ImproperlyConfigured: SQLite 3.9.0 or later is required (found 3.7.17) ''' I verified the sqlite3 version both in virtual environment and also in non virtual environment(standard). I can see the latest sqlite3 in both the python. ''' $ python3.7 Python 3.7.12 (default, Nov 8 2021, 09:02:58) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux Type "help", "copyright", "credits" or "license" for more information. from sqlite3 import dbapi2 as Database Database.sqlite_version_info (3, 36, 0) ''' Below is the error logs from apache web server. [Mon Nov 08 15:02:33.698244 2021] [wsgi:error] [pid 1459] [remote 192.168.0.105:62615] backend = load_backend(db['ENGINE']) [Mon Nov 08 15:02:33.698249 2021] [wsgi:error] [pid 1459] [remote 192.168.0.105:62615] File "/home/rafiq/myprojectenv/lib/python3.7/site-packages/django/db/utils.py", line 111, in load_backend [Mon Nov 08 15:02:33.698252 2021] [wsgi:error] [pid 1459] [remote 192.168.0.105:62615] return import_module('%s.base' % backend_name) [Mon Nov 08 15:02:33.698257 2021] [wsgi:error] [pid 1459] [remote 192.168.0.105:62615] File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module [Mon Nov 08 15:02:33.698260 2021] [wsgi:error] [pid 1459] [remote 192.168.0.105:62615] return _bootstrap._gcd_import(name[level:], package, level) [Mon Nov 08 15:02:33.698265 2021] [wsgi:error] [pid 1459] [remote 192.168.0.105:62615] File "/home/rafiq/myprojectenv/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 73, in <module> [Mon Nov 08 15:02:33.698267 2021] [wsgi:error] [pid 1459] [remote 192.168.0.105:62615] check_sqlite_version() [Mon Nov 08 15:02:33.698273 2021] [wsgi:error] [pid 1459] [remote … -
How to get multiple fetch functions execute in order?
I created an IG like button where the number of like changes after a click. I added 2 fetch functions - one with PUT. I tried multiple ways but the results are same - the GET fetch is getting executed first. How can I prevent that? function liking(tweetid) { let l = document.querySelector('#numlikes-' + tweetid); fetch(`tweets/${tweetid}`, { method: 'PUT', body: JSON.stringify({ tweet_like: 1 }) }); fetch(`tweets/${tweetid}`) .then(response => response.json()) .then(post => { l.innerHTML = post.likes; }); } -
How to override delete method (generics class) in Django Rest Framework? [duplicate]
I am trying to override delete method in generics.RetrieveUpdateDestroyAPIView class using the followings code snippet. :- In views.py class ArtistView(generics.RetrieveUpdateDestroyAPIView): serializer_class = ArtistSerializer queryset = Users.objects.filter(user_type='artist') In serializers.py class ArtistProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('profile_pic_url','cover_pic_url','full_name','genre','location') class ArtistSerializer(serializers.ModelSerializer): profiles = ArtistProfileSerializer(many=False) class Meta: model = Users fields = ['id','user_type', 'email', 'profiles','username'] def delete(self, instance, *arg, **kwargs): profile = instance.profiles profile.delete() In urls.py urlpatterns = [ path('all-artist/', views.ArtistListView.as_view()), path('all-artist/<int:pk>', views.ArtistView.as_view())] How can I do it? -
there is a way to use it managing the table Manytomany Filter_horizontal
I have the following model managing the intermediate table guia = models.ManyToManyField( Fisico, through= 'Planilla', blank = True, null = True ) I want to see it horizontally since admin.StackedInline it does not serve me for what I require -
Deploying django app to heroku - can't find new uploaded files
I build this site "https://bookzd.herokuapp.com" to download books but when i choose a book and try to downloaded it can't be downloaded, it says 404 not found. I did run Django app locally and it work fine. -
Django Deployment on Heroku Issue
Folks I've been steadily working through error codes trying to deploy a Django app on Heroku since yesterday. Design/front end is more my skillset, and I'm struggling to get my head around it. I've worked through a lot of questions and fixes here that have got me further, but there's still something breaking the deployment, even though it says it's built and deployed. What else should I include in this post to help solve this issue? Many thanks in advance! Sam 2021-11-08T14:16:21.000000+00:00 app[api]: Build succeeded 2021-11-08T14:16:23.704273+00:00 heroku[web.1]: Starting process with command `gunicorn Bax-Conversions.wsgi --log-file -` 2021-11-08T14:16:25.194030+00:00 app[web.1]: [2021-11-08 14:16:25 +0000] [4] [INFO] Starting gunicorn 20.1.0 2021-11-08T14:16:25.194734+00:00 app[web.1]: [2021-11-08 14:16:25 +0000] [4] [INFO] Listening at: http://0.0.0.0:15090 (4) 2021-11-08T14:16:25.204556+00:00 app[web.1]: [2021-11-08 14:16:25 +0000] [4] [INFO] Using worker: sync 2021-11-08T14:16:25.214346+00:00 app[web.1]: [2021-11-08 14:16:25 +0000] [9] [INFO] Booting worker with pid: 9 2021-11-08T14:16:25.222572+00:00 app[web.1]: [2021-11-08 14:16:25 +0000] [9] [ERROR] Exception in worker process 2021-11-08T14:16:25.222574+00:00 app[web.1]: Traceback (most recent call last): 2021-11-08T14:16:25.222588+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker 2021-11-08T14:16:25.222588+00:00 app[web.1]: worker.init_process() 2021-11-08T14:16:25.222588+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 134, in init_process 2021-11-08T14:16:25.222589+00:00 app[web.1]: self.load_wsgi() 2021-11-08T14:16:25.222589+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2021-11-08T14:16:25.222589+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2021-11-08T14:16:25.222590+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi 2021-11-08T14:16:25.222590+00:00 … -
How can I handle multiple requests at the same time in Django?
I'm currently writing an API in which a user could transfer money from their account to a phone but I'm facing an issue which is the user can call the API more than once at the same time and ask for transferring the money. Normally the balance of his account wouldn't be correct after the calls so I searched a lot and found out that I can use atomic transactions and lock the database. Now if the user uses the API for example twice, one of them runs correctly but the other one gets django.db.utils.OperationalError: database is locked error. Any idea how can I handle both of them correctly? (I could use a while and wait until the database gets unlocked but I rather don't do that) models.py @transaction.atomic() def withdraw(self, amount, phone, username): property = transferLog.objects.filter(username=username).order_by('-time').select_for_update()[0] if property.property >= int(amount): self.username = username self.property = property.property - int(amount) self._from = username self._to = phone self.amount = int(amount) self.time = str(datetime.datetime.now()) self.save() return {'result': 'success', 'message': 'transfer complete', 'remaining': self.property} else: return {'result': 'error', 'message': 'not enough money'} -
how to save csv data in list in django
Here soil_type should be in list format in database , here soil_type can be multiple Let us consider my views.py as class HorticultureItemsUpload(View): field_map = { 'PLANT_NAME': 'item_name', 'ALTERNATE_NAME': 'common_name', 'PLANT_CODE': 'plant_code', 'USER_TEXT_9': 'tree_type', 'USER_TEXT_8': 'categories', 'USER_TEXT_10': 'growth_rate', 'USER_TEXT_13': 'crown_shape', 'USER_TEXT_11': 'season_interest', # multiple 'USER_TEXT_20': 'ornamental_flower', 'USER_TEXT_12': 'height_at_maturity', 'USER_TEXT_14': 'soil_type', # multiple 'USER_TEXT_15': 'exclude_intolerant', # multiple # 'USER_TEXT_19': 'recommended_for', 'USER_TEXT_16': 'recommended_for', # Multiple 'USER_TEXT_17': 'summer_foliage_colour', 'FLOWER_COLOUR': 'flower_colour', 'PLANT_NOTES_TXT': 'description', 'PZ_CODES': 'pz_code', 'LABEL_TXT': 'label_text', } def get(self, request): self.currency_choices = [choice[0] for choice in CURRENCY_CHOICES] self.uom = [unit.name for unit in UnitOfMeasure.objects.all()] return render(request, 'jobs/upload_items_csv.django.html', { 'uom': self.uom, 'currency_choices': self.currency_choices }) def get_values_remapped(self, row): self.field_errors = {} remapped_dict = {self.field_map[key]: row[key] for key in self.field_map} return remapped_dict def post(self, request): client = request.user.client self.user = request.user self.client = client self.currency_choices = [choice[0] for choice in CURRENCY_CHOICES] self.uom = [unit.name for unit in UnitOfMeasure.objects.all()] data = { 'uom': self.uom, 'currency_choices': self.currency_choices } csv_file = request.FILES['items_csv'] reader = csv.DictReader(csv_file) error_rows = [] errors = [] count = 0 duplicates = 0 try: with transaction.atomic(): for line_number, row in enumerate(reader): try: remapped_row = self.get_values_remapped(row) if JobItems.objects.filter( item_name=remapped_row['item_name'], client=self.client, plant_code=remapped_row['plant_code']).exists(): duplicates += 1 continue except KeyError as e: messages.error(request, 'Column "%s" (case sensitive) was not … -
Django Rest-framework, JWT authentication
I'm newbie in Django Restframework. I use JWT to make login, register API, everythings worked well, I want to GET a user information with authenticated (tokens). This is my code for UserViewSet class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer authentication_classes = [IsAuthenticated,] I've tested on Postman but i received: "'IsAuthenticated' object has no attributes 'authenticate'" REST_FRAMEWORK = { 'NONE_FIELD_ERRORS_KEY':'error', 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } Could you please to help me to solve this promblem? Thank you very much. -
Django Error: RecursionError: maximum recursion depth exceeded
When I execute the python3 manage.py runserver command it gives me the error RecursionError: maximum recursion depth exceeded. I am currently using Django version 3.2 and using the Django project to learn in django https://docs.djangoproject.com/en/3.2/intro/tutorial01/ and I use pythonanywhere, but before the error it gives me this File "/usr/local/lib/python3.9/site-packages/django/urls/resolvers.py", line 413, in check messages.extend(check_resolver(pattern)) File "/usr/local/lib/python3.9/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/usr/local/lib/python3.9/site-packages/django/urls/resolvers.py", line 413, in check messages.extend(check_resolver(pattern)) File "/usr/local/lib/python3.9/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/usr/local/lib/python3.9/site-packages/django/urls/resolvers.py", line 413, in check messages.extend(check_resolver(pattern)) RecursionError: maximum recursion depth exceeded -
Django searching for a particular record
Im trying to search for a particular record, based on the ID i have input into the button on the UI: <button class="btn btn-sm btn-icon btn-icon-only btn-outline-primary" type="button" value={{ skill.id }} name='editbut'> I have checked and the ID reflects correctly In the view, I have the below. This works when I hardcode in the value, but when I try to extract it from the button value, it fails. Any help would be amazing!! Thanks def edit_skill(request): skillid = request.POST.get('editbut') t = skills.objects.get(id=skillid) t.status = 'closed' t.save() # this will update only messages.success(request, ('Changes saved')) return redirect('index') -
Get blank page when deployed django app using rest framework and react js (simpleJWT) on raspberry pi
i open my website, it shows a blank webpage and i checked the errors where it cannot load js files. i don't know how to correct my urls and it showed the following errors. i followed this tutorial https://levelup.gitconnected.com/full-stack-web-tutorial-django-react-js-jwt-auth-rest-bootstrap-pagination-b00ebf7866c1 i can run the webpage at localhost at raspberrypi. but having problem to deploy it. i give the info of urls.py. i also showed the settings.py content for staticfiles: i also showed the content for index.html: The "react_and_bootstrap.html" is at same directory where index.html located. i've run "python manage.py collectstatic" and the static folder is located at project directory as follows: Under "app" folder contains: Under "sales" folder contains: Under "static folder contains: This is my nginx configuration segment: i only showed the code involved with this project. i would like to setup a subnet called "my domain/sales/" but unsuccessful. The main problem is it can't load the static files where my urls setting got problem. and probably my nginx setting also got problem. Hope someone can guide me to solve this problem. Thanks. (if need more info, i can provide further). i deployed this django rest framework app using gunicorn, supervisor and nginx on raspberry pi. Thanks again. -
django horizontal stacked bar chart
I hope you're all doing great. I have been struggling to make a stacked horizontal bar chart here, I feel like I am not far off from the solution but I can't seem to find it. Bar Chart code: var ctx = document.getElementById("myBarChart"); total_value = parseInt(document.getElementById("total_value").textContent); var myBarChart = new Chart(ctx, { type: 'horizontalBar', indexAxis: 'y', data: { labels: [ {% for group in chart_group_data %} '{{group}}', {% endfor %}, ], datasets: [ {% for obj in timeperiod_list %} { label: "Value", stack: "Base", backgroundColor: [{% for obj in group_value %} '{{obj.timeperiod.color}}',{% endfor %}], hoverBackgroundColor: [{% for obj in group_value %} '{{obj.timeperiod.color}}',{% endfor %}], borderColor: [{% for obj in group_value %} '{{obj.timeperiod.color}}',{% endfor %}], data: [{% for obj in chart_percentage_data %} '{{obj|floatformat:"2"}}', {% endfor %}], }, {% endfor %}], }, options: { responsive:true, maintainAspectRatio:false, layout: { padding: { left: 10, right: 25, top: 25, bottom: 0 } }, legend: { display: false }, scales: { xAxes: [{ ticks: { autoSkip: false, beginAtZero: true } }], yAxes: [{ stacked:true, }] }, } }); views.py for i in group: group_value_data = GroupValue.objects.filter(group=i) group_value_first = group_value_data.first() group_value_last = group_value_data.last() chart_timeperiod = TimePeriod.objects.filter(competition=obj_id) for time in chart_timeperiod: try: week_group_value = group_value_data.get(timeperiod=time) chart_percentage_data.append(week_group_value.value) except: chart_percentage_data.append(0) …