Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'invalid key error' recaptcha, is my views.py wrong?
Below I have a signup form. I get no errors in python shell, I have tried to do this with the def signup(request) part but I get 'request' not defined. My keys are correct, I have checked. This makes sense to me, but I am confused as to how to pass this 'request' on correctly in views.py class SignUp(generic.CreateView): form_class = forms.UserCreateForm success_url = reverse_lazy('login') template_name = 'signup.html' def signup(request): recaptcha_response = request.POST.get('g-recaptcha-response') data = { 'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY, 'response': recaptcha_response } r = requests.post('https://www.google.com/recaptcha/api/siteverify', data = data) result = r.json() if result['success']: form.save() messages.success(request, 'Success') else: messages.error(request, 'Invalid reCAPTCHA. Please try again.') -
How to make website login page using Python in the back end?
I would like to create a simple website where the user can select create user or login and then is able to either create a username with an email and hashed password stored in a hash table using SQL or some sort of code to connect the front end to the back end and access data stored somewhere. I am not sure what all this would involve. If someone could point to some online open sources which would provide growth in python back end development, that would be great. -
Django or Flask! Which one is better for high traffic site (need to convert from php to python)?
I need to convert my site from PHP to Python. So, I need to choose python framework Django or flask. I searched for this a lot. Both have pros and cons. Site follow MSA. so it separates many microsites. But If all together are large scare and high traffic. SO, some of the reason flask is better, some Django is better. I wanna make some use flask some Django. But need to choose one. If think only performance(speed/db connect/secure...), what is better? -
Filter a query set in Django based on aggregate of one of its fields for a foreign key?
Consider the following two models, Worker and Invoice: class Worker(models.Model): name = models.CharField(max_length=255) class Invoice(models.Model): worker = models.ForeignKey( 'Worker', on_delete=models.CASCADE) amount = models.DecimalField(max_digits=10, decimal_places=2) I would like to perform a query for only those Invoices for which the total (the sum of amounts) is greater than zero for a given Worker. Basically, I would like to define a get_payable_invoices() function which returns a Queryset such that the test passes: from decimal import Decimal from django.test import TestCase from django.db.models import Sum from myapp.models import Worker, Invoice def get_payable_invoices(): return Invoice.objects.filter( worker__in=Worker.objects.annotate(Sum('invoice__amount')))\ .filter(invoice__amount__sum__gt=0) class PayableInvoicesTests(TestCase): def test_get_payable_invoices(self): worker1 = Worker.objects.create(name="John Doe") invoice1 = Invoice.objects.create( worker=worker1, amount=Decimal('100.00')) invoice2 = Invoice.objects.create( worker=worker1, amount=Decimal('-150.00')) worker2 = Worker.objects.create(name="Mary Contrary") invoice3 = Invoice.objects.create( worker=worker2, amount=Decimal('200.00')) self.assertEqual(get_payable_invoices().count(), 1) self.assertEqual(get_payable_invoices().first(), invoice3) The current implementation doesn't work, though, and returns a django.core.exceptions.FieldError: Cannot resolve keyword 'invoice' into field. Choices are: amount, id, worker, worker_id It seems that although the objects returned when iterating over the query set do have the invoice__amount__sum attribute, it cannot be used in filter() in this way. It seems to me that I should formulate the query along the lines of the one in https://docs.djangoproject.com/en/2.2/ref/models/expressions/#using-aggregates-within-a-subquery-expression, but I'm struggling to adapt that example to mine because … -
Django rest-framework Social Oauth2: How to set permission classes per view or method
I'd like to set permission per view or method using Django rest-framework Social Oauth2. How should I set permission to each view or method? At first, I've tried to set 'DEFAULT_AUTHENTICATION_CLASSES' in settings.py. But some method doesn't need authentication, I'd like to set AllowAny. So, I've tried to set decorator to the method but it doesn't work. settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', 'rest_framework_social_oauth2.authentication.SocialAuthentication', ), } views.py @permission_classes([AllowAny, ]) @api_view(['POST']) def someMethod(request): return foo -
How to set django HttpResponse content after create?
In flask ,we can use response.set_data(r), but how to do this in Django? response = HttpResponse(text) -
How do I customize admin add/edit page
I'm new to Django(working on 1.5), I've created a new model Ad and registered it in Django Admin, when I add a new Ad on the admin page, instead of manually filling out each field, how can I do the following scenario: Get json from an api endpoint(a list of Ads) and render them on the add/edit page as a select list, I'm using model form so I guess I need an extra custom field for it? Also where should I put the logic calling api ? when I select one of the Ad, it can fill out other fields of the Ad. my admin page: class AdAdminForm(forms.ModelForm): class Meta: model = Ad class AdAdmin(admin.ModelAdmin): form = AdAdminForm fieldsets = ( (None, { 'fields': ('name', 'price', 'contact') }), ) admin.site.register(Ad, AdAdmin) -
How do I convert seconds to hh:mm:ss in django template
So I have a dictionary called match. This has details of a match and one of the keys are game_time. If the game time is <= 10, the match is in draft. Else, I want to report the game time but the value its stored in is just in seconds. {% if match.game_time <= 10 %} drafting {% else %} {{match.game_time|date: "Z"}} {% endif %} Just gives me an error Could not parse the remainder: ': "Z"' from 'match.game_time|date: "Z"' any help appreciated -
infinite scrolling with jquery
I followed this tutorial:https://simpleisbetterthancomplex.com/tutorial/2017/03/13/how-to-create-infinite-scroll-with-django.html It works fine except for the infinite part. Instead of loading more content upon scrolling, it just puts a "more" link at the bottom of the page which loads more content upon being clicked. Here is my code: views.py: def home(request): numbers_list = range(1, 1000) page = request.GET.get('page', 1) paginator = Paginator(numbers_list, 20) try: numbers = paginator.page(page) except PageNotAnInteger: numbers = paginator.page(1) except EmptyPage: numbers = paginator.page(paginator.num_pages) return render(request, 'blog/home.html', {'numbers': numbers}) home.html: <div class="infinite-container"> {% for number in numbers %} <div class="infinite-item">{{ number }}</div> {% endfor %} </div> {% if page_obj.has_next %} <a class="infinite-more-link" href="?page={{ page_obj.next_page_number }}">More</a> {% endif %} <div class="loading" style="display: none;"> Loading... </div> <script> var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], onBeforePageLoad: function () { $('.loading').show(); }, onAfterPageLoad: function ($items) { $('.loading').hide(); } }); </script> I assume its because of the obvious hyperlink in home.html which is titles "more" but how can i change that so it add content automatically once i reach the bottom of the page instead of when i click the button? -
How to implement Django_moderation with django 2.2.3
I'm making a django project and want to add approval feature (edit or add) from a specific model.But i am getting confused with django_moderation doc. and is there any way to use it with django 2 I have read django_moderation got confused with their explanation. -
Ordering queryset by property of related model with another property equal to something
Let's say i have this model relationship: class Account(models.model): ... class Balance(models.Model): class Meta: verbose_name = u"Balance" verbose_name_plural = u"Balances" name = models.CharField(max_length=200, verbose_name=u"Currency", null=True, blank=True) count = models.FloatField(verbose_name=u"Count", null=True, blank=True) account = models.ForeignKey(Account, verbose_name='Account', on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.name I have the queryset of accounts, they all have the same amount of balances and balances have the same names but not the same counts. For example i have 3 accounts, and each account has only 2 related balances with names 'foo' and 'bar', but 'count' property in these balances may differ. How do i order account by 'count' property of its balance with name 'foo'? Also if possible would like to get solution for this problem but for filtering though i've made kludge for this already using for in so it's not that important. -
Django How to filter and sort queryset by related model
I have this model relationship: class Account: < ... fields ... > class Balance(models.Model): name = models.CharField(...) count = models.FloatField(...) account = models.ForeignKey(Account, related_name='balance') Let's say we have some number of accounts. I need to filter these accounts by balance__name and sort by balance__count. I need sorted accounts, not a list of balances. How do I do that? I don't even have any suggestions to find out a solution using iteration. -
What is causing SMTPAuthenticationError
I just deploy my application to an ubuntu server. I have ssl, so I made the respective modifications in my settings.py, it looks like this: EMAIL_BACKEND = 'django_smtp_ssl.SSLEmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 465 EMAIL_HOST_USER = 'email@gmail.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_USE_SSL = True I believe this is the Right configuration but when a email is sent I get something like: Traceback (most recent call last): File "/home/admin/Mefid/TransversalScripts/comunication.py", line 122, in send_email fail_silently=False, html_message=html_message) File "/home/admin/Mefid/venv2/lib/python3.7/site- packages/django/core/mail/__init__.py", line 60, in send_mail return mail.send() File "/home/admin/Mefid/venv2/lib/python3.7/site- packages/django/core/mail/message.py", line 291, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/admin/Mefid/venv2/lib/python3.7/site- packages/django/core/mail/backends/smtp.py", line 103, in send_messages new_conn_created = self.open() File "/home/admin/Mefid/venv2/lib/python3.7/site-packages/django_smtp_ssl.py", line 14, in open self.connection.login(self.username, self.password) File "/usr/lib/python3.7/smtplib.py", line 730, in login raise last_exception File "/usr/lib/python3.7/smtplib.py", line 721, in login initial_response_ok=initial_response_ok) File "/usr/lib/python3.7/smtplib.py", line 642, in auth raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbvc\n5.7.14 YlL_uB0GK_TLI557gRMyVYqHRr9iVrfj5mJ3jaEuyHjSmmevxT5-8ocIMMRh0BVOPqnrCR\n5.7.14 prX-jJCduiyPcF2RrYAWJkg4A5jUboKUMLzBEyz72VWQLPYiOKxFcZ5SBvrICb> Please\n5.7.14 log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 i11sm7651758oia.9 - gsmtp') ''' I followed a guide here https://github.com/bancek/django-smtp-ssl is there anything else I should be aware of? Thanks for your help. -
Callback with Boto3, Showing Upload Progress
I am in a situation with a document storage feature in a Django/Python application (using Boto3) where I also need to provide the user with information on the progress of an upload. The methods I have seen which use straight JS are not all universally 'usable' across browsers, what I want is to be able upload a file using Boto3 and then also show an upload progress bar in my Django template. Looking at the docs here: https://boto3.amazonaws.com/v1/documentation/api/latest/_modules/boto3/s3/transfer.html I am not understanding how it would be possible to show building progress of the upload calling ProgressPercentage() from within a template. How would I go about displaying the actual progress for my user in a template using Boto3? class ProgressPercentage(object): def __init__(self, filename): self._filename = filename self._size = float(os.path.getsize(filename)) self._seen_so_far = 0 self._lock = threading.Lock() def __call__(self, bytes_amount): # To simplify we'll assume this is hooked up # to a single filename. with self._lock: self._seen_so_far += bytes_amount percentage = (self._seen_so_far / self._size) * 100 sys.stdout.write( "\r%s %s / %s (%.2f%%)" % ( self._filename, self._seen_so_far, self._size, percentage)) sys.stdout.flush() transfer = S3Transfer(boto3.client('s3', 'us-west-2')) # Upload /tmp/myfile to s3://bucket/key and print upload progress. transfer.upload_file('/tmp/myfile', 'bucket', 'key', callback=ProgressPercentage('/tmp/myfile')) -
Best alternative to tkinter GUI in Django
I've created a very simple GUI in tkinter which is basically a bird's eye view of a warehouse, in which you could hover over particular areas to get some data from database or press into it to get some more details. What I didn't know while creating it is that I won't be able to call it with Django (and I guess any other framework). Do you have any suggestion what's the most optimal way to do above task? -
Why is my href tag directing to a different function?
I am working on getting a website up and running with Django 2.2. I am attempting to get a sidebar put together and I figured the first step is make sure I am linking to the right place and then go from there. On my html template I have links so that students can view assignment details and on the sidebar there should be links so students can go to course pages. Currently the href is using the views 'assignment_page' function instead of the 'course_page' function. I have researched into what I should be doing inside the anchor href tag and I feel like I am doing it right as the assignment links work. Looking below you can see the structure of the href tag for the assignment and the course links are the same but the course link doesn't point in the right place. Here is the html template: This the the course link I discussed {% for course in student_courses %} <div> <a href="{% url 'view_course' course.title %}"> {{ course.title }} </a> </div> {% endfor %} Here is the assignment link {% for assignment in course_assignments %} <div> <a href="{% url 'view_assignment' assignment.title %}"> {{ assignment.title }}</a> <p>Due … -
(1045, "Access denied for user)
I am trying to connect my Django app on Heroku to an external MySQL database server of another domain. I have already set up the config variable but the Heroku app doesn't seem to be using them. I get the error below. It seems the Heroku app is using an amazonaws host and not the one I have specified on the DATABASE_URL. Please help (1045, "Access denied for user 'dekacoke_dekate'@'ec2-3-85-219-69.compute-1.amazonaws.com' (using password: YES)") -
How to filter a model in django?
So i have a model called Partner. A business is a partner. I have a foreignkey field who takes self as a parameter to create choices. What i want to do is to go through all the created partners and filter out ones that are parent companies. I was thinking of having a boolean that says is_parent. How do i go about this can i search for the boolean in the database and create a choicefield or something with it so i can get a list of parent companies? I have tried to filter through my result but that did not work as expected. parent = models.ForeignKey( 'self', blank=True, help_text="Parent Company name (if necessary)", null=True, on_delete=models.CASCADE, max_length=200 ) -
'QuerySet' object has no attribute 'vulnerability_slug
i getting mentioned problem while declaring below statement series_urls[m] = part_one.vulnerability_slug this is my model class vulnerability(models.Model): vulnerabilty_date = models.DateTimeField('date published', default=datetime.now) vulnerability_doc = models.FileField(upload_to='documents/%Y/%m/%d/', default="") member_name = models.ForeignKey(TeamMember, default=1, verbose_name="team", on_delete=models.SET_DEFAULT) vulnerability_action = models.CharField(max_length=200, default="no action needed") vulnerability_slug = models.CharField(max_length=200, default=1) def __str__(self): return self.vulnerability_action works well till part but when i include part.vulnerability_slug i am getting error. -
How do I create a confirmation form prepopulated with data collected from an uploaded image in Django?
I'm using Tesseract to scrape text from an image the user uploads. The program currently stores the largest number found in the image and stores it in the database. I'm trying to redirect to a confirmation form after the user uploads an image. The confirmation form should be prepopulated with largest dimension for the user to edit. Should I create a new view for the confirmation form? #views.py def image_view(request): if request.method == 'POST': form = partForm(request.POST or None, request.FILES) if form.is_valid(): data = request.POST.copy() image_file = request.FILES.get('image') text_content = pytesseract.image_to_string(Image.open(image_file)) Serial_number = request.POST.get('Serial_number') x = Component(Serial_number = Serial_number,text=text_content, image=image_file,dimension1=max(new_list)) form.save() return redirect('confirmation_form') else: form = partForm() return render(request, 'home.html', {'form': form,}) #forms.py class editForm(forms.ModelForm): Serial_number = forms.CharField(max_length=20) class Meta: model = Component fields =['Serial_number','image','text','dimension1','Good_Candidate'] -
How to change models name in django from django admin interface?
using "verbose_name" we can change the models name, but here i want this process to be kind of dynamic, like from inside admin panel itself, it will be renamed, so that it will not have to be hard coded. can anybody suggest any solution? -
How can I return a template ( along with a needed argument ) with a custom template filter?
I want to use a custom template filter which will eventually return (redirect to) url of one of the pages that I have in the project along with the needed argument. Is there any way to do that ? (couldn't find anything) Thanks in advance def show(list) -> str: return {'%url 'app:list' list %'} <a href={{original_url|show}}}> -
View an Image Using Django CreateView Before Submitting
I have a Django CreateView that works as expected. I allow the user to attach a photo and then after they click Submit, the view captures the image as expected. However, I am trying to figure out if there is a way, using CreateView, to show the image that has been captured. As of right now, it shows the file name, but I am trying to get it to show the image instead. I tried a variation of this SO question, but it is not for CreateView and I can't figure out how to translate it. Render image without saving Here is my simple example, that works as expected. My Model... class NewAuthor(models.Model): image = models.ImageField(upload_to='images/',default='images/pic.jpg') My view.... class CreateNewAuthorView(CreateView,NeverCacheMixin): model = NewAuthor form_class = CreateNewAuthorForm template_name = 'create_new_author.html' My form... class CreateNewAuthorForm(forms.ModelForm): class Meta: model = NewAuthor fields = ['image',] My HTML... <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="picture"> {{ form.image }} </div> How can I incorporate code that will allow the image that was uploaded to actually be displayed before the user hits submit? Thanks in advance for any suggestions. -
How to access field values of an object from a ModelMultipleChoiceField, from within a template?
I have a database of television channels that I am displaying using a Django form with a ModelMultipleChoiceField and a CheckboxSelectMultiple widget. The template renders fine, but how do I access fields of the individual objects that are part of the ModelMultipleChoiceField field of the form? Channel model class Channel(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name This is the form class ChannelForm(forms.Form): channels_list = forms.ModelMultipleChoiceField(queryset=Channel.objects.all().order_by('name'), widget=forms.CheckboxSelectMultiple) This is how I was trying to access the 'name' field of each channel in the template by doing {{ channel.name}}. {% for channel in form.channels_list %} {{ channel }} accessing: {{ channel.name }}<br> {% endfor %} When it renders it simply says "accessing: " without the channel name -
How to run daphne in localhost with https and mkcert
I am trying to run a django-channels project locally using https (the app has a facebook login that requires https). I have followed the instructions for generating a key and certificate using mkcert ( https://github.com/FiloSottile/mkcert ) and have attempted to use the key and certificate by running daphne -e ssl:443:privateKey=localhost+1-key.pem:certKey=localhost+1.pem django_project.asgi:application -p 8000 -b 0.0.0.0 The server seems to be starting OK however when I try to visit https://0.0.0.0:8000 nothing happens and eventually I get a 'took too long to respond' message. No new output is added to the standard daphne output that appears when I start up the server: 2019-07-16 19:23:27,818 INFO HTTP/2 support enabled 2019-07-16 19:23:27,818 INFO Configuring endpoint ssl:8443:privateKey=../sec/localhost+1-key.pem:certKey=../sec/localhost+1.pem 2019-07-16 19:23:27,823 INFO Listening on TCP address 0.0.0.0:8443 2019-07-16 19:23:27,823 INFO Configuring endpoint tcp:port=8000:interface=0.0.0.0 2019-07-16 19:23:27,824 INFO Listening on TCP address 0.0.0.0:8000 Can anyone help with this?