Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass comment object to reply form in django
Please help me! I can't find a way to pass Comment model to reply form (it be create be jQuery). Here is full code on github. Snippet code is below. I have two model: User = settings.AUTH_USER_MODEL class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) class Reply(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.ForeignKey(Comment, on_delete=models.CASCADE) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) I create reply form by jQuery: $(document).ready(function(){ $form = $('<form class="mt-3" method="POST" action="/reply/"></form>'); $form.append("<input type='hidden' name='csrfmiddlewaretoken' value='" + csrftoken + "'>"); $form.append('<textarea name="content" id="" cols="30" rows="5"></textarea>'); $form.append('<br />'); $form.append('<input type="button" value="Cancel" class="btn btn-dark me-2 remove-button">'); $form.append('<input type="submit" value="Post" class="btn btn-primary">'); $(".reply-button").click(function(){ $button = $(this); $button.parent().append($form); }); //gán sự kiện khi sử dụng append một đối tượng sau này $(document).on('click', '.remove-button', function(){ $form.remove(); }); }) Action redirect to ReplyView view: class ReplyView(View): def post(self, request, *args, **kwargs): # I expect something can get Comment id for reply qs = Comment.objects.filter(id = 1) comment = qs.first() if request.user.is_authenticated: r = Reply(user = request.user, comment = comment, content= request.POST.get("content")) r.save() return redirect("comment-page") -
How to Load Django Template Async
I have an API to keep watching database for changes and updates the same to Django. And am using Django channels to update the changes to the front end templates as well. I am running the API along with Django run server and gets changes from database and API runs indefinitely. The problem is though API keeps watching the changes which never terminates Django is not able to get the http request so webpage is not loading. I need to run API when Django starts as well as web page should be loaded and for every 1 second will update the web page with the new changes. But now when I start the API along with Django am not able to load the webpage because API is infinite. How do I do this in order to load webpage and start updating changes to the webpage ? -
Django model related_list with list view
First, I have a student model and a counseling model. There are hundreds of consultation models in one student model. I'd like to make the last consultation date for each subject(classification) into a listview for each student. If make it , teacher can see at a glance who consulted the longest and who consulted the most recently. is there any way? consultation model.py class Consultation(models.Model): classification = models.CharField( max_length=10, choices=CLASSIFICATION, # there are 'korean', 'english', 'math', 'etc ... ' default='etc', ) content = models.TextField(max_length=1000, blank=False, verbose_name='contentt') created_to = models.ForeignKey( Student, related_name='consultations', verbose_name='student', on_delete=models.CASCADE ) created_at = models.DateTimeField(default=datetime.now, verbose_name='time') student mnodel.py class Student(models.Model): name = models.CharField(max_length=255, verbose_name='이름') I want to user ListView if i can class StudentList(ListView): model = Student template_name = 'student/list.html' context_object_name = 'students' paginate_by = 10 blah blah blah What i want to make is like student name last consultation date of korea subject last consultation date of english subject last consultation date of math subject student name last consultation date of korea subject last consultation date of english subject last consultation date of math subject student name last consultation date of korea subject last consultation date of english subject last consultation date of math subject student name … -
How do i enable SSO in Django
How do i enable SSO in Django. As i am working in an organization, my manager asked me to enable SSO for default login using our org SSO ssytem. for our django application. Now, we have added the link to our django home page with our org SSO system. but how do we handle this situation in django urls.py file as there are some base64 string is being concatinated while hitting our org SSO system and redirecting back to our djngo home page, and it is showing error 404. kindly help in this regard. Best Regards krkc -
display images when AWS_DEFAULT_ACL = None in django
Here how can i display images stored in s3 where bucket is set as private in django AWS_ACCESS_KEY_ID = 'XXX' AWS_SECRET_ACCESS_KEY = 'XXX' AWS_STORAGE_BUCKET_NAME = 'XXX' AWS_DEFAULT_ACL = None AWS_QUERYSTRING_AUTH = False DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' MEDIA_URL = 'https://mybucket.s3.amazonaws.com/' in my template <img src="{{ logo.url }}"alt="p" > But I am not able to display the image in the front end -
how to use different decorator from parent class in child class in django?
I have 2 class based views MyFirstView and MySecondView. I want these 2 views to use different decorators from each other. I have been googling for the solution almost an hour now but still can't find any answers to this. So I'm here asking for help. @method_decorator(my_first_decorator, name="dispatch") class MyFirstView(UpdateView): # some attributes # some methods @method_decorator(my_second_decorator, name="dispatch") class MySecondView(MyFirstView): # some attributes I have been trying to give the different decorator to the views like showed above but for some reason MySecondView still using MyFirstView's decorator. I also tried to override the dispatch method but without any success. class MyFirstView(UpdateView): @method_decorator(my_first_decorator) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) # some attributes # some methods class MySecondView(MyFirstView): @method_decorator(my_second_decorator) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) # some attributes -
Limitting user's ability with "premium" and set time intervals
I'm trying to monetize my website using "premium" plans. I am trying to make it such that eg normally, you will be required to wait 1hour before you can create your second blogpost for that specific user, and if you try to post during that one hour, you will receive a message saying that you have to wait for {{ remaining time }} left. I'm totally new to monetization. Could someone share how I can impose the 1hour waiting time before a post can be created and also how to create a "premium plan" where the code can "recognise" this "premium" plan and hence auto shorten the duration..like the payment etc. I also plan to monetise other functionalities so if any kind soul can give an example of this, it would really help as I try to adapt the same method taught to other functionalities...Thank you! models.py class BlogPost(models.Model): title = models.CharField(max_length=50, null=False, blank=False, unique=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) date_published = models.DateTimeField(auto_now_add=True, verbose_name="date published") date_updated = models.DateTimeField(auto_now=True, verbose_name="date updated") class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) forms.py class CreateBlogPostForm(forms.ModelForm): class Meta: model = BlogPost fields = ['chief_title'] views.py def create_blog_view(request): context = … -
Celery-Django weblogs Grok Pattern
I'm trying to get the grok pattern for the following web log line: '''[2020-12-14 10:44:57,598: INFO/ForkPoolWorker-1] Task celery.chord_unlock[1f93d444-835f-4ff4-b730-915b0f17f9ab] retry: Retry in 1s''' -
How to customise unique = true in django
ok basically, users on my website can create blogposts. But I do not want to use unique = True because that'll mean that user1 cannot create a post that has the same title as user2. I want to make it such that user1 can create a post that has the same title as user2 BUT user1 CANNOT create another post with the same name as any existing post that USER1 has previously created. Meaning user 1 can have a blogpost title "hello" and user 2 can also have a blogpost "hello" but user 1 cannot have 2 blogpost with the same title 'hello' Ok i think this is clear enough^....if I use unique = true, this would be too much, so how can I customise that such that it only applies to the user's post? Thanks! models.py class BlogPost(models.Model): title = models.CharField(max_length=50, null=False, blank=False, unique=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) forms.py class CreateBlogPostForm(forms.ModelForm): class Meta: model = BlogPost fields = ['chief_title'] html <form class="create-form" method="post" enctype="multipart/form-data">{% csrf_token %} <div class="form-group"> <label for="id_title">Title</label> <input class="form-control" type="text" name="title" id="id_title" placeholder="Title" required autofocus> </div> <button class="submit-button btn btn-lg btn-primary … -
For how long does OSCAR save a user basket
Users report their basket being deleted the day after they added products to it, other times it lasts for more than two days. There doesn't seem to be any saved cookie apart from a session ID and a CSRF token and I couldn't find a function that actively deletes users' baskets after a specific amount of time. I would like to increase the time OSCAR saves baskets to a month but all I could find in the source is a reference to a cookie set for "7 x 24 x 60 x 60", which would mean a week. -
Change urls' scheme from http to https in DRF api-root
I created an API, deployed it on the server on 8443 port and setup cloudflare's SSL certificates. Everything works perfectly, but I got a problem that urls in api-root still have http scheme. Also I set X-Forwarded-Proto $scheme header in nginx.conf. What could be the problem? -
How to return the data from django signal?
I am using Django-rest for developing the API. In my case, when the user posts the data, I have to process the posted data (It will take 2-3 min). I wrote the Django signal for preprocessing data. My signal.py file looks like this, @receiver(post_save, sender=ExposureIndex) def calculate_exposure(instance, created, *args, **kwargs): ear_table = instance.ear_index.name haz_dir = instance.hazard_index.file.path # calling celery task task = exposure_calculation.delay(ear_table,haz_dir) return task.id And my celery calculation function is here, @shared_task(bind=True) def exposure_calculation(self, ear_table, haz_dir): progress_recorder = ProgressRecorder(self) CalculateExposure(ear_table, haz_dir) return 'Done' My django-rest view function is looks like this, class ExposureIndexViewSet(viewsets.ModelViewSet): queryset = ExposureIndex.objects.all() serializer_class = ExposureIndexSerializer permission_classes = [permissions.IsAuthenticated] My question is when the user posts the data, I want to return the task.id instead of returning the actual response (I tried to return it from the Django signal but it is not returning in the actual API). Can anyone suggest to me how to return task.id instantly when the user posts the exposureIndexData? -
CSRF verification failed on Production environment Django
I am using Django v2.2.8 with python 3.6.9. My payment gateway falls back on url which i specified i.e. https://example.com/success, https://example.com/failure after the transaction. However, i have used csrf_exempt on the views handling these urls which works fine in local environment but on production it gives 403 forbidden csrf verification failed. views.py @csrf_exempt def payu_failure(request): data = {k: v[0] for k, v in dict(request.POST).items()} response = payu.verify_transaction(data) return JsonResponse(response) source from https://github.com/renjithsraj/paywix/blob/master/PAYU.md settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', ] urls.py has proper configuration path('failure', views.payu_failure, name='payu_failure'), -
How to use Django streaming download a file when writting data to it?
How to use Django to streaming download a file when writing data to it? That means I don't know the file size when I start downloading it. -
502 Bad Gateway on Digitalocean Droplet nginx/1.14.0 (Ubuntu) Python/Django seems timeout for gunicorn is not working
Amazing thing is happening all is running perfectly my application is live on Digital ocean droplet with 2 CPUs and 4GB RAM. Setup is NGINX / GUNICORN / PYTHON / DJANGO Application works perfectly fine with small output to produce as PDF report byusing package xhtml2PDF but when the output is large like 2MB or 3MB to produce PDF report after 30 seconds I got 502 Bad Gateway error. I checked with command sudo journalctl -u gunicorn output gunicorn[1326]: Fatal Python error: Cannot recover from stack overflow Jan 27 14:38:37 msaaspro.com gunicorn[1326]: Current thread 0x00007f78ffaa2740 (most recent call though I have increased timeout for gunicorn and nginx upto 300 but the process break with in 30s in this situation. Can anyone have idea what parameters I need to increase as a server setup to handle this on large PDF report processing. -
Django Sum float values
I have model in Django which have three fields. Float, and two CharFields. I need to sum the float fields by the other two. models.py class Hours(model.Model): hours_worked = models.FloatField() order_number = models.CharField() oper = models.CharField() What I need to do is go through all data in DB and sum hours_worked for the same order_number+oper. So let say I have in db 4 records: |hours_worked|order_number|oper| |------------|------------|----| | 4| 252| 10| | 8| 320| 20| | 8| 252| 10| | 6| 252| 20| And I need to return queryset of three objects like this: |hours_worked|order_number|oper| |------------|------------|----| | 12| 252| 10| | 8| 320| 20| | 6| 252| 20| Is there any easy way how to do it? -
Staticfiles are not working on real Django server
I am using VPS SSH server and in localhost everything works perfect while on server staticfiles are not working (css, js, images). I did the migrations and collectstatic. -
How to add custom field to django rest auth model without modifying the django auth model?
I am trying to add a phone field for Django rest user registration. I am using Django auth model. I don't want to add a custom field to Django user model. Without modifying the user model I need to add a phone field to RegisterUserSerializer -
send model form as a json response in django
I want to send a modelform to my template using through json response(I've no idea if it's possible or not). Actually in my template I have a list of objects from a model, and when i click them i send a post request to my view through ajax or axios with the object id, then in view I'm creating the model form of that object and I want to send that the model form of instance object back to template. to summarize it up how can i send an model form through json response.(If not possible how to ) -
How to check if query has select_related but no other field filtering, django queries?
Django Model Admin has default Paginator that has a count method that perform a count(*) to get number of records for a given query, which add overhead when table size grows. One of the methods to solve this uses the following override of count: from django.core.paginator import Paginator class CustomAdminPaginator(Paginator): ... @cached_property def count(self): query = self.object_list.query is_filtered = query.where if is_filtered: return super().count try: cursor = connection.cursor() cursor.execute("SELECT reltuples FROM pg_class WHERE relname = %s", [query.model._meta.db_table]) return int(cursor.fetchone()[0]) except: return super().count Basically this solution uses an estimated record count stored in one of postgres meta tables. One of the problem of this method, is that even if the query has only select_related on non-nullable field (then the number of records is equal to the number of records if the query does not have select_related) then it will call the super count i.e. it will not use the pg_class utility. The question is how to know if query only has select_related or prefetch_related but no other filed filters such as, create_date__lte..etc? -
Django: better (simpler) migration system alternative?
Is there an alternative to built-in Django migration system, which doesn't try to be intelligent? Ideally, I would like the following: Simple DSL for typical operations (add/change/remove column, add/change/remove table, add/change/remove index, etc., including raw SQL as the last resort) Auto-revert for these operations (unless raw SQL is used) Single folder with all migrations for the whole project (so when I refactor some 'app', e.g. split it into two apps, that doesn't require to change migrations). No boilerplate for specifying migration dependencies: each migration is assumed to depend on every preceding one. No 'state' management. Just run the DSL statements. -
Meaningful error message if Redirect after Post fails (Testing Django)
After successful POST a redirect should happen (PRG Pattern) response = admin_client.post(url, data) assert response.status_code == 302 If this test fails, I get a very meaningless error message. AssertionError assert 200 == 302 Is there a django-way to get the error message of the form into the exception? -
How to change the format of REST API Filter?
I'm filtering the date of REST API url by calling a string. /api/data/?date_range=Today for Today but converting it into a date /api/data/?date_range=2021-01-28 won't work. How to change this? Thanks! class DataFilter(filters.FilterSet): start_date = DateFilter(field_name='timestamp', lookup_expr='gt') end_date = DateFilter(field_name='timestamp', lookup_expr='lt') date_range = DateRangeFilter(field_name='timestamp') class Meta: model = Data fields = [] class DataView(generics.ListCreateAPIView): serializer_class = RainfallSerializer queryset = Data.objects.all() filterset_class = DataFilter def get(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) serializer = DataSerializer(queryset, many=True) return Response(serializer.data) -
Build SPA for WeatherMap (Similar to CACTI)
I'm currently at initial conceptual phrase for SPA development. I'm a network engineer and also a beginner in Python programming with some concepts around web development. I'm planning to build a SPA to visualise traffic volume like a weathermap between different continents. I would like to have some inputs from everyone of you about the options/toolkits that I've in my mind or any extra stuffs that can facilitate this purpose much easier as a newbie Front end weather heat map: Python Flask / Django web framework, JavaScript/CSS, not sure what plug-in to use to build the coordinates between different countries and connect the dotted point between them Backend: Any suggestion of JSON based database (thinking of TSDB like influxDB) but hopefully to have something easier to integrate with python Last but not least, if there's any good reference, either web page or books that I can read through, that would be really helpful. Hope to hear any good suggestions here. Best Regards RJ. -
How to change make changes to my 'Order' in Django after receiving payment by Stripe Checkout Session?
I am making an e-commerce website by Django and want to use Stripe Checkout Session for receiving online payments. I followed https://stripe.com/docs/api/checkout/sessions for creating checkout sessions and https://stripe.com/docs/webhooks/build for creating the webhooks. I could receive payments smoothly, but I want to change the 'order' to 'complete = True' right after payments are received. However, the request of view 'stripe_webhook' does not have attribute of user, so I can't call 'request.user' to get the corresponding 'order'. How could I solve this issue? Thanks so much. models.py class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True, null = True, blank = True) date_completed = models.DateTimeField(null = True, blank = True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) def __str__(self): return f'{self.user.username} {self.date_created}' views.py @login_required def stripe_payment(request): return render(request, 'stripe_payment.html', {}) @csrf_exempt def stripe_config(request): if request.method == 'GET': stripe_config = {'publicKey': settings.STRIPE_PUBLISHABLE_KEY} return JsonResponse(stripe_config, safe=False) @csrf_exempt def stripe_create_checkout_session(request): if request.method == 'GET': domain_url = 'http://localhost:8000/' stripe.api_key = settings.STRIPE_SECRET_KEY order = Order.objects.get(user = request.user, complete = False) total = int(order.get_cart_items_total) * 100 try: checkout_session = stripe.checkout.Session.create( success_url = domain_url + 'success?session_id={CHECKOUT_SESSION_ID}', cancel_url = domain_url + 'cancelled/', payment_method_types = ['card'], mode = 'payment', line_items = [ { 'name': ' ', 'quantity': 1, 'currency': 'usd', 'amount': …