Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django SMTP setup using gmal with custom `from`
I want to reproduce the following test case from backend email from Django built using Gmail servers , however I keep getting the owner email in to, and from from my feedback form . I am using the following send_email setup send_mail(subject, message, from_email, ['xxx@xxx']) desired output Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: You have a new aaaaaaa@gmail.com from support From: xxxx@gmail.com To: support@demo.io Date: Mon, 22 Jun 2020 02:59:30 -0000 Message-ID: <159279477011.24057.7925107016621366148@xxxxx> -
Run "git pull" for a Django project running on Windows Server 2016 IIS
My current set up has a Django project running on Windows 2016 IIS. The project is hosted on GitHub for collaboration and I would like to set up a GitHub webhook so whenever there's a push to master branch from any of the collaborators, the IIS Server will run a "git pull" to update the project on the server. What is normally the setup for this? What I have tried so far is to create an endpoint in the Django project, this endpoint whenever called will run Python subprocess to run "git pull" command in the project itself. However, whenever I run it, it get a 500 response from IIS. -
Reverse url not found
what is this error? AttributeError at /size/uspolo10/ 'str' object has no attribute 'get'a valid view function or pattern name. I got this error. I can't understand this situation that 'str' and 'get'. Please help me to solve this error. views.py class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() tag = models.CharField(max_length=10,blank=True,null=True,default='New') discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() description = models.TextField() image = models.ImageField() schargeinc = models.FloatField(blank=True, null=True,default=-1) size = models.ForeignKey(Sizes_class, on_delete=models.CASCADE, null=True, default=False) selcsize = models.CharField(default=False,null=True,blank=True,max_length=25) def __str__(self): return self.title def get_add_cart_wsize_url(self): return reverse("core:size", kwargs={ 'slug': self.slug }) def get_absolute_url(self): return reverse("core:product", kwargs={ 'slug': self.slug }) def get_add_to_cart_url(self): return reverse("core:add-to-cart", kwargs={ 'slug': self.slug }) def get_remove_from_cart_url(self): return reverse("core:remove-from-cart", kwargs={ 'slug': self.slug }) size.html <form method="POST" action="." > {% csrf_token %} <div id="exampleModalPopovers" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="exampleModalPopoversLabel"> <h5>Select a size</h5> {% for size in object.size.sizes_choice %} <div class="custom-control custom-radio"> <div class="custom-control custom-radio"> <input id="{{ forloop.counter }}" name="sizes_choice" value="{{ size }}" type="radio" class="custom-control-input" required> <label class="custom-control-label" for="{{ forloop.counter }}">{{ size }}</label> </div> </div> {% endfor %} </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary btn-md my-0 p"> Set </a> </div> </div> </form> urls.py path('size/<slug>/', size, name='size'), -
371 dinh bo linh-p26-quan binh thanh-tp ho chi minh
namespace Example.Namespace1 { public partial class ImportantClass { protected partial class Nested1 { // I can finally start writing code here public int AddOffset(int offset) { // Code inside of a method } public string ID{ get; protected set; } } } } -
I am using mixins CreateView... and having issue in pre populating the slug field
I am using Django model-specific CreateView, UpdateView and DeleteView. For my CreateView i have some fields = ['subject', 'title', 'slug', 'overview'] on create.html page including slug field which should be populated automatically based on the title field as the user types in. Also i am using the same template for create and edit operation. In the Admin panel i can use prepopulated_fields = {'slug': ('title',)} to get this done and as the user types in this field generates the slug. Here is the related section from views.py class OwnerCourseMixin(OwnerMixin, LoginRequiredMixin, PermissionRequiredMixin): model = Course fields = ['subject', 'title', 'slug', 'overview'] success_url = reverse_lazy('manage_course_list') class CourseCreateView(OwnerCourseEditMixin, CreateView): permission_required = 'courses.add_course' Any help would be appreciated. -
EDIT A FORM IN DIFERENTS TEMPLATE FOR EACH SITUATION DJANGO
I have a model called "" and the same its used to do a form with ModelForm. How you can see, i've done all the views to insert, edit, delete and see data in each template. But, I would like to edit this form in these way: The user will submit the form without fill a unique field After the user submit, I will have a template to show the informations and I would like to have something to approve or reject the form(I thought in a boolean field, with default=false) if I approve: I would like to display the same form with the fields that has already filled when the user submited, but with these fields just readonly and the another field that is empty I would like that the user could fill. After the user fill these field that was empty, he would save the forms and would be dislplayed in another template where I can accepet the answer and "close" the the cicle of the form. There is a way to do this with python/django? maybe just doing a new view. my models: class RegistroFalha(models.Model): nome = models.CharField(max_length=255) tag = models.TextField() status = models.CharField( max_length=50, default='Aberto', choices=( … -
How can i connect webcam stream from javascript to django backend?
I created a djagno website which use OpenCV to connect with webcam and stream it in browser locally and it worked. But when I uploaded the website on Heroku server, it stopped working. So I used javascript to connect the webcam. But the stream I got from javascript did not seems to be connected with my backend. So how can I connect webcam accessed using javascript and send the stream to Django backend and after processing display it back on frontend? Javascript code var video = document.querySelector("#videoElement"); if (navigator.mediaDevices.getUserMedia) { navigator.mediaDevices.getUserMedia({ video: true }) .then(function (stream) { video.srcObject = stream; }) .catch(function (err0r) { console.log("Something went wrong!"); }); OpenCv code class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) def __del__(self): self.video.release() def get_frame(self): success, image = self.video.read() ret, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes() I know these are a lot of question, so I am expecting a pathway and keywords from where I can learn these concepts. At least give me some direction so I can learn and accomplish this. -
How to restrict access to certain pages on to admin user in Django
I have created a Control Panel App to manage the newsletter of the project, so there are pages for which the admin can manage the newsletter, not the Django admin. How can I restrict the access of these pages to be only to admin and show a 404 error if a normal user is trying to access the link? I am looking for the most secure way to do this Here is the newsletter app views.py def control_newsletter(request): form = NewsletterCreationForm(request.POST or None) if form.is_valid(): instance = form.save() newsletter = Newsletter.objects.get(id=instance.id) if newsletter.status == "Published": subject = newsletter.subject body = newsletter.body from_email = settings.EMAIL_HOST_USER for email in newsletter.email.all(): send_mail(subject=subject, from_email=from_email, recipient_list=[ email.email], message=body, fail_silently=False) context = { "form": form, } template = 'control_newsletter.html' return render(request, template, context) def control_newsletter_list(request): newsletter = Newsletter.objects.all() paginator = Paginator(newsletter, 10) page = request.GET.get('page') try: items = paginator.page(page) except PageNotAnInteger: items = paginator.page(1) except EmptyPage: items = paginator.page(paginator.num_pages) index = items.number - 1 max_index = len(paginator.page_range) start_index = index - 5 if index >= 5 else 0 end_index = index + 5 if index <= max_index - 5 else max_index page_range = paginator.page_range[start_index:end_index] context = { "items": items, "page_range": page_range } template = "control_newsletter_list.html" return … -
I'm using Google drive storage API for my django website
I have uploaded.the document using Google drive storage api but Im not able to locate the backend storage..im using json key for it... please help.me on it -
Using cron.yaml along with app.yaml to run python files
I'm very new to Django. I have a working prototype of my app that basically gathers tweets using Twitter's API. All this works fine locally (localhost:8000). I recenly deployed my app to Google App Engine using their SDK and everyhting works fine. The only problem I'm having is needing a script to run every so often to update what tweets to display to user. From what I understand, cron.yaml will allow a script to be called periodically. This file should be in the same directory as app.yaml (which it is), and my app is still using old data. Here's my code: app.yaml runtime: python env: flex entrypoint: gunicorn -b :$PORT trumps_tweets.wsgi runtime_config: python_version: 3 handlers: - url: / script: gatherTweetData.py # This sample incurs costs to run on the App Engine flexible environment. # The settings below are to reduce costs during testing and are not appropriate # for production use. For more information, see: # https://cloud.google.com/appengine/docs/flexible/python/configuring-your-app-with-app-yaml manual_scaling: instances: 1 resources: cpu: 1 memory_gb: 0.5 cron.yaml cron: - description: "refresh tweets" url: / schedule: every 30 mins The 'gatherTweetData.py' in the handlers section of the app.yaml is what gets all this new data for my app to display (this gatherTweetData … -
TypeError: __init__() got an unexpected keyword argument 'Label'
I'm using Django to create custom form from UserCreationForm model but the cmd show this error: TypeError: init() got an unexpected keyword argument 'Label' here my form.py: from django import forms from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User MALE = 'M' FEMALE = 'FM' SEX = (("", "----------"), (MALE, "Male"),(FEMALE, "Female"),) class RegisterForm(UserCreationForm): email = forms.EmailField() name_first = forms.CharField(Label=('Tên'), max_length=200, help_text='Vui lòng viết có dấu') name_lastnmidle = forms.CharField(Label=('Họ và Tên đệm'), max_length=200, help_text='Vui lòng viết có dấu') birthdate = forms.DateField(widget=extras.SelectDateWidget(years = range(1995, 1900, -1)), label='Ngày tháng năm sinh?', required = False) sex = forms.ChoiceField(widget=forms.Select(), choices=SEX, initial= "", label='Giới tính của bạn?', required=False) class Meta: model = User fields = ["usernname", 'name_lastnmidle', 'name_first', "birthday", 'sex', "email", 'password1', 'password2'] Thanks you -
How can I speed my css and js load speed on Django
I have you finished my first real project and I laughed it. However, the loading speed of the CSS and js takes some seconds. Both files are hosted on AWS, however, I do not think that is the reason for the speed problem. The thing is that the files are like 3MB I do not know if that is too much, I tried to minify them, but still, it takes some time. By the way, you should know that I bought my HTML templates, rich means that the CSS was not written by me. Any recommendations, I would really appreciate it. -
Sending emails using Gmail works locally but not on heroku (django)
Sending an email works locally with this settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST_USER = os.environ.get("EMAIL_USER") EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = 587 EMAIL_HOST_PASSWORD = os.environ.get("EMAIL_USER_PASSWORD") EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = os.environ.get("EMAIL_USER") However, when I try this live on Heroku I get this error: SMTPSenderRefused at /password_reset/ (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError p80sm1777250qke.19 - gsmtp', 'None') Does anyone know what the issue is and how to correct it? Thanks! -
Getting HTTP Error 403: Forbidden from sending a sendgrid email (django python)
I am trying to send an email using SendGrid in Django python. Here is my settings.py EMAIL_BACKEND = "sendgrid_backend.SendgridBackend" SENDGRID_API_KEY = os.environ.get("SENDGRID_API_KEY") SENDGRID_SANDBOX_MODE_IN_DEBUG = False EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = SENDGRID_API_KEY EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = os.environ.get("DEFAULT_FROM_EMAIL") In my application, this error comes up when doing password reset (I used the normal way Django recommends, nothing custom) and through my contact us page. This error occurs on both my local machine in development and live (heroku). Please let me know how to fix this. Thanks! -
Django model database look up
I am generating video files triggered by POST request and saving them programmatically into the django model below. How can I look up the uploaded file itself once uploaded to the database in a similar fashion to VideoUpload.objects(get)? I don't have users only guests. I am using hash-id-field so far however can change this. Models.py from django.db import models from django.conf import settings import hashlib from hashid_field import HashidAutoField class VideoUpload(models.Model): hashed_video_file_name = HashidAutoField(primary_key=True) name = models.CharField(max_length=40) videofile= models.FileField(upload_to='videos/', null=True) objects = models.Manager() -
how can i remove Unicode with double backslash
hi i have string like this s= "café & pâtisserie \\u201cin morad abc \u2013" how could i remove the Unicode without affecting the character in cafe word i tried this newstring = s.encode('ascii', 'ignore').decode('unicode_escape') and the output was "caf & ptisserie “in morad abc" any help please -
How to annotate with a custom function in Django?
I have an Event model, that, for the sake of simplicity only has a lat and lon FloatField(). From pythons native "geopy.distance" library, you can acquire the distance bewteen two coordinates like so: from geopy.distance import distance home = (33.28473, -117.20384) event = (33.829384, -117.38932) distance = distance(home, event).miles #returns a float In my application context I need to order all of the events by location. I attempted standard django annotation syntax: Event.objects.all().annotate(distance=distance( (F('lat'),F('lon')), home ).miles, output_field=FloatField()).order_by('distance') But I get the following error: QuerySet.annotate() received non-expression(s): <django.db.models.fields.FloatField>. Am I missing something here? -
Permission denied to create database testing views in Django
I've tried to test the views of my application in django but with no success. test_views.py class TestViews(TestCase): #test_main_view_GET test is displayed on the main url in main_tour_folder def test_destinations_GET(self): client = Client() response = client.get(reverse('destination')) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, 'tour_store/destinations.html') I got the message after running the command python manage.py test <app_name>: RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against t he production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the first PostgreSQL database instead. warnings.warn( Got an error creating the test database: permission denied to create database Where I don't understand how do I implement this test in my DATABASE in settings.py file. settings.py: #imports import os //To import the env.py secret_keys if os.path.exists('env.py'): import env import dj_database_url ... . . //postgress if 'DATABASE_URL' in os.environ: DATABASES = { 'default': dj_database_url.parse(os.environ.get('DATABASE_URL')) } else: #local print("Postgres URL not found, using sqlite instead") DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } I've seen in one article that I need to create a TEST with NAME dictionary within the DATABASES config but … -
Google Analytics 0 Pageviews
I am running a Django-Heroku app. I have connected it to Google Analytics with this code: <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-170094620-2"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-170094620-2'); </script> I put that after the on my base.html, and after the extends tag on every other page. When I go onto my site, Google Analytics says that there is one active user, but when I ask it how many pageviews I have ever had, it says 0. I may be making a stupid mistake, but please tell me what I need to do. Thanks! -
Is There A Way To Simplify/Streamline This Database Design
Im designing my first ever SQL database and am realizing just how difficult it is. I may have bitten off more than I can chew with my ambitions for this project, I didnt realize just how complex this was. I know its a massive ask, but Ill post my database design here and if anyone would like to make suggestions or answer any of the questions below it would be greatly appreciated. https://imgur.com/TC8BZmN A module is one class, a package is a group of many classes. Students can enroll in many individual classes, many packages of classes, or any combination. A module can has multiple Extra_Files containing downloadable files for each class (maybe 3 per class). A Module_Extra table will be required for each Module a student enrolls in (whether an individual Module or a Package of Modules). This will contain a boolean Completed which the Teacher will set as True when the Student completes a unit. Attached to Module_Extra is Extra_Files_Teacher and Extra_Files_Student. This is so Students and Teachers can upload multiple extra files and attach them to a Module (whether an individual Module or a Package of Modules). I am using Django. Students will view a page. One … -
Check if an entry with a unique constraint already exists
I have a Django model with this constraint. constraints = [ models.UniqueConstraint(fields=['provider', 'id'], name='unique_entry') ] I want to check if this already exists before attempting to save a new entry. I'm currently doing if Model.objects.filter(id=new_id, provider=new_provider).exists(): # Do stuff to prevent collision try: # try to save except IntegrityError: # handle error Even when I expect a collision it never seems to enter the if statement and instead attempts to save and predictably hits an IntegrityError. I can't seem to figure out how to determine if my new entry will cause an integrityerror before it actually does. -
Django issue with linking css to html
I am aware that there are other posts on this, however, none of the answers have helped fix my issue. I am making a django project and would like to use some basic css on my page, however it does not seem to be linking. The html file is in a folder called templates, while the css is in a folder called static. Here is what I used to link my css. <link rel="stylesheet" type="text/css" src='../static/style.css'> And my css file looks like this: body { background: black; } h1 { color: white; } Any help would be appreciated. -
django-recaptcha and django-csp nonce not working together
I am unable to get a django-csp's nonce="{{request.csp_nonce}} to show up inside of django-recaptcha's js_v3.html file. CSP_INCLUDE_NONCE_IN=['script-src'] CSP_SCRIPT_SRC = ["'self'", "https://www.google.com/recaptcha/", "https://www.gstatic.com/recaptcha/" ] CSP_FRAME_SRC = [ "https://www.google.com/recaptcha/" ] I tried: https://github.com/praekelt/django-recaptcha/issues/101 How to override external app template in Django? But no luck. I would appreciate if someone could help! -
Python NSInternalInconsistencyException error when using django
I am running into a NSInternalInconsistencyException when trying to run python in django. I am using a mac on catalina. I was following the simple tutorial below that uses marplotlib to generate graphs. i have followed the tutorial 3 separate times and all have produced the same error. My site says its ready to serve and then when i open the webpage python stops running an i et this error. i have tried on different browsers but still no luck. anyone know how to fix it? https://medium.com/@mdhv.kothari99/matplotlib-into-django-template-5def2e159997 Error: Application Specific Information: *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'NSWindow drag regions should only be invalidated on the Main Thread!' terminating with uncaught exception of type NSException abort() called -
Do I need to manually get new tokens for OAuth on a Django webapp?
I am a little confused right now. I am using googleapiclient to call the Docs API, google_auth_oauthlib.flow to handle the authorization flow, and google.oauth2.credentials only for, from what I can tell, the Credentials class. I need to authorize users for my app for non-short periods of time (days-months). I need to know if I need to manually refresh their tokens should they expire. The example Flask implementation here does not seem to manually need to refresh tokens if/when they expire. It says # Save credentials back to session in case access token was refreshed. in the test_api_request view as if credentials is automatically updated with a new token when the API is called by the object returned by build. Is this the case? A lot of the docs regarding these libraries have limited/vague information about how the token refresh works. If not, how do I know when the token has expired? Does the Credentials instance have an expiry field? How do I get a new token using the refresh token? Thanks