Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Async functions in Django
I'm trying to use django admin for administrate my Telegram bot. I have an async function called mailing, how can i start this function in django admin actions? I can make it sync but i don't know how make a pause to my bot will be no banned when it send many massages, and continue to answer users. This is my first question on Stackowerflow. Sorry for my english. admins.py @admin.action(description='mailing') def mailing(modeladmin, request, queryset): pass @admin.register(Publish) class PublishAdmin(admin.ModelAdmin): list_display = ('name', 'created_at') actions = [mailing] async def mailing_start(text, url, user_id=None): users = db.select_user_list() count = 0 receivers_count = 0 markup = '' if url: pass #markup = await create_link_button(url) for user in users: try: if user_id != user[0]: if url: await bot.send_message(user[0], text, reply_markup=markup) else: await bot.send_message(user[0], text) count += 1 if count == 18: await asyncio.sleep(3) count = 0 receivers_count += 1 except Exception as err: print(f'id - {user[0]}, bot is stopped \n{err}') receivers_count -= 1 return f'{emoji.emojize(":white_check_mark:", use_aliases=True)}, ' \ f'message recieved {receivers_count}' -
How to restrict an user from saving an instance of a model if he/she has not created an instance of a previous model?
I have five key models: class Patient(models.Model): title=models.ForeignKey(Title, on_delete=CASCADE) name=models.CharField(max_length=100) gender=models.ForeignKey(Gender, on_delete=CASCADE) center=models.ForeignKey(Center, on_delete=CASCADE) mr_uid=models.CharField(max_length=9) class Package(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) diagnosis=models.ForeignKey(Diagnosis, on_delete=CASCADE) treatment=models.ForeignKey(Treatment, on_delete=CASCADE) patient_type=models.ForeignKey(PatientType, on_delete=CASCADE) date_of_admission=models.DateField(default=None) max_fractions=models.IntegerField(default=None) total_package=models.DecimalField(max_digits=10, decimal_places=2) class Receivables(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) pattern = RegexValidator(r'(RT|rt|rT|Rt)\/[0-9]{4}\/[0-9]{2}\/[0-9]{4}', 'Enter RT Number properly!') rt_number=models.CharField(max_length=15, validators=[pattern]) discount=models.DecimalField(max_digits=9, decimal_places=2, default=0) approved_package=models.DecimalField(max_digits=10, decimal_places=2, default=0) approval_date=models.DateField(default=None) proposed_fractions=models.IntegerField() done_fractions=models.IntegerField() base_value=models.DecimalField(max_digits=10, decimal_places=2, blank=True) expected_value=models.DecimalField(max_digits=10, decimal_places=2, blank=True) class Discharge(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) date_of_discharge=models.DateField(default=None) mould_charges=models.DecimalField(max_digits=7, decimal_places=2, default=0, blank=True) ct_charges=models.DecimalField(max_digits=7, decimal_places=2, default=0, blank=True) discharge_updated=models.BooleanField(default=False) class Realization(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) cash=models.BooleanField(default=False) amount_received=models.DecimalField(max_digits=10, decimal_places=2, default=0) billing_month=models.DateField(default=None) deficit_or_surplus_amount=models.DecimalField(max_digits=8, decimal_places=2, blank=True) deficit_percentage=models.FloatField(blank=True, default=0) surplus_percentage=models.FloatField(blank=True, default=0) remarks=models.TextField(max_length=500, default="N/A") A basic summary: A patient consults a doctor. Immediately his treatment package is decided. If the patient has any Government scheme's support, the package goes for approval to the Government agency. Upon the arrival of the approval, the receivables are calculated. The patient then takes the treatment and gets discharged. We then receive the amount. The problem: At the beginning, the patient's profile is created. The rest of the tables will be created as and when the events occur. What I want is, for example, when the data-entry operator fills up the Receivables form and saves it, the Package instance must already be there for the same patient, likewise, when he/she … -
Twitter API "Token request failed with code 401, response was '{\"errors\":[{\"code\":89,\"message\":\"Invalid or expired token.\"}]}'."
Iam working with twitter API and stuck with an error can some one help me with that. I have to pass temporary URL to frontend which help the user to authenticate with our Application. I know its a one time URL. If we hit that temporary URL endpoint for the 1st time, user can authenticate(works fine). But for the next time, its showing error as "Token request failed with code 401". Is there any way to continuously regenerate..enter image description here enter image description here -
Django REST Framework: How to pass a prefetched queryset to the serializer when the View must use a library-provided queryset
I would like to use drf-haystack to use a queryset prefetched by serializer as shown below. I need to use a haystack-specific queryset (annotate and prefetch_related are not available) for this view, and I can't pass the prefetched queryset to the SerializerMethodField. I've spent quite a bit of time on this issue. Is there a better way to do this? # views.py class PostSearchView(ListModelMixin, HaystackGenericAPIView): index_models = [Post] serializer_class = PostSearchSerializer def filter_queryset(self, *args, **kwargs): #This queryset is haystack's own queryset, so it cannot be annotate or prefetch_related. queryset = super(PostSearchView, self).filter_queryset(self.get_queryset()) return queryset.filter(published_at__lte=timezone.now()) def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) # serializers.py class PostSearchSerializer(BaseHaystackSerializer): is_views = serializers.SerializerMethodField() class Meta: index_classes = [PostIndex] search_fields = ("text",) fields = ("is_views",) def get_is_views(self, obj): try: History.objects.get(post_id=obj.pk) return True except History.DoesNotExist: return False return obj.is_views # I wanted to do it this way. -
How to get all files from a specific folder and store them in DB, django
class Documents(models.Model): file = models.FileField() I have got a folder called media in the root. It contains multiple files (pdf's). Can I automatically store them in the table called Documents. Thank you so much! -
Why Django copies all images, which I use for creating of the model instances
I have a model 'Book'. It has a field 'image'. Whenever I add a new instance on the admin panel, Django copies this image in a 'media' folder. Why does it do it? Can I turn off this function? -
OperationalError at / no such table: fruits_fruits
OperationalError at / no such table: fruits_fruits Request Method: GET Request URL: http://104.198.201.84/ Django Version: 3.2.8 Exception Type: OperationalError Exception Value: no such table: fruits_fruits Exception Location: /usr/local/lib/python3.7/dist-packages/django/db/backends/sqlite3/base.py, line 423, in execute Python Executable: /usr/bin/python3 Python Version: 3.7.3 Python Path: ['/var/www/projects/fruitstore', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Sat, 30 Oct 2021 08:49:33 +0000 Error during template rendering In template /var/www/projects/fruitstore/fruits/templates/fruits.html, error at line 47 no such table: fruits_fruits -
how do i upload video in django to heroku
please can someone tell me how to implement video upload in django for production? I actually i am working on a project to upload videos . In my model i used: (1). video = models.FileField() (2). video = CloudinaryField(resource_type = "video/%y") but of them didnt work as the project crashed. However, models.FileField() works for development on my local machine but doesnt work when i try to upload on heroku. I will deeply appreciate if anyone can help me solve this problem as i have searched youtube ,internet but still have not found solution to it. -
Render HTML from ajax/json in Django
I am trying to filter blog articles by certain tags via ajax. After days learning ajax and working on this I have come up with below code. I have successfully got the data filtered by tag and now want to display it as html. Ive used .each loop to iterate through the values in app.js, and trying to insert the html into the header id trial in all-articles.html. I am getting a syntax error in the console. The syntax error is on the json? data. Here is the screenshot of the error. Any help is appreciated! Thank you all-articles.html {% for article in page_obj %} <article> <header id="trial> <h4>{{ article.title }}</h4> </header> </article> {% endfor %} app.js $(document).ready(function () { $(".tag-nav-links").on("click", function (e) { e.stopPropagation(); return $.ajax({ type: "POST", url: "", data: { filter: `${e.target.textContent}` }, success: function (json) { var html = ""; $(json).each(function (index, value) { html += "<h4>{{" + value.title + "}}</h4>"; }); $("#trial").append(html); }, }); }); }); views.py @csrf_exempt def allarticles(request): articles_list = Articles.objects.all() paginator = Paginator(articles_list, 12) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) all_tags = Tags.objects.all() if request.is_ajax(): tag_assign = request.POST['filter'] tag = Tags.objects.get(tag=tag_assign) data = serializers.serialize('json', Articles.objects.filter(articletags__tag=tag)) return JsonResponse(data, safe=False) context = {'page_obj': page_obj, … -
What are the differences among django_redis, channels_redis, asgi_redis and redis server?
I am new to Django and right now i'm learning Django async with Channels. I have noticed some programmers use channels_redis for their projects, some use django_redis, some use asgi_redis and i found redis server in google. Is there any difference among those libraries? -
Display rating star in Django with fontawesome v5.13
I am writing a website with django and in this website, I periodically ask users to rate platform. I store the ratings with models.FloatField() in my database. Now my problem is how to display the stars. If I have something like 3.5 as the rating value, then in my html page, I should have 3 full stars and the fourth star should be half while the fifth (also the last) should be empty star How can I achieve this with fontawesome v5.13 -
Im trying to create a user model with a foreign key but im getting an error
I am making a notes app. When I try to create a foreign key to link the user and its notes, im getting an error. I am very new to foreign keys, I looked at the Django docs, this is how they created a foreign key. here's the code : from django.db import models class User(models.Model): username = models.CharField(max_length=50) email = models.EmailField(max_length=50) class Note(models.Model): body = models.TextField(null=True, blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.body[0:50] here's the error : django.db.utils.IntegrityError: NOT NULL constraint failed: new__api_note.author_id -
django database query OR condition
I am implementing a friend system similar to facebook where one can send friendship requests and accept requests and then see their friends. On the page where one sees the friend requests I am trying to filter out the users who have accepted the friend request and are friend already now. In the code below, 'u' is the current logged in user. Friendship table hold two fields , both foreign keys, please see below: try: already_friends = Friendship.objects.get(Q(from_friend=u) | Q(to_friend=u)) for x in already_friends.iterator(): my_requests = FriendRequest.objects.filter(Q(receiver=request.user) & ~Q(sender=x)) except ObjectDoesNotExist: class FriendRequest(models.Model): sender = models.ForeignKey(User, related_name='the_sender',on_delete=models.CASCADE) receiver = models.ForeignKey(User, related_name='the_receiver', on_delete=models.CASCADE) def __str__(self): return "request sent" class Meta: unique_together = (('sender', 'receiver'),) class Friendship(models.Model): from_friend = models.ForeignKey(User, related_name="from_friend", on_delete=models.CASCADE) to_friend= models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return "Friend request accepted" class Meta: unique_together = (('from_friend', 'to_friend'),) When I use the query I wrote at the top using Q (complex queries) and then use iterator, I get the following error: 'Friendship' object has no attribute 'iterator' How can I achieve what I intend to do using django models/queries? -
Problem uploading images to S3 Bucket from Django App
My problem is that images stored in media folder are not transferring to S3 Bucket. I tested with other file from request and the file did transfer, so I assume settings.py must be OK. From views.py -> This works: if request.method == 'POST': imageFile = request.FILES['images'] upload = Upload(file=imageFile) upload.save() image_url = upload.file.url print(image_url) This does not work: for i in os.listdir(folder): f = os.path.join(conf_settings.MEDIA_ROOT,company, i) upload = Upload(file=f) upload.save() No error but it just does not work. This also does not work: for i in os.listdir(folder): with open(os.path.join(folder, i)) as f: upload = Upload(file=f) upload.save() >The error I am getting is: > >Exception Value: >'_io.TextIOWrapper' object has no attribute '_committed' > >at upload.save() This is my storage_backend.py from django.conf import settings from storages.backends.s3boto3 import S3Boto3Storage class MediaStorage(S3Boto3Storage): location = 'media' default_acl = 'public-read' file_overwrite = True This is my model.py class Upload(models.Model): uploaded_at = models.DateTimeField(auto_now_add=True) file = models.FileField() I am uploading a .ZIP file with images. Unzipping it and saving them to media folder, then I want to upload from media folder to S3 Bucket. This operation fails. The file in request.FILES is the Zip file, which I am using to test that all settings.py for AWS should be … -
Value matching query does not exist
I am a beginner in Django. I recently came across a problem: When I am trying to fetch objects, it is saying DoesNotExist: Value matching query does not exist. I searched the web but still I got no clue as to why this is happening. My models.py from django.db import models class Value(models.Model): eq_input = models.CharField(max_length=20, default='x**2 + y**2') color = models.CharField(max_length=20, default='Magma') My forms.py from django import forms from .models import Value class ViewForm(forms.ModelForm): Equation = forms.CharField(max_length=20, label='Equation') Color = forms.CharField(max_length=20,label='Color') class Meta: model = Value fields = { 'Equation', 'Color' } My views.py from django.shortcuts import render from django.http import HttpResponse from .models import Value from .forms import ViewForm def home_view(request): if request.method == "POST": form = ViewForm(request.POST) if form.is_valid(): form.save() else: form = ViewForm() context = { 'form': form } return render(request, "home.html", context) My home.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>3D Graph Plotter</title> </head> <body> <center><h1>This is a 3D plotter</h1></center> <center> <form action="." method="POST">{% csrf_token %} {{ form.as_p }} <input type="submit" name="Save" /> </form> </center> </body> </html> and my urls.py from django.contrib import admin from django.urls import path, include from equation.views import eq, home_view urlpatterns = [ path('admin/', admin.site.urls), path('', home_view, name='hv') ] Is there … -
Django admin panel new user registration is not added
OperationalError at /admin/auth/user/add/ no such table: main.auth_user__old Request Method: POST Request URL: http://localhost:8000/admin/auth/user/add/ Django Version: 2.0.3 Exception Type: OperationalError Exception Value: no such table: main.auth_user__old Exception Location: C:\Anaconda3\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 303 Python Executable: C:\Anaconda3\python.exe Python Version: 3.8.8 Python Path: ['C:\Users\sinan\Desktop\blog', 'C:\Anaconda3\python38.zip', 'C:\Anaconda3\DLLs', 'C:\Anaconda3\lib', 'C:\Anaconda3', 'C:\Anaconda3\lib\site-packages', 'C:\Anaconda3\lib\site-packages\locket-0.2.1-py3.8.egg', 'C:\Anaconda3\lib\site-packages\win32', 'C:\Anaconda3\lib\site-packages\win32\lib', 'C:\Anaconda3\lib\site-packages\Pythonwin'] Server time: Cmt, 30 Eki 2021 10:22:25 +0300 -
Django and react login with google authentication
I was trying set up google authentication with react frontend and django rest framework backend. I set up both the frontend and backend using this two part tutorial, PART1 & PART2. When I try to login with google in the frontend I get POST http://127.0.0.1:8000/google-login/ 400 (Bad Request) I think it's because my google api needs an access token and an authorization code to be passed. After debugging the react js, I noticed the response I get from google doesn't have an authorization code. I suspect because responseType is permission(by default), Source:React login props , instead of code. I was wondering how would you change the response type in react? (I'm not even sure if this alone is the issue) Here's my backend code In my views.py file class GoogleLogin(SocialLoginView): adapter_class = GoogleOAuth2Adapter callback_url = "http://localhost:3000" client_class = OAuth2Client in my urls.py path('google-login/', GoogleLogin.as_view(), name='google-login'), for my front end /Components/login.js const googleLogin = async (accesstoken,code) => { console.log(accesstoken) let res = await cacaDB.post( `google-login/`, { access_token: accesstoken, code: code } ); console.log(res); return await res.status; }; const responseGoogle = (response) => { console.log(response.code); googleLogin(response.accessToken, response.code); } return( <div className="App"> <h1>LOGIN WITH GOOGLE</h1> <GoogleLogin clientId="client_id" buttonText="LOGIN WITH GOOGLE" onSuccess={responseGoogle} onFailure={responseGoogle} /> … -
Google PageSpeed Insights not working on pythonanywhere
I had just started a simple application which displays Hello World! This is the index page of games. over here. Also, I wanted to test that website for improvements using PageSpeed Insights using this. When I use PageSpeed Insights, I get this message: Lighthouse returned error: ERRORED_DOCUMENT_REQUEST. Lighthouse was unable to reliably load the page you requested. Make sure you are testing the correct URL and that the server is properly responding to all requests. (Status code: 401) I am using www.pythonanywhere.com using Django for hosting my website. How can I fix that? -
Django-Celery process on Heroku with AWS S3 Access Forbidden
This is a pretty specific issue that I'm running into, but I'm extremely stuck. I've deployed my Django app to Heroku. This app allows the user to upload a pdf which is then stored in AWS S3 bucket storage. The app then redirects the user to a loading page while the pdf is processed in a background process. When the processing is completed, the user is given the option to view and accept changes to their database entries. I'm using celery on a Heroku-redis server for the asynchronous processing. HOWEVER it seems that the Redis server doesn't have the right permissions to read and write to my AWS bucket. Importantly, the main server DOES. I know this because when the user uploads his file, the result is saved in the requisite folder inside the S3 bucket, AND because I very clearly have access to my static files on the site. There's clearly some failure in the credentials handoff from the server to the broker, but I have no idea how to fix this. Code and details below. Here's my celery.py file: from __future__ import absolute_import import os from celery import Celery from django.conf import settings # set the default Django … -
Django Doesn't Pass ForeignKey Models to JSON
I've a Comment models that have 2 attributes referenced to Forum models and Profile Models as a foreign key the I try to serialize it to JSON. But when I try with serializers, the JSON object of my foreignkey attrs return Null. I don't know why since it seems normal when I debug the code and print the object before I save to my form. MODELS: class Comment(models.Model): message = models.TextField() forum_creator_username = models.CharField(max_length=200, null=True, blank=True) forum_creator = models.ForeignKey(Forum, on_delete=models.CASCADE, blank = True, null = True) comment_creator = models.ForeignKey(Profile, on_delete=models.CASCADE, blank = True, null = True) created_at = models.CharField(max_length=50,null=True, blank=True) comment_creator_username = models.CharField(max_length=200, null=True, blank=True) creator_image = models.ImageField( blank=True, null=True, default="profiles/default-user_pfzkxt", ) Views: def index(request, id): forums = Forum.objects.all().values() form = CommentForm(request.POST) response={} if request.method == "POST": if (form.is_valid): print(form.is_valid) print(form.is_valid()) add_comment = form.save(commit=False) add_comment.forum = Forum.objects.get(pk=id) add_comment.comment_creator = Profile.objects.get(user = request.user.id) add_comment.forum_creator = Forum.objects.get(pk=id) add_comment.forum_creator_username = add_comment.forum_creator.creator.username add_comment.comment_creator_username = add_comment.comment_creator.username add_comment.creator_image = add_comment.comment_creator.profile_image add_comment.created_at = datetime.now().strftime("%A, %d %B %Y, %I:%M %p") add_comment.save() return HttpResponseRedirect(request.path_info) response['form'] = form Comment.forum_creator = Forum.objects.get(pk = id) test = Comment.forum_creator = Forum.objects.get(pk = id) print("TES FORUM:",test.id) Comment.comment_creator = Profile.objects.get(user = request.user.id) a = Comment.comment_creator print("comment_reator adalah:",a) print("TES", Comment.forum_creator, "comment:",Comment.comment_creator) response['forum'] = Comment.forum_creator return render(request, … -
Return a distinct order based on In Query
I have a queryset where I want to return the respective order based on my values inside the in filter. Below are my given syntax and models Models class Transaction(models.Model): user = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True) comments = models.TextField(null=True, blank=True) class Profile(models.Model): user = models.OneToOneField(User, null=True, blank=True, related_name='profile', on_delete=models.SET_NULL) first_name = models.CharField(max_length=125, null=True, blank=True) middle_name = models.CharField(max_length=125, null=True, blank=True) last_name = models.CharField(max_length=125, null=True, blank=True) nickname = models.CharField(max_length=100, null=True, blank=True) balance = models.DecimalField(default=0.0, max_digits=7, decimal_places=2) is_online = models.BooleanField(default=False) Syntax from trading.models import Transaction ids = [4, 1, 3, 2] tx = Transaction.objects.filter(user_id__in=ids).order_by('user').distinct('user') Where I expect that the returned order of Transaction object is based on the id order of the list of ids -
Requests are sent 3 times to Django
I am trying to send request using axios and React to django API, The request false twice, then true. So I always have trouble checking :( The tokens are JWT and are configured httponly through the server. I just learned Django and I'm a rookie. So the first if statement is always executed. useEffect(() => { if (!isAuthenticated && !userInfo) { history.push('/login') } else { if (!user || !user.username) { dispatch(getUserDetails('profile')) } else { setUsername(user.username) setEmail(user.email) } } }, [dispatch, history, userInfo, user, isAuthenticated]) | Order | Result | -------- | ---------------------------------------- | | First | {user: {…}} | | Second | {isAuthenticated: false, userInfo: null} | | third | {user: {…}} | | Fourth | {isAuthenticated: false, userInfo: null} | | Fifth | {user: {…}} | | Sixth | {isAuthenticated: true, userInfo: null} | | Seventh | {user: {…}, loading: true} | -
Django signal to delete file on aws s3 not working
I have written the pre_save signal in Django to auto-delete the user's old profile_pic if the user updates its profile_pic. This is my code. @receiver(pre_save, sender=User) def delete_file_on_update(sender, instance, **kwargs): """ Delete the user's old profile pic file when user update the profile and return the status True or False i.e where old pic is deleted or not. """ # If instance is saving for first time in database, don't delete profile_pic file. try: old_file = sender.objects.get(pk=instance.pk).profile_pic except sender.DoesNotExist: return False # If user has not updated profile pic, don't delete profile_pic file. new_file = instance.profile_pic if old_file == new_file: return False try: old_file.delete(save=False) return True except Exception: return False This was working fine when storage was local but when I used the AWS s3 storage, It is not deleting the old profile_pic anymore. Also on debugging this signal is get called on each pre_save of user and old_file.delete(save=false) is also executing but the file is not deleting on AWS s3. -
How to convert pdf files into JPEG files and save them in ImageField of Django
I want to convert pdf files into jpeg files and save them as ImageField in Django. In my case, I already have pdf files in MyModel and some of them will be converted into jpeg files and saved as jpeg files as ImageField in AnotherModel. pdf_path = MyModel.object.pdffile.path If I use "convert_from_path" provided by pdf2image, I think it is necessary to prepare the path for a jpeg file in advance. However, I don't know how to prepare it before creating each record of ImageField. -
ProgrammingError at /admin/aws_app/imageframe
django.db.utils.ProgrammingError: column "frame_captype_id" of relation "aws_app_imageframes" does not exist LINE 1: ...ws_app_imageframes" ("time_stamp", "image_frame", "frame_cap... I recently truncated this table ( image frames which is having foreign-key relation with frame_cap, but now it is not allowing me to push any data , and throwing the above error , what's the issue ?, currently both the tables are truncated class ImageFrames(models.Model): time_stamp = models.DateTimeField(auto_now_add=True) image_frame = models.FileField(upload_to = 'camera_frames',null=True,blank=True,max_length=500) flagged_as = models.ManyToManyField(FLag) frame_captype = models.ForeignKey(FrameCapType,on_delete=models.CASCADE,null=True,blank=True)