Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Binding Multiple Files to Django Form Widget
Previously my Django form had a field that supported uploading a single file: image = forms.ImageField(required=False, help_text=_('Optional image (2.5 MB or less)'), allow_empty_file=True) If the user tried to edit the form after submitting it, I displayed the previously uploaded file by binding it to the form like so: if request.method == 'POST': ... else: data = {'title': model.title} file = {'image': model.file} form = MyForm(data, file, instance=model) To enable uploading multiple files, I've now changed the widget to: image = forms.ImageField(required=False, help_text=_('Optional image (2.5 MB or less)'), allow_empty_file=True, widget=forms.ClearableFileInput(attrs={'multiple': True})) This works fine when uploading the files, but I can't find a way to bind more than one file to the form when it comes to editing it. Is there a solution using the current widget, or would it involve using a custom or multiple widgets? Thanks. -
Django password help_text not rendering correctly
I am rendering a simple signup form as follows: <form method="post"> {% csrf_token %} {% for field in form %} <p> {{ field.label_tag }}<br> {{ field }} {% if field.help_text %} <small style="color: grey">{{ field.help_text }}</small> {% endif %} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </p> {% endfor %} <button type="submit">Sign up</button> </form> However, the help text for the password, which is an unordered list, is rendering as a single string (including the markup). It is basically putting the entire ul in quotes as can be seen from the shot from dev tools. Any ideas how to solve this problem? -
celery task issue in post_save
I have a model called "Request". On creation I have to send an email with the details of "Request" model. The project is written in Django 1.9 So I decided to use celery, write the mail sending func in post_save signal of "Request". The issue is on celery task, I am getting Http404 exception. Already tested with transaction to fix the issue as mentioned on the link below. handle-post-save-signal-in-celery - stack overflow link from django.db import transaction from app.notifications.tasks import service_request_notification # signal @receiver(post_save, sender=Requests) def send_notifications(sender, instance, created, **kwargs): if created: transaction.on_commit( lambda: service_request_notification.delay(instance.pk)) # celery task @app.task def service_request_notification(request_id): req = get_object_or_404(Requests, pk=request_id) send_mail_to_admins(req) -
Django Filter Query on Listview
I have a case, that needs show user will expire in 1 month & user already joined below 1 month on the view. here my template.html look like +-------------------------------------+ +-------------------------------------+ | Member will Expired in 30 days | | New Member Almost 30 Days | +-------------------------------------+ +-------------------------------------+ | Name | Expired in | | Name | 1 Month in | +-------------------------------------+ +-------------------------------------+ | John | 12 Hours | | Alex | 12 Hours | | Doe | 10 Days | | Monroe | 12 Days | | Sue | 30 Days | | Zax | 28 Days | +-------------------------------------+ +-------------------------------------+ here my template.html code ... {% for a in dashboards %} <tr> <td>{{ a.name }}</td> <td>{{ a.membership_till|naturaltime }}</td> </tr> {% endfor %} ... ... {% for a in dashboards %} <tr> <td>{{ a.name }}</td> <td>{{ a.membership_till|naturaltime }}</td> </tr> {% endfor %} ... here my model.py class User(models.Model): ... name = models.CharField(max_length=255) joined_date = models.DateTimeField(max_length=255) membership_till = models.DateTimeField(max_length=255) ... here my views.py class DashboardListView(ListView): template_name = 'index.html' context_object_name = 'dashboards' model = models.User Currently, I only can show all the data on that two table without filtering. I need to show 2 <table> with 2 different functions but I don't have … -
What's the different between "# -*- coding: utf-8 -*-" ,"from __future__ import unicode_literals" and "sys.setdefaultencoding("utf8")"
What I know is: 1. "# -- coding: utf-8 --" It is used to declare the encoding of a Python source file, once I set the encoding name, Python parser will interpret the file using the given encoding. I call it "file encoding"; 2. "from __future__ import unicode_literals" I'm doing my tasks using Python2.7, and I use "from __future__ import unicode_literals" to change the default type of string from "str" to "unicode". I call it "string encoding"; 3. "sys.setdefaultencoding('utf8')" But sometimes, I get an error in Django, for example, I stored Chinese in admin, then I visited the releated pages UnicodeEncodeError at /admin/blog/vulpaper/29/change/ 'ascii' codec can't encode characters in position 6-13: ordinal not in range(128) ....the more error information The string that could not be encoded/decoded was: emcms外贸网站管理系统 for this problem, I will write "sys.setdefaultencoding('utf8')" in Django settings file to solve it. But Actually, I don't know the tech detail of the above. What make me confused is: 1. Since I set the python source file encoding, why should I set the string encoding to ensure my string's encoding is favorite encoding? What's the different between "file encoding" and "string encoding"? 2. Since I set the "file encoding" and "string … -
GUI takes lot time to load for models foreign keys in django
In my code Foreign keys Process_part has thousands entries. while creating new Tool its taking 2 min to load process_part into the html page...is there any chances to make page load faster class Tool(models.Model): tool_id = models.AutoField(db_column='Tool_id', primary_key=True) tool_name =models.CharField(db_column='Tool_name') process_part =models.ForeignKey(ProcessPart,on_delete=models.CASCADE -
passing None to a foreign key while saving a serialiser in Django Rest Framework
Here is a model for header, class Header(models.Model): id = models.AutoField(primary_key=True) features = models.ForeignKey(Project, null=True, blank=True, related_name= 'features') def __str__(self): return str(self.name) and this the model for Project (the foreign key of features in Header): class Project(models.Model): id = models.AutoField(primary_key=True) project_info = models.OneToOneField(ProjectInfo, related_name='project_info') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) dataset_associated = models.ForeignKey(Dataset) ratio_test_training = models.IntegerField() random_seed = models.IntegerField(blank=True, null=True) url = models.URLField(blank=True, null=True) def __str__(self): return str(self.project_info.name) And, when I am trying to save Header serializer by passing None to features, it shows an error that : {features: ["This field may not be null."]} even when I have set its property of null = True. This is the serializer for Header: class HeaderSerializer(serializers.ModelSerializer): features = ProjectSerializer() class Meta: model = models.Header fields = ('id', 'features') def create(self, validated_data): features_data = validated_data.pop("features") if(features_data): features = models.Project.objects.get(pk = (features_data.get("id"))) else: features = None obj=models.Header.objects.create(features = features) obj.save() return obj And this is the code in views.py, @api_view(['GET', 'POST', 'DELETE']) def header_detail_pk(request): if request.method == 'POST': features = request.POST.get('features') if(features): features = project_serializer.data print("Not none") else: features = None serializer = HeaderSerializer('features':features) if serializer.is_valid(): serializer.save(features= features) return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
django CreateView with SuccessMessageMixin error: no attribute 'cleaned_data'
I tried to use SuccessMessageMixin with CreateView but got an error. I used it with UpdateView and it worked. It'd be nice to get a hint about what to do next. Thanks. Repo: https://github.com/jeremy886/DjangoBasics/blob/DjangoForms/courses/views.py Error: AttributeError at /courses/2/create_quiz/ 'Quiz' object has no attribute 'cleaned_data' Request Method: POST Request URL: http://localhost:8000/courses/2/create_quiz/ Django Version: 2.0.5 Exception Type: AttributeError Exception Value: 'Quiz' object has no attribute 'cleaned_data' Exception Location: C:\Users\jeremy\.virtualenvs\django\lib\site-packages\django\contrib\messages\views.py in form_valid, line 12 Code: class QuizCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView): model = "course" pk_url_kwarg = "course_pk" context_object_name = 'course' form_class = forms.QuizForm template_name = "courses/quiz_create.html" success_message = "%(title)s was created successfully" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) course_pk = self.kwargs.get(self.pk_url_kwarg) course = get_object_or_404(models.Course, pk=course_pk) context["course"] = course return context def form_valid(self, form): course_pk = self.kwargs.get(self.pk_url_kwarg) quiz_form = form.save(commit=False) quiz_form.course = get_object_or_404(models.Course, pk=course_pk) # find a way to add "Successfully added!" message return super().form_valid(quiz_form) def get_success_url(self): course_pk = self.kwargs["course_pk"] return reverse_lazy('courses:detail', kwargs={'pk': course_pk}) # More: how to get the quiz id from the above quiz form -
django model object and queryset save to other table
using django 2.0.2 python3.4 skip details models.py class Post(models.Model): postuid = models.BigAutoField( db_column='postUID', primary_key=True) useruid = models.Foreignkey .... skip content = models.Text .... registerdate = models.Date .... class KeepPost(models.Model): keeppostuid = bigautofield useruid = ForeignKeyfield postuid = integerfield content = textfield registerdate = Detetime keepdate = Datetime Post to KeepPost Post.objects.get(postuid=1) or Post.objects.filter(useruid=1) KeepPost.objects.create(modelobjects or queryset) get() is return model object , filter() is return queryset i want move two type -
Python Django get distinct queryset by month from a DateField
class MyModel(models.Model): TRANSACTION_TYPE_CHOICES = ( ('p', 'P'), ('c', 'C'), ) status = models.CharField(max_length=50, choices=TRANSACTION_TYPE_CHOICES, default='c') user = models.ForeignKey(User, db_index=True, on_delete=models.CASCADE,related_name='user_wallet') date = models.DateField(auto_now=True) amount = models.FloatField(null=True, blank=True) def __unicode__(self): return str(self.id) I am a fresher in Python django and have a little knowledge in Django Rest Framework. I have a model like above and I want to filter the date field by month and get distinct queryset by month.....Is there any default way to do this... Thanks in advance -
when celery 4.0 connect to the rabbitmq to be backend, have connection error, handshake timeout
In my environment, I try to use Django with Celery to do the background task with rabbitmq. everything just works fine in the development environment, when I deploy our web service to client environment. The celery has a connection issue with rabbitmq. I already do a lot of online searches, try to BROKER_POOL_LIMIT = None to the setting file in Django, and increase the handshake_time in rabbitmq.conf. but still not working. anyone have any idea what could cause that kind of problem? -
How to create a Django Model for a checklist app where the SubTask can be added at Runtime according to the Requirement?
Basically, Auto generated Charfield that can be created or deleted as per the requirement of the user of Checklist App to add or remove 'n' number of subtasks where n>1. -
Django-Pycharm: Deployment option port number removal
A project of mine required me to host a website through Pycharm onto a local server and i managed to do that by going to the settings option under file, Deployment option, Local files and I selected the path to my project. I managed to get my project running on the server. The URL is `172.16.50.67:8000' at the moment How do i remove the port number and just run it on 172.16.50.67 instead of 172.16.50.67:8000? I would have used wamp/IIS to host it but it used to give me a lot of errors and thus This was my last option. -
Django calculate total price with tax
My math kind of sucks at the moment. I actually have simple calculation that needs to be done for my invoices application. The models are: class Product(models.Model): name = models.Charfield(max_lenght=50) price = models.DecimalField(decimal_places=2, max_digits=10) tax = models.PositiveIntegerField() Class Invoice(models.Model): client = models.ForeignKey(Client) date = models.DateField() class Specification(models.Model): invoice = models.ForeignKey(Invoice) product = models.ForeignKey(Invoice) timestamp = models.DateTimeField(auto_now_add=True) I need to have clean way to calculate the total price of the products + the tax to show on the InvoiceDetail template. What is the best way to calculate this? -
Bootstrap grid output different than expected
I have been trying to make this work with bootstrap grid to display my contents but things doesn't work when I try to add certain features to it. I think I am doing the things right, but since I am new to bootstrap I think I might not know something which the community can help me with. Here is the code for reference, than I will explain what I'm doing and what I want to achieve. Please don't get scared to see the code, its very easy to understand, cooperate. This is my snippet from base.html <div class="container"> <div class="row"> <div class="col-lg-12 col-xs-12 col-md-12"> <!-- 1 Adding Site Title --> <center><h1 class="Heading"><a href="/" style="text-decoration: none !important">Suman Mishra</a></h1></center> <hr> </div> <!--Closing Col --> </div> <!--Closing Row --> <div class="row"> <div class="col-lg-12 col-xs-12 col-md-12"> <center> <ul> <li> <a href="" class="wide" style="text-decoration: none !important">Home</a> </li> <li> <a href="" class="wide" style="text-decoration: none !important">Categories</a> </li> <li> <a href="" class="wide" style="text-decoration: none !important"> Nothing to display</a> <li> <a href="" class="wide" style="text-decoration: none !important"> Bhai Kuch bhi</a> </li> </ul> </center> <hr> </div> <!-- Closing Column --> </div> <!-- Closing Row --> <div class="row"> <div class="col-md-9"> {% block content%} {% endblock %} </div> <!-- Closing Column --> <div … -
Adding replies to comments. All replies post only to the first comment
I am new to Django so please forgive any silly mistakes in code or logic. Intro I am making an app. Where a User can ask a Question and other users can answer. There can be unlimited answers to 1 Question, Users can also comment on answers. Problem Now the problem is If a question has 5 answers and no matter which answer you comment on, The comment appears on only the 1st Answer. The problem is in my views models.py class Reply(models.Model): answer = models.ForeignKey(Answer, related_name='replies') replier = models.ForeignKey(User, related_name='repliers') comment = models.CharField(max_length=1000) Views.py class ReplyCreate(LoginRequiredMixin, CreateView): model = Reply form_class = ReplyForm def form_valid(self, form, *args, **kwargs): self.object = form.save(commit=False) print(self.object) # This print works fine self.object.replier = self.request.user print(self.object.replier) # This print works fine pk = self.kwargs.get('pk') print(pk) # This is where the problem is, this always prints "1" no matter which answer I comment on self.object.answer = get_object_or_404(Answer, pk=pk) print(self.object.answer) self.object.save() return super().form_valid(form) What am I doing wrong. How do I call the pk of my Answer -
Processing Payments Via Paypal in Django-Oscar
I am trying to set up a basic e-commerce site using Django Oscar and am having difficulties. The majority of the problem has to do with the absence of examples of how to hook up meaningful (think Paypal, Stripe, Braintree) methods of payment and presence of obscure ones of which I have never heard before. Either way, I am attempting to use django-oscar-paypal and follow its documentation. The Paypal Express part seems to work in that the button shows up and something akin to check out and processing happens. However, if I choose to proceed with checkout in a regular way (with hopes of paying with a card), I am taken to the following page (the message in parentheses is mine) Which is a product of the following template: {% extends "checkout/checkout.html" %} {% load i18n %} {% block title %} {% trans "Payment details" %} | {{ block.super }} {% endblock %} {% block checkout_nav %} {% include 'checkout/nav.html' with step=3 %} {% endblock %} {% block checkout_title %}{% trans "Enter payment details" %}{% endblock %} {% block order_contents %}{% endblock %} {% block shipping_address %}{% endblock %} {% block shipping_method %}{% endblock %} {% block payment_method %}{% endblock … -
Where to place script in API Django Rest Framework
I've already developed a django app with python script running at the views. I have my create view where the user inputs some variables and then i pass new variables from these, using numpy, pandas, functions, scipyoptimize, to context in the resultview (detailview). Example: I ask to the user to input three values and then i use this three values to sum/multiply/divide/mod/abs and then i display the table in pandas with this results, creating a pandas.df_to_html() instance and overriding the context at ResultView(DetailView) and passing them to a template using jinja notation. That works absolutely well. My question is, I'm trying to do the same but with an REST API in DRF, where's the best place to put this script? Serializers or Views, and how can I do that, I've been searching a lot and I can't find anything similar. When i curl the ..../1/detail, i want to be able to catch new context based on the variables from the database. -
django interactions between users in real time
I'm currently making a django web-site, in which users could make data exchange with two-sided confirmation. For example: User A wants to exchange bios with user B. Both bios are stored in database. User A alerts user B about his intent, user B accepts, they both recive information about length of bio(also stored in databas), based on that info they decide upon further exchange, if both of them confirm, bio of user A is shown to user B and vice versa. The questions I have: What is the best(most simplistic) way to alert user B when user A sends a request to my server? What is the best way to check confirmations in real time? How could i implement a file exchange in similliar fashion, just instead of length of a bio, using file size? I would appreciate help with any of this questions, as well as advices on general approach of cross-user interaction using django and databases. also, here's part of my models.py for this app: from django.db import models class BIO(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE) biography = models.TextField() -
asyncio in django view
result = loop.run_until_complete(asyncio.gather(*tasks)) File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/tasks.py", line 596, in gather fut = ensure_future(arg, loop=loop) File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/tasks.py", line 518, in ensure_future loop = events.get_event_loop() File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/events.py", line 676, in get_event_loop return get_event_loop_policy().get_event_loop() File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/events.py", line 584, in get_event_loop % threading.current_thread().name) class TemplateTeamView(LoginRequiredMixin,TemplateView): template_name = 'of/template_team.html' def get_context_data(self, **kwargs): loop = asyncio.get_event_loop() tasks = [of._get_detail_template(i) for i in [1,2,3,4]] result = loop.run_until_complete(asyncio.gather(*tasks)) context = super(TemplateTeamView, self).get_context_data(**kwargs) context.update({"result": result}) return context how to design calling multi APIs to gather result before render template? -
saving Base64ImageField using Django Rest saves it as Raw image. How do I convert it to a normal image
I have 5 image fields in my model , imageA, imageB, imageC, imageD and imageE I am trying to save the image in the following manner images=["imageA","imageB","imageC","imageD","imageE"] for field in images: if field in serializer.validated_data: content = serializer.validated_data[field] dict = {field : content} modelJob.objects.filter(id=modjob.id).update(**dict) However the images saved in the imageField of the model are raw and not an actual image. How can I fix this ? This is what my serializer looks like class Serializer_Custom_RX(serializers.ModelSerializer): imageA = Base64ImageField(max_length=None, use_url=True, ) class Meta: model = modelTest fields = [ 'title', 'zip', 'imageA', ] -
Django: Best way to give Stripe ACH deposit verification Error
I'm working on Stripe ACH verification where I have the user input two numbers corresponding to deposits in their bank account. What's the best way to error out the html field when they enter a value that isn't a integer between 1 and 99. Should this be done javascript side (jquery?) or in my view. My gut tells me that it needs to be done in the view, but I don't know how to relay an error message back to the user. Should I create a form for this? I wouldn't think so since I'm not saving things to the database. Thoughts? My View in Django def ach_payment_verify_updateview(request): request.stripe_id = request._post['token'] print('hi') try: if not isinstance(request._post['deposit_1'], int): ### some kind of error message here print(request._post['deposit_1']) print(request._post['deposit_2']) My current javascript code. document.querySelector('form.ach-payment-verify-form').addEventListener('submit', function(e) { e.preventDefault(); var nextUrl = paymentForm.attr('data-next-url'); var deposit_1 = document.getElementById('deposit-1').value; var deposit_2 = document.getElementById('deposit-2').value; stripeDepositHandler(nextUrl, deposit_1, deposit_2) }); function stripeDepositHandler(nextUrl, deposit_1, deposit_2){ var paymentMethodEndpoint = '/billing/ach-payment-verify/create/' var data = { 'token': 'ba_1CWoJSFAasdfafsdReMae', 'deposit_1':deposit_1, 'deposit_2':deposit_2, } $.ajax({ data: data, url: paymentMethodEndpoint, method: "POST", success: function(data){ var successMsg = data.message || "Success! Your account has been verified." $("form.ach-payment-verify-form")[0].reset(); if (nextUrl){ successMsg = successMsg + "<br/><br/><i class='fa fa-spin fa-spinner'></i> Redirecting..." //<i … -
AWS Elastic Beanstalk health check issue
First I apologize for not being familiar with English. My web application is Django and web server use Nginx, use Docker image and Elastic Beanstalk to deployment. Normally there was no problem, but as the load balancer expands EC2, my web server becomes 502 Bad Gateway. I'm checked Elastic Beanstalk application logs, about 16% of the requests returned 5xx errors, at which time the load balancer expands EC2, causing the web server to transition to the 502 Bad Gateway state and the Elastic Beanstalk application to the Degraded state. Is this a common problem when the load balancer performs a health check? If not, can I tell you how to turn off the Health Check? I will attach a capture image for your help. enter image description here -
How to create an in instance using HyperlinkedModelSerializer by just providing the url of the nested HyperlinkedModelSerializer fields?
I am trying to create an instance of a model which has all its fields to be the related fields. class LearnerQuestionAnswer(models.Model): quiz_question = models.ForeignKey(Quiz_Question, on_delete=models.CASCADE) learner = models.ForeignKey(Learner_Model, on_delete=models.CASCADE) chosen_option = models.ForeignKey(Answer_Options, related_name="chosen_option", default=None, on_delete=models.CASCADE, blank=True, null=True) For this model I have created the following serializer:- class LearnerQuestionAnswerSerializer(serializers.HyperlinkedModelSerializer): quiz_question = Quiz_QuestionSerializer() learner = Learner_ModelSerializer() chosen_option = Answer_OptionsSerializer() class Meta: model = LearnerQuestionAnswer fields = ('quiz_question', 'learner', 'chosen_option') All the nested serializer's are as well HyperlinkedModelSerializer. I want to create an instance of this model by just providing the urls of the related fields like for example consider the following POST method:- { "quiz_question": "http://localhost:8080/api/registration_quiz_questions/83/", "learner": "http://localhost:8080/api/registration_learners/3/", "chosen_option": "http://localhost:8080/api/registration_answer_options/218/", } Is this possible an how? -
Q&A model with comments for Q and A's like StackOverflow The comments are repeating on both
Hi Djangonauts I am new to Django. Please forgive any silly mistakes in code or logic I am building a app like StackOverflow in my project, where a users and ask Questions and Other users can answer those questions. I also have a comment section on both of them just like StackOverflow. That is, other users can comment on the question or comment on the answers. Now the problem is If my Question has 5 answers. If I leave a comment on 1 answer it repeats on all 5 answers. Also the same with question. If I leave a comment on 1 question. All Question gets the question comment Example of Error: Question: This is a Question Answer 1: This is the 1st answer Comment 1: this is a comment to Answer1 Answer 2: This is the 2nd answer Comment 1: this is a comment to Answer1 # This should not be here but it is Answer 3: This is the 3rd answer Comment 1: this is a comment to Answer1 # and it repeats for every answer Below is my model: class Question(models.Model): user = models.ForeignKey(User, related_name='questions') title = models.CharField(max_length=250, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) message = models.TextField() def …