Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding choices but not showing in the selectbox
I am trying to add categories in my blog project. So that whenever user post a blog he will add category also but in the select box it is not showing I tried this : from django import forms from .models import Post,Category,Comment choices = Category.objects.all().values_list('name','name') choice_list = [] for item in choices: choice_list.append(item) class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title','title_tag','author','category','body','snippet','header_image') widgets = { 'title' : forms.TextInput(attrs={'class':'form-control','placeholder':'Title of the Blog'}), 'title_tag' : forms.TextInput(attrs={'class':'form-control','placeholder':'Title tag of the Blog'}), 'author' : forms.TextInput(attrs={'class':'form-control','value':'','id':'elder','type':'hidden'}), 'category' : forms.Select(choices=choice_list, attrs={'class':'form-control','placeholder':"blog's category"}), 'body' : forms.Textarea(attrs={'class':'form-control','placeholder':'Body of the Blog'}), 'snippet' : forms.Textarea(attrs={'class':'form-control'}), } Here Category model contains my categories -
How to set custom choices in Wagtail form?
I am fetching a list of items from another project, and want to show that list in my form. I tried overriding ModelChoiceField to define choices, but it is not working: from django.forms import ModelChoiceField class CustomChoiceField(ModelChoiceField): def _get_choices(self): # Overriding ModelChoiceField's _get_choices() method to set custom choices self._choices = my_utils.get_choices() return self._choices from wagtail.admin.forms import WagtailAdminPageForm from wagtail.snippets.widgets import AdminSnippetChooser class MyCustomForm(WagtailAdminPageForm): my_field = CustomChoiceField(queryset=SomeModel.objects.all(), widget=AdminSnippetChooser(SomeModel), required=False) I want to choose from the list that was returned by the API call, and whatever the user chooses, should be saved in the my_field. How can I achieve this? -
How can i let users to write to each other in messenger from my website?
Im working in Django and i have a form in user profile for facebook account. I want to integrate this to do something like down below but user to user not user to website. sth like this -
Raise validation error only when a new file is being uploaded
Django 3.1.5 I'd like to prevent saving a file with the same name. This is necessary for fingerprinting static assets (for caching purposes). For example: If a user has already saved a file main-1.css, s/he can't upload such a file anymore. In thic they sholuld rename it and upload as main-2.css. def _validate_file_existance(value): model = apps.get_model('staticassets', 'CssFile') try: existing_file = model.objects.get(file__contains=value) except Exception as e: return # File doesn't exist. # File exists. raise ValidationError('A file with such a name already exists. Change the file version or don't try to save it.') Used like this: class SvgFile(models.Model): alt = models.CharField(max_length=255, verbose_name="Alt", null=False, blank=True, default="") file = models.FileField(upload_to=svg_upload_to, verbose_name="SVG file", validators=[validate_svg_file_existence], ) Problem If I want to edit alt, this validator raises validation error. But I don't upload a new file. I just edit another field of the instance of an SvgFile. Could you help me solve the problem: Raise validation error only when a new file is being uploaded. Keep silence when the file field is not touched. -
How not to display a field when it's None in Django
I have this model: class MsTune(models.Model): name = models.CharField(max_length=255) # title (source) start_page = models.CharField(max_length=20, blank=True, null=True, default="") def __str__(self): if self.start_page != '' or self.start_page is not None or self.start_page is not "None" or self.start_page is not null: return '%s, %s' % (self.name, self.start_page) else: return '%s' % (self.name) As you can see, I want only name if start_page is empty, or name, start_page if start_page is filled. No matter how many conditions I put (see above), I keep getting name, None in my template. What am I missing? Also, is there a shorter code I can put in place, instead of the verbose if / else ? -
How to use hooks.py of django-paypal to check payment attributes sent?
I followed https://django-paypal.readthedocs.io/en/stable/standard/ipn.html to use PayPal Standard IPN of django-paypal for a Django e-commerce website. I do not understand how should I use the signal in hooks.py to ensure the attributes such as 'business' and 'amount' are not changed by others. I cannot find any post that gives a good example about it. Most of them just ignore the hooks.py file. Is this file 'hooks.py' necessary for security? If yes, what should I return in hooks.py (for both scenarios: Attributes are found changed and payment fails; and attributes are not changed and everything is good to go)? Thanks so much. views.py from django.core.urlresolvers import reverse from django.shortcuts import render from paypal.standard.forms import PayPalPaymentsForm def view_that_asks_for_money(request): # What you want the button to do. paypal_dict = { "business": "receiver_email@example.com", "amount": "10000000.00", "item_name": "name of the item", "invoice": "unique-invoice-id", "notify_url": request.build_absolute_uri(reverse('paypal-ipn')), "return": request.build_absolute_uri(reverse('your-return-view')), "cancel_return": request.build_absolute_uri(reverse('your-cancel-view')), "custom": "premium_plan", # Custom command to correlate to some function later (optional) } # Create the instance. form = PayPalPaymentsForm(initial=paypal_dict) context = {"form": form} return render(request, "payment.html", context) yourproject/hooks.py from paypal.standard.models import ST_PP_COMPLETED from paypal.standard.ipn.signals import valid_ipn_received def show_me_the_money(sender, **kwargs): ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: # WARNING ! # Check that the receiver email is … -
ValueError returning a function from a function in a model during makemigrations
I have a model defined in Django 3.1 like class MyModel(models.Model): def get_path(path): def wrapper(instance, filename): # code to make the path return 'path/created/for/filename.jpg' return wrapper image = models.ImageField(upload_to=get_path('files/')) but when I do python3 manage.py makemigrations I am getting a ValueError: Migrations for 'myproject': myproject/migrations/0023_auto_20210128_1148.py - Create model MyModel Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Library/Python/3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Library/Python/3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Python/3.7/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Python/3.7/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/Library/Python/3.7/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/Library/Python/3.7/site-packages/django/core/management/commands/makemigrations.py", line 182, in handle self.write_migration_files(changes) File "/Library/Python/3.7/site-packages/django/core/management/commands/makemigrations.py", line 219, in write_migration_files migration_string = writer.as_string() File "/Library/Python/3.7/site-packages/django/db/migrations/writer.py", line 141, in as_string operation_string, operation_imports = OperationWriter(operation).serialize() File "/Library/Python/3.7/site-packages/django/db/migrations/writer.py", line 99, in serialize _write(arg_name, arg_value) File "/Library/Python/3.7/site-packages/django/db/migrations/writer.py", line 51, in _write arg_string, arg_imports = MigrationWriter.serialize(item) File "/Library/Python/3.7/site-packages/django/db/migrations/writer.py", line 271, in serialize return serializer_factory(value).serialize() File "/Library/Python/3.7/site-packages/django/db/migrations/serializer.py", line 37, in serialize item_string, item_imports = serializer_factory(item).serialize() File "/Library/Python/3.7/site-packages/django/db/migrations/serializer.py", line 199, in serialize return self.serialize_deconstructed(path, args, kwargs) File "/Library/Python/3.7/site-packages/django/db/migrations/serializer.py", line 86, in serialize_deconstructed arg_string, arg_imports = serializer_factory(arg).serialize() File "/Library/Python/3.7/site-packages/django/db/migrations/serializer.py", line 159, in serialize 'Could not … -
Pass get_queryset in Context
Need help on passing the returned value from get_queryset to the context for rendering, I am reading the Django documentation on Class-based Views and I keep getting the same error name 'querySet' is not defined, any insight on what I'm doing wrong would be appreciated. class SearchPropertyListView(ListView): template_name = "search/search_list.html" def get_queryset(self): querySet = Property.objects.all() city_or_neighborhood = self.request.GET.get('city_or_neighborhood') category = self.request.GET.get('category') purpose = self.request.GET.get('purpose') if city_or_neighborhood != '' and city_or_neighborhood is not None: querySet = querySet.filter(Q(city__title__icontains=city_or_neighborhood) | Q(neighborhood__title__icontains=city_or_neighborhood) ).distinct() elif category != '' and category is not None: querySet = querySet.filter(category__title=category) elif purpose != '' and purpose is not None: querySet = querySet.filter(purpose__title=purpose) return querySet def get_context_data(self, *args, **kwargs): context = super().get_context_data(**kwargs) city = City.objects.all().annotate( num_property=Count("property")).order_by("-num_property") categories = Category.objects.all() purposes = Purpose.objects.all() featured = list(Property.objects.filter(featured=True)) shuffle(featured) context['city'] = city context['categories'] = categories context['featured'] = featured context['purposes'] = purposes context['querySet'] = querySet return context -
Optimize repeteted queryset
I have few querysets that I use in every single view (>50). Is there a way to write once for all and keep the queryset result available for all views ? def MyView(request): company= Company.objects.get(User=request.user) user_info= User_infos.objects.get(User= request.user) groups= request.user.groups.values_list('name',flat = True) I'm using those results for filtering purposes like Product.objects.filter(Company = company) -
Fetching multiple entries of same id in django
I am trying to make a query and retrieve all the data listed under that particular user with the help of the primary key. I am getting the data but it consists of only one data but I should get three. Here is the views: def eachlead(request, pk): # print(pk) lead = Lead.objects.get(id=pk) leadinfo = LeadDetail.objects.filter(id=pk) print(list(leadinfo)) return render(request, "onelead.html", {'lead': lead, 'leadinfo': leadinfo}) Here is models: class LeadDetail(models.Model): Lead = models.ForeignKey(Lead, on_delete=models.CASCADE) files = models.FileField(blank=True, upload_to='media') tasks = models.TextField(max_length=1000) def __str__(self): return self.Lead.first_name class Lead(models.Model): lead_status = ( ('Potential', 'Potential'), ('Prospect', 'Prospect'), ('Negotiation', 'Negotiation'), ('Converted', 'Converted'), ('Failed', 'Failed') ) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) age = models.IntegerField(default=0) city = models.CharField(max_length=25, null=True) country = models.CharField(max_length=30, null=True) email = models.EmailField(max_length=50, null=True) agent = models.ForeignKey('Agent', on_delete=models.CASCADE, null=True) status = models.CharField(max_length=15, choices=lead_status, null=True) avatar = models.ImageField(null=True, upload_to='media') def __str__(self): return self.first_name The response I am getting is [<LeadDetail: Test1111>] or [{'id': 1, 'Lead_id': 1, 'files': 'media/dummy.pdf', 'tasks': 'Meeting at 19:00 Friday'}] but there are 3 tasks under this ID: -
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.