Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Setting up SendGrid using Django - User input "from_email"
All the Google searching in the world hasn't answered my question, so hoping someone can help me out. I have a Django based "Contact Me" webpage, which uses a form and the Django send_mail function. My app is hosted through Heroku. When I try to submit an email on my form, the form tries send_mail(subject, message, from_email, ["mypersonal@email.com"]) But I get the following error: (550, b'The from address does not match a verified Sender Identity. Mail cannot be sent until this error is resolved. Visit https://sendgrid.com/docs/for-developers/sending-email/sender-identity/ to see the Sender Identity requirements') This seems to imply to me that the "from_email" needs to be MY verified email on SendGrid, and not the email of the person trying to contact me? What am I missing? My goal is to have user submissions be sent to my @gmail.com address -
pycharm IDE warning on django doc: Expected type 'timedelta', got 'DateTimeField' instead python 3.7
in Django's doc is the following code snippet from django.db import models from django.utils import timezone import datetime class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) Pycharm highlights self.pub_date and shouts Expected type 'timedelta', got 'DateTimeField' instead How do I get rid of this and do things right? -
Form not saving new object to database
I have a form named ProtocolUserCredentialsForm. The main objective of processCredsForm is is to save the user input for the data_source_username, user, data_source, and data_source_password and assign it these creds in a new object in a database. Get displays the actual form and the html. For Post, it sends the user to a new page with form.html, by clicking submit on the first page (that has upgrade_user_creds.html and the form). When the user clicks the submit button, I need the credentials to save and for a new object to be created. I am just confused on why this is not creating a new ProtocolUserCredentials object in the database when I check admin? There isn't any errors coming up as well. class UpdateCredsView(TemplateView): template_name = 'update_user_creds.html' def processCredsForm(self, request): creds_form = ProtocolUserCredentialsForm(data=request.POST) context = {} obj = ProtocolUserCredentials() obj.user = creds_form['user'] obj.data_source = creds_form['data_source'] obj.data_source_username = creds_form['data_source_username'] obj.data_source_password = creds_form['data_source_password'] if creds_form.is_valid(): credentials = creds_form.save(commit=FALSE) credentials.save if not creds_form.is_valid(): if not (creds_form.non_field_errors()): context['form_errors'] = creds_form.errors context['form1'] = creds_form def get(self, request): context = {} allcreds = ProtocolUserCredentials.objects.all() context = {'form1': ProtocolUserCredentialsForm(), 'allcreds': allcreds} return render(request, 'update_user_creds.html', context) def post(self, request): post_data = request.POST context = {} context = {''} if 'submit_nautilus_creds' … -
Can't install Django to windows. It gives a error called "ModuleNotFoundError: No module named 'pip._vendor.packaging'"
I installed virtual Environment and entered this code py -m pip install virtualenvwrapper-win Then I created a virtual environment called "myproject_01" using this command. mkvirtualenv myproject_01 Then I tried to install Django using this command but it gives an error ""ModuleNotFoundError: No module named 'pip._vendor.packaging'". py -m pip install Django Please help me to fix this error.This is the error I get when I try to install Django -
Specify nested fields Django
I was looking into Django Rest Framework Documentation and I read about Nested Serialization, and how Depth could be used, there it specify the depth of relationships: class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ['id', 'account_name', 'users', 'created'] depth = 1 But doing in this way, all filds get the depth of 1, how can I specify wich field I want to be nested, like, for account_name, use a depth = 1, and for user a depth = 2 -
Forms fields respecting DRY django
Given some forms in Django (take the following for simplicity) class LoginRegisterForm(forms.Form): email = forms.EmailField(label="Email", max_length=100) password = forms.CharField(label="Password", widget=forms.PasswordInput(), max_length=100) We're trying to restrict the submission of these forms if there are additional fields submitted so we have the following added method to our form class def correct_fields(self): return set(self.data.keys()) == {"Email", "Password"} And the following code in the views.py method corresponding to the submission of this form: if form.is_valid() and form.correct_fields: How can we avoid having to write Email and Password in both the definition of the form and the correct_fields method? Does django offer a build-in function to prevent forms being submitted if the correct fields are not submitted? (The form is still submitted if the correct fields and some additional fields are given). If this functionality is not given, how do I avoid writing the fields twice? -
Django send_mail method : Include session userid in mail message
I was able to use send_mail method and it works without any problem. What I am trying to achieve is to include session's username in mail message. My views.py allow a certain authenticated user to create numbers. On successful addition of numbers, an email is triggered to the administrators, which at the moment does not include user's userid. So the administrators have no way of knowing which user created the numbers. My attempt to get userid displayed in mail body below. I also tried another variant - #send mail subject= 'Numbers created by {request.user}' message = 'This user {request.user} has created numbers. ' from_email= settings.EMAIL_HOST_USER to_list = [settings.EMAIL_ADMIN] -
HTTP ERROR 405 when i submit my form.how to fix this?
first i went to url /idontknow/ the html of the template belonging to this url: <body> <form action="{% url 'polls:idk' %}" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </body> it loaded my form input the data and then submitted the form. after i submitted it gave me the 405 error , how to solve this such that when i submit i want the same page to reload but with my submiited data inside form. MY View: class IDK(FormView): form_class=NameForm template_name = "polls/idk.html" success_url = "polls/idontknow/" def form_valid(self, form): print("DATA="+form) return super(IDK, self).form_valid(form) my urls: path('idontknow/', views.IDK.as_view(), name='idk'), -
How can I fix this sign up function?
from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render, redirect from django.urls import reverse_lazy def SignUp(request): if request.user.is_authenticated: return redirect('home') else: form = UserCreationForm success_url = reverse_lazy('login') return render(request, 'signup.html', {'form': form}) When I try to sign up it just refreshes the page, but nothing works, the user isn't registered. So how can I fix this? Thanks -
Using Either Slug or PK in URL (Python - Django)
I want the user to access posts using either the PK or Slug. I can get http://localhost:8000/post/8/ to work but not http://localhost:8000/post/working-in-malaysia/. I have looked at a few posts on Stack Overflow but I don't want http://localhost:8000/post/8/working-in-malaysia. And I don't want it to be a case of either the PK works. Or the slug works. I want the user to be able to enter either. Below is the code I have tried. I tried to merge together code I saw in a number of other posts. Sadly to no avail. urls.py urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('post/<int:pk>/', views.post_detail, name='post-detail'), #path('post/<slug:the_slug>/', views.post_detail, name='post-detail-slug'), path('post/<slug:url>/', views.post_detail, name='post-detail-slug'), path('post/new/', PostCreateView.as_view(), name='post-create'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), path('about/', views.about, name='blog-about'), path('facebook/',TemplateView.as_view(template_name='blog/index.html'), name="facebook") ] views.py class PostDetailView(DetailView): model = Post # Should match the value after ':' from url <slug:the_slug> #slug_url_kwarg = 'the_slug' slug_url_kwarg = 'url' pk_url_kwarg = "id" # Should match the name of the slug field on the model slug_field = 'url' # DetailView's default value: optional query_pk_and_slug = True def dispatch(): post = get_object_or_404(Post) comments = post.comments.filter(active=True, slug=slug) new_comment = None if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = post new_comment.save() else: comment_form = … -
Django select random post elemets efficiently
I have some post models where the ID is a UUID. Now I want to display some random post proposals the user may also like to see at my post_detail template... This is how I process the post proposals the user may also like to see at views.py: def post_proposals(proposal_count): post_elements = sorted( chain( Model1.objects.all(), Model2.objects.all(), Model3.objects.all() ) ) post_elements_list = list(post_elements) # Conversion to list is requierd by random post_proposals = random.sample(post_elements_list, proposal_count) return post_proposals def post_detail(request, pk): ... args = { 'post': post, 'post_proposals': post_proposals(proposal_count=10), ... template.html: {% for post_proposal in post_proposals %} <h1>{{ post_proposal.title }}</h1> {% endfor %} The problem now is that this would kill my database performance from my understanding... As soon as I have a lot of posts stored at my database the query will become massive. I first have to get all elements of 3 models and then get 10 random entries from the list each time a post gets displayed to the user. I also found the following which seems to be quite useful: https://elpenia.wordpress.com/2010/05/11/getting-random-objects-from-a-queryset-in-django/ Sadly I can't use that solution as I work with UUIDs which are non-sequential strings instead of int values I would have with IDs. -
python *args as an tuple? directory?
How can I turn a phrasebook into a *argument I mean, specifically, the example in django we have: .order_by('field1', 'field2'...) and I'd like to do if sort =="byName": a=[] #???? a.append('name') a.append('surname') .order_by(a) #??? -
Am trying to deploy my django app on heroku using gcs google cloud storage
Am trying to deploy my django app on heroku using gcs google cloud storage as my storage it can't find the json file enter image description here -
DJANGO: How to use custom user types for social login?
I have custom models for users with multiple user types. Like user1@gmail.com is type A, and he/she can do a,b and c thing, user2@outlook.com is type B, and he/she can do a,b,d or e thing. And that system is working perfectly. But I have an option to login via google and Facebook via social_django, and office365 login via django-microsoft-auth. So how can I add that users (from login via Google, Facebook etc.) to user types for normal users? Also can I add the to existing user types or I need new ones? -
Django - How can I get birthday and gender using GoogleOAuth2
I managed to set google login working well but I am trying to get additional information from the users, specifically gender and birthday. Unfortunately I am having trouble trying to achieve this. Here are my configurations in settings.py: SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'xxxx' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'xxxx' SOCIAL_AUTH_GOOGLE_OAUTH_SCOPE = [ 'https://www.googleapis.com/auth/user.birthday.read', ] SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', # <--- enable this one 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) After adding the link to the scope I was expecting to get the birthday but when I check the response from: https://www.googleapis.com/oauth2/v1/userinfo?access_token='xxxx' I get the following response: { "id": "xx", "email": "xx@gmail.com", "verified_email": true, "name": "xx", "given_name": "xx", "family_name": "xx", "picture": "https://xx.com/a-/xx", "locale": "xx" } As you can see birthday is missing. Anyone that got through this one out there? Thanks -
Django: request.POST.get from form data not working correctly
I have been trying to come up with a solution and have been searching the web for hours now. I hope you guys can help me find the problem in my code! I am trying to implement a form in Django, a simple textfield. As soon as the user submits the text data in the field, I want it to POST the data and I want a next view to retrieve that data and print it on screen. In detail: I want the user to enter some text in the form on page home.html then submit it, and the user input will then be printed on the next page predict.html (of course, I am planning to transform the inpur in between, but first I want the text to at least get printed on the second page). This is my code: views.py from django.shortcuts import render from django.http import HttpResponse from .forms import NameForm from django.template import RequestContext def index(request): return render(request, 'personal/home.html') def predicted(request): predicted = request.POST.get('data') return render(request, 'personal/predicted.html', {"predicted": predicted}) def get_name(request): if request.method == 'POST': if form.is_valid(): return render_to_response('personal/predcited.html', RequestContext(request)) else: form = NameForm() return render(request, 'home.html', {'form': form}) forms.py from django import forms class NameForm(forms.Form): data … -
Django - Editing a Query from two different tables
I have got a query running from two different tables but I when I go in to edit the query I am hitting a roadblock; A roadblock in my own logic on how django works. I run a query of all devices at a specific location and this works fine. In the database I have a table for location, a table for devices and a table for maintenance. search device by location search_device.html {% extends "example/base.html" %} {% block content %} <head> <title>Search Devices at Locations</title> </head> <body> <form action="{% url 'search_device' %}" method="POST" > {% csrf_token %} <table> <tr> <td><b>Locations: &nbsp;&nbsp; </b></td> <td> <select name="location_name"> {% for location in locations %} <option value="{{location.location_name}}">{{location.location_name}}</option>{% endfor%} </select> </td> <td><input type="submit" value="Submit"/></td> </tr> </table> </form> <br> <h3 align="left">Render Device List based on Location Choice</h3> <table> <tr> <td><b> Devices: </b></td> <td><b>License Key:</b><br> <td><b>Maintenance Support End Date: &nbsp;</b> <br> <td><b>Actions</b></td> </tr> {% for device in devices %} <tr> <td id="device_name"> {{device.device_name}} </td> <td id="license_key"> {{device.maintenance.license_key}} </td> <td id="maintenance_support_end_date"> {{device.maintenance.maintenance_support_end_date}} </td> <td><a href="{% url 'edit_device' device.id %}"><button id="edit_device">Edit Device</button></a> </td> </tr> {% endfor %} </table> This works fine and gives me a list of all devices at each location. What I'd like to be able … -
Django Custom user login form doesn't work
I'm a beginner at Django and I created custom user model (Person) using AbstractBaseUser and custom forms for registration (RegForm) and login (LogForm). With RegForm everything is okay and it works right but when I try to login I always have error messages that's my username or password incorrect, even when it's correct. I have tried to read documentation but I didn't find solution. And I have no idea what is wrong. views.py : from django.shortcuts import render,redirect from django.contrib import messages #from .models import Tutorial from django.http import HttpResponse from django.contrib.auth import logout, authenticate, login, get_user_model # для входа, выхода from .forms import RegForm , LogForm from .models import Person, Service, Category from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import AuthenticationForm @login_required def homepage(request): return render(request = request, template_name='barter/home.html', context = {"category":Category.objects.all}) def register(request): #вход аккаунта next = request.GET.get('next') # if request.method == 'POST': form = RegForm(request.POST or None) if form.is_valid(): user = form.save(commit = False) Username = form.cleaned_data.get('Username') password = form.cleaned_data.get('password') user.set_password(password) user.save() new_user = authenticate(Username=user.Username, password=password) login(request, new_user) if next: return redirect(next) return redirect('/') context = { 'form' : form, } return render(request,"register.html",context) def login_request(request): #вход next = request.GET.get('next') form = LogForm(request.POST or None) if form.is_valid(): Username = … -
Python reportlab - Last page
I'm trying to create an invoice with the python reportlab library. (to return in a Django view) What I am already able to do is the following: I can create the first page with the header and add a table with all products, which can go over multiple pages. But now my problem: How can I write something at the bottom of the last page? (I already added a Spacer to be sure that there's enough space for the important part of the invoice. I need to get a canvas on which I can draw the invoice. (That function which draws the invoice is all set up) I hope you can help me! PS: I'm sorry for my english, I'm from switzerland. -
Summary values on a Django Model with tens of millions of records
I have a Django model developed on PostgreSQL with more than 20 Millions of records. The large volume of data makes it impossible to get even a simple count of all rows. from myapp.models import LargeModel len(LargeModel.objects.all()) Is there any workaround for this? -
Why is Django Channels websocket connect call failing?
I am working on a web app that consists of a Django channels 2 app running on AWS Elastic Beanstalk, where AWS Elasticache serves as my redis instance. Everything works completely fine in development, but once I deploy it to AWS I start having websocket issues. Initially it works just fine, sending data over the websocket, for about two minutes, but at some point the connection always fails. Django throws the exception [Errno 110] Connect call failed. In my past experience this has always been related to it not being able to connect to the redis instance, however, in those cases it failed immediately. I have no idea why it's suddenly failing after some amount of time. Any suggestions for causes of this error? -
Hi there. I would like to register the models in admin.py but it doesn't work
Here is admin.py code and I registered app in INSTALLED_APPS and I created three app beside this app . from django.contrib import admin admin.autodiscover() from .models import ( Teacher,Student,Group, Subject,Table,Dairy, NotParticipating,Task,StudentTask, ) @admin.register(Teacher) class TeacherAdmin(admin.ModelAdmin): list_display = ('created_at', ) admin.site.register(Student) admin.site.register(Group) admin.site.register(Subject) admin.site.register(Table) admin.site.register(Dairy) admin.site.register(NotParticipating) admin.site.register(Task) admin.site.register(StudentTask) -
How to deploy changes made to my django project, which is hosted on pythonanywhere?
I am new to git and Pythonanywhere. So, I have a live Django website which is hosted with the help of Pythonanywhere. I have made some improvements to it. I have committed and pushed that changes to my Github repository. But, now I don't know that how to further push that changes to my Pythonanywhere website. I am so confused. Please help!!! Forgive me, I am new to it. -
Reducing backlog and celery mem consumption
I have a Django app that simply checks an API and then stores the response from the API to my DB if the status is completed, I use celery for this, the celery task looks like this @task(bind=True, priority=5) def process_domain_scan(self, scan_url): response = self.get_status(scan_url) if response and (response.get('status') != "FAILED"): while response and response.get('status') == "PENDING": print "processing :: {}".format(response) time.sleep(5) response = self.get_status(scan_url) if response and response.get('status') == "COMPLETED": #store to database the problem here is that sometimes the job I am running on the external API might be pending for hours and hence my celery task will be in a loop for hours while waiting for the status to return Completed is there a better way of using celery to do this without waiting for the API to return Completed -
Deployment failed on heroku
I am relatively new to Django and I am finishing my first project. I've been following the heroku django tutorial at http://devcenter.heroku.com/articles/django and https://www.youtube.com/watch?v=kBwhtEIXGII&list=PL-51WBLyFTg2vW-_6XBoUpE7vpmoR3ztO&index=24&t=576s but I keep running into the following problem. heloku logs --tail 2020-04-27T17:49:06.576169+00:00 app[web.1]: ModuleNotFoundError: No module named 'crm-live' 2020-04-27T17:49:06.576364+00:00 app[web.1]: [2020-04-27 17:49:06 +0000] [10] [INFO] Worker exiting (pid: 10) 2020-04-27T17:49:06.614676+00:00 app[web.1]: [2020-04-27 17:49:06 +0000] [4] [INFO] Shutting down: Master 2020-04-27T17:49:06.614802+00:00 app[web.1]: [2020-04-27 17:49:06 +0000] [4] [INFO] Reason: Worker failed to boot. 2020-04-27T17:49:08.033207+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=codrut-crm.herokuapp.com request_id=2d4b0b83-fb4b-4658-b465-d96b3cd3c4fd fwd="188.26.24.149" dyno= connect= service= status=503 bytes= protocol=https 2020-04-27T17:53:52.000000+00:00 app[api]: Build started by user ursache.codrut71@gmail.com 2020-04-27T17:54:58.618150+00:00 app[api]: Deploy 11a7c2b5 by user ursache.codrut71@gmail.com 2020-04-27T17:54:58.618150+00:00 app[api]: Release v9 created by user ursache.codrut71@gmail.com 2020-04-27T17:54:58.947798+00:00 heroku[web.1]: State changed from crashed to down 2020-04-27T17:55:10.000000+00:00 app[api]: Build succeeded 2020-04-27T17:55:37.135414+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=codrut-crm.herokuapp.com request_id=dad84a35-0089-44a8-9d8c-4c06e673f59d fwd="188.26.24.149" dyno= connect= service= status=503 bytes= protocol=https 2020-04-27T17:56:52.119540+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/admin" host=codrut-crm.herokuapp.com request_id=485798b3-6d1b-48c7-beb2-5d9a0ba52dcf fwd="188.26.24.149" dyno= connect= service= status=503 bytes= protocol=https 2020-04-27T18:08:48.000000+00:00 app[api]: Build started by user ursache.codrut71@gmail.com 2020-04-27T18:09:49.587556+00:00 app[api]: Deploy 11a7c2b5 by user ursache.codrut71@gmail.com 2020-04-27T18:09:49.587556+00:00 app[api]: Release v10 created by user ursache.codrut71@gmail.com 2020-04-27T18:10:01.000000+00:00 app[api]: Build succeeded 2020-04-27T18:10:05.771483+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" …