Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django how to custom rest-auth reset password to send email using SendGrid
I am using Django rest-auth and I am writing a method to send user am email to reset the password. But instead of using the default way of sending email, I would like to use SendGrid to send the email. views.py class PasswordResetSerializer(serializers.Serializer): email = serializers.EmailField() password_reset_form_class = PasswordResetForm def get_email_options(self): return {} def validate_email(self, value): self.reset_form = self.password_reset_form_class(data=self.initial_data) if not self.reset_form.is_valid(): raise serializers.ValidationError(self.reset_form.errors) return value def save(self): request = self.context.get('request') opts = { 'use_https': request.is_secure(), 'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'), 'request': request, } opts.update(self.get_email_options()) self.reset_form.save(**opts) serializers.py class PasswordResetView(GenericAPIView): serializer_class = PasswordResetSerializer permission_classes = (AllowAny,) def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response( {"detail": _("Password reset e-mail has been sent.")}, status=status.HTTP_200_OK ) SendGrid function class SendEmail(View): def get(self, request, *args, **kwargs): from_email_address = self.request.GET['from_email_address'] to_email_address = self.request.GET['to_email_address'] email_subject = self.request.GET['email_subject'] email_content = self.request.GET['email_content'] sg = sendgrid.SendGridAPIClient(apikey=settings.SENDGRID_API_KEY) from_email = Email(from_email_address) to_email = Email(to_email_address) subject = email_subject content = Content("text/plain", email_content) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) print(response.status_code) return HttpResponse('Email has been sent!') I am aware that first I have to use url(r'^password/reset/$', PasswordResetView.as_view(), name='rest_password_reset'), to send user an email with the link that includes the 'uid' and 'token' to reset the password. and then use the: … -
Celery v4 not routing tasks as expected
I'm updating my celery workers from celery v3 to celery v4, and all my tasks are Class Based Tasks. I have manually registered the tasks since it's what indicated in the upgrade doc. The problem is in task routing, I have the following Task: class RegisterTask(Task): routing_key = 'app_server.register' def run(**params): whatever ... I'm running two celery workers, one on the default queue, and the other on the register queue, like below: # Default Worker celery -A app_server worker --loglevel=info --concurrency=1 # Register Worker celery -A app_server worker -Q app_server_register --loglevel=info --concurrency=1 and here's my queues definition: CELERY_TASK_DEFAULT_QUEUE = 'app_server_default' CELERY_TASK_DEFAULT_ROUTING_KEY = 'app_server.default' CELERY_TASK_QUEUES = ( Queue('app_server_default', routing_key='app_server.default'), Queue('app_server_register', routing_key='app_server.register') ) The unexpected behavior is the difference I see when I call the task using Celery V3 and Celery V4. # Celery V3 RegisterTask().delay(**params) # task is consumed by the register worker! # Celery V4 RegisterTask().delay(**params) # task is consumed by the default worker! And I want the task to be consumed by the register worker (celery v3 behavior), hence why I hardcoded the routing_key attribute in the class based task. But Celery V4 seems to ignore the routing_key attribute in the class based task. [I'm also using redis as … -
Django FileExtensionValidator doesn't show error meesage
I am using FileExtensionValidator Django's FileField and leverage this answer to limit the file size, both are working, but the validation error messages will not be shown. I'm using Django 2.1. The following is my code: Model from django.core.validators import FileExtensionValidator class Project(models.Model): owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='projects', ) title = models.CharField( _('project name'), max_length=100, help_text=_('Required. 100 characters or fewer.'), ) slug = models.SlugField( _('slug'), max_length=80, ) created = models.DateTimeField( _('dateTime created'), auto_now_add=True, ) xmlfile = models.FileField( _('input file'), upload_to=user_directory_path, validators=[FileExtensionValidator(allowed_extensions=('xml',))], help_text=_('Required. Please upload an XML file.'), ) Form from django.core.exceptions import ValidationError def file_size(value): limit = 9 * 1024 * 1024 if value.size > limit: raise ValidationError('File too large. Size should not exceed 9 MiB.') class ProjectForm(forms.ModelForm): xmlfile = forms.FileField( label='XML File Upload', widget=forms.FileInput(attrs={'accept':'application/xml'}), validators=[file_size], ) class Meta: model = Project widgets = { 'owner': HiddenInput(), } View class ProjectCreate(CreateView): form_class = ProjectForm model = Project template_name = 'project_new.html' success_url = reverse_lazy('my_projects_list') def get_initial(self): initial = super().get_initial() initial['owner'] = self.request.user return initial I tested this code. When trying to upload an XML file less than 9M, it works and the user is brought to the success URL. But when either file format or file size is wrong, it's … -
Ck editor idsplaying html not normal text?
I am a newbie in django and I am making my blog I used ck editor for my blog ,So I can style my text but instead of displaying that as a normal text on browser it,s displaying that as a html tag. This is how it displays Check the image enter image description here -
Django framework : Using bootstrap dual list box
I am trying to create the following UI using the Django framework and Bootstrap. <form id="form" action="" class="wizard-big"> {% csrf_token %} <select class="form-control dual_select" multiple> <option value="United States">United States</option> <option value="United Kingdom">United Kingdom</option> <option value="Australia">Australia</option> <option selected value="Austria">Austria</option> <option selected value="Bahamas">Bahamas</option> <option value="Barbados">Barbados</option> <option value="Belgium">Belgium</option> <option value="Bermuda">Bermuda</option> <option value="Brazil">Brazil</option> <option value="Bulgaria">Bulgaria</option> <option value="Cameroon">Cameroon</option> <option value="Canada">Canada</option> </select> <div> <input class="btn btn-success widget-btn-1 btn-sm" type="submit" name="do-something" value="Do Something" /> </div> </form> <script src="{% static 'po/assets/js/duallistbox/jquery.bootstrap-duallistbox.js' %}"></script> <script src="{% static 'po/assets/js/duallistbox/duallistbox.active.js' %}"></script> With the above html code and after adding required .js to html, I am able to create required UI. I want to pass the selected values (e.g. Austria and Bahamas as shown in the above picture) to a function in views.py when "Do Something" button is clicked. Can you please tell me how to do it? -
Django rest_framework not retrieving token athentication
I run into some problems when trying to retrieve token authentication in Django using django rest_framework Serializers.py files: from django.contrib.auth import get_user_model, authenticate from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers class AuthTokenSerializer(serializers.Serializer): """create the serializer class for the token""" email = serializers.CharField() password = serializers.CharField( style = {'input-type': 'password'}, trim_whitespace = False ) def validate(self, attrs): """validate and authenticate the user""" email = attrs.get('email') password = attrs.get('password') user = authenticate( request=self.context.get('request'), username=email, password = password ) if not user: msg=_('Unable to authenticate with provided credentials') raise serializers.ValidationError(msg, code='authentication') attrs['user'] = user return attrs Views.py files: from rest_framework import generics from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.settings import api_settings from user.serializers import UserSerializer, AuthTokenSerializer class CreateTokenView(ObtainAuthToken): """obtain a new token for user""" serializer_class = AuthTokenSerializer renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'core', 'user', ] I get the following errors when trying to retrieve the token: ProgrammingError at /api/user/token/ (1146, "Table 'django.authtoken_token' doesn't exist") -
Django rest-framework how to get 'uid' and 'token' through only email address
I am implementing a function to send user an email to reset their password using rest-auth API: url(r'^password/reset/confirm/$', PasswordResetConfirmView.as_view(), This API requires 'password1', 'password'2, 'uid' and 'token'. But since I am only getting an email address from the user. I am not sure how to get the 'token' and 'uid' only through the email address. I know Django provides something like: url(r'^api-token-auth/', views.obtain_auth_token) But this method requires both username and password to get the token which does not work for my case since I only have the email address. Can someone show me how to get the 'token' and 'uid' through only the email address? Thanks a lot! -
Allauth redirect to 'account/login/None' when i login/signup
When I create an account or log in with an existing one, Allauth redirects to 'account/login/None' or 'account/signup/None', but I am logged in and create the account successfully views: class LoginView(RedirectAuthenticatedUserMixin, AjaxCapableProcessFormViewMixin, FormView): form_class = LoginForm template_name = "account/login.html" success_url = "/" redirect_field_name = "next" # .... class SignupView(RedirectAuthenticatedUserMixin, CloseableSignupMixin, AjaxCapableProcessFormViewMixin, FormView): template_name = "account/signup.html" form_class = SignupForm redirect_field_name = "next" success_url = "/" # .... urls.py urlpatterns = [ path('account/', include('allauth.urls'), name='account'), # .... ] settings.py LOGIN_REDIRECT_URL = '/' -
Model field on django should is the sum of other model
I'm new on Django and I have a problem. I need to have two models, but with the particularity of that one of them have the field "total" that is the subtraction of two field of other model, but "total" has not be save on db. class account(models.Model): number = models.CharField() total = 0.0 def __get_total(self): return B.input - B.output # I don't know how to # join A with B # should be query about whole # movement of a particular account total = property(__get_total) class movement(models.Model): input = models.DecimalField() output = models.DecimalField() a = models.ForeignKey(A, related_name='a') -
Reverse lookup on foreign key in template
I'm trying to output the field of a model instance that is a foreign key of a model that I have the context of in my template. Models.py class Product(models.Model): title = models.CharField(max_length=120) def __str__(self): return self.title class Variation(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) title = models.CharField(max_length=120) price = models.DecimalField(decimal_places=2, max_digits=20, default=0) def __str__(self): return self.title There can be many variations to one product. Within my template, the following will output the title of the variation {{cart.variation}} How can can I get the title of the product given the foreign key relationship from variation to product and output that in my template? I've tried this, but it doesn't work: {{cart.variation.product_set.first}} Thanks! -
Django: return the response to view function
I have html checkout from that returns success/failure response. I want to pass this response back to view function. <html> <body> <button id="rzp-button">Authenticate</button> <script src="https://checkout.razorpay.com/v1/checkout.js"></script> <script> var options = { "key": "test_key", "subscription_id": "{{ sub_id }}", "name": "My Billing Label", "description": "Auth txn for sub_8seKGNhVEOwnjj", "handler": function (response){ alert(response.razorpay_payment_id); } }; var rzp1 = new Razorpay(options); document.getElementById('rzp-button').onclick = function(e){ rzp1.open(); } </script> </body> </html> I think I have to write something inside "handler": function (response){ alert(response.razorpay_payment_id); } to return to view with response. Could someone help me with this? Thanks. -
django.db.utils.OperationalError: no such table:
I recently started a django project and I am having trouble accessing a sqlite3 database that I recently added. I ran python manage.py inspectdb --database 'football' after inserting the new database into settings.py. This gave me the file that I copy pasted into models.py. From there I ran makemigrations which gave me this error: SystemCheckError: System check identified some issues: ERRORS: teambuilder.Countries.country_id: (fields.E007) Primary keys must not have null=True. HINT: Set null=False on the field, or remove primary_key=True argument. teambuilder.Playertransferhistory: (models.E004) 'id' can only be used as a field name if the field also sets 'primary_key=True'. teambuilder.Teams.team_id: (fields.E007) Primary keys must not have null=True. HINT: Set null=False on the field, or remove primary_key=True argument. (venv) Jacks-MBP:SportWebsite Tilley$ python manage.py makemigrations SystemCheckError: System check identified some issues: ERRORS: teambuilder.Playertransferhistory.id: (fields.E007) Primary keys must not have null=True. HINT: Set null=False on the field, or remove primary_key=True argument. From there I changed null to false where needed and reran makemigrations which gave me this: Migrations for 'teambuilder': teambuilder/migrations/0001_initial.py - Create model Countries - Create model LeagueGames - Create model Leagues - Create model Playerinfo - Create model Playertransferhistory - Create model Teams followed by migrate which outputted: Operations to perform: Apply all migrations: … -
Are my (hobby) dev and production environements adapted to my needs?
I'm on an open source project that will make use of Wikidata API. It will provide some small tools based on forms and SPARQL queries made on Wikidata and will also run a blog. 1/ The website The blog's trafic is currently 500~1000 visits/day the days after an article is published. I don't except that the tools will generate way more trafic. The tools will rarely have to deal with query sets of more than 100 wikidata items and will probably don't post more than 100 statements at once. The database will contain something like 20 tables and 10 000 lines The site will be based on Django CMS and entirely written in Python. 2/ My personal needs An easy to manage environnement, as I want to focus on the tools devlopment. Stable, as I can't monitor the server each day. Economic, as it is a hobby project. 3/ My current production environment Cloud VPS SSD 1 form OVH : 1 vCore > 2GHz 2 Gb of RAM 20 Gb of SSD 3€/mounth ($3.4) Ubuntu server Vesta CP control panel NGINX as a proxy Apache for backend MySQL database 4/ My dev environement Cloud based desktop from Shadow (due to … -
Django Project and Web Frameworks
I am a Django learner. How to create a Project using Django? 2.[a] What are the precautions while creating a Django Project? [b] What is the tree structure or file-folder hierarchy of a Django Project? What are the System Requirements to Install Django? What are the types of data scripts in view of Django Project? Why only Scripts are used in Django? What are the Differences between Scripting Languages and Programming Languages? Where will we use Scripting Languages as well as Programming Languages? What are the Advantages and Consequences of Django? How can I Deploy a Project into a Zipped Folder? What is the difference between the Absolute path and the Relative Path? What is the difference between the Root Level Directory and the Project Level Directory? What are the Differences between Web Application and Enterprise Application? -
AJAX Routing to Django URLs (Using Django 2.0 "path" urlpatterns)
This used to work before Django 2.0 changed url patterns from "url" to "path": html.py <!DOCTYPE html> {% load static %} <head> <script type="text/javascript" src="{% static 'main/js/jquery-3.3.1.js' %}"> </head> <body> <div id='test'> <p><button class="btn">Click Here!</button></p> </div> <script> $('.btn').click(function(){ console.log('button is clicked!') $.ajax({ url: 'main/all_json', sucess: function(serverResponse){ console.log('success.serverResponse', serverResponse) } }) }); urls.py urlpatterns = [ url(r'^all_json$',views.all_json, name="all_json") ] views.py def all_json(request): return HttpResponse ('hello world!') But now, Django 2.0 uses "path" instead of the url regex pattern. When I use path: app_name= "name" urlpatterns = [ path('all_json/',views.all_json, name="all_json"), ] I get the: GET http://127.0.0.1:8000/main/all_json 404 (Not Found) I looked in the new documentation and release notes and there are some SO answers that explain how to use it SO post 1 & SO post 2. That has been useful up to this point, where I'm unable to pass the url from the AJAX function to the "path". I'm new to AJAX and I'm used to using the {% url main:all_json %} in Django for my actions. But with AJAX I believe I can't use this notation. Is that right? And for some reason, the examples that I have that used url(r'^$') urlpatterns before Django 2.0 worked, but now I get … -
Which modelfield can store video playback time in django? Or, displaying TimeField WITHOUT a clock associated
I'm surprised that I can't find an answer on SO, but I'm trying to store some information when a user taps/clicks somewhere on my video player. To do this I store the current playback time in a TimeField like so: class TappableItem(models.Model): video = models.ForeignKey(Video, on_delete=models.CASCADE) **video_time = models.TimeField()** position = models.FloatField() And I save it using momentjs: get formattedVideoTime() { const seconds = this.video.currentTime; return moment.utc(seconds*1000).format('HH:mm:ss.SSS'); } So the problem is this: it saves in the DB in a format I want, for example 00:02:41 but when I try to display it in my HTML template, it converts to a date and prints something like 12:02 AM or midnight. I can't find a way to override this behavior. Should I be using a different modelField? -
i am getting a 404 error when using login_required, can somebody help me solve the problem?
I'm new to django and i'm trying to make a learning log website. when I try to restrict my topics with login_required funtion i get a 404 error. here is my code: from django.contrib.auth.decorators import login_required @login_required(login_url='/users/login/') def topics(request): """ Show all topics.""" topics = Topic.objects.order_by("date_added") context = {"topics": topics} return render(request, "learning_logs/topics.html", context) I get this error whenever i use the decorator in my code: Using the URLconf defined in learning_log.urls, Django tried these URL patterns, in this order: admin/ users/ login [name='login'] users/ logout [name='logout'] users/ registration [name='register'] learning_logs/¨ The current path, users/login/, didn't match any of these. please can somebody help me solve this problem? The url works fine but when i use the decorator it breaks. -
Djoser Disable Unused Endpoints
I am using Djoser for authentication in my WebApp and it is pretty fine. However, I'm concerned about some endpoints, like auth/users which returns all users if a token is passed. I won't be using this endpoint and don't want my users to use it as well. How can I disable these unused endpoints provided by Djoser? -
python manage.py runserver just answer first request
I don't know how to introduce myself... First time using Django and Vue in a project. Lots of problems managing to use them both together. Now, when everything seems to be working, when I start running command: "python manage.py runserver" it seems to begin, but after first (sometimes after second or third) request it stops listening, but no error is displayed. So annoying start over and over again when I change something, since I am trying to make requests and I have to try a lot. I appreciate any light on my darkness right now. -
raise TypeError("%s object is not callable" % repr(self))
hg clone git+https://github.com/geekcomputers/Python.git File "/usr/lib/python2.7/dist-packages/mercurial/demandimport.py", line 98, in call raise TypeError("%s object is not callable" % repr(self)) TypeError: "unloaded module 'monotonic'" object is not callable -
Django: How to show sum of Model field in template
I have built the following model: class Fund(models.Model): name = models.CharField(max_length=30) gp = models.ForeignKey(GeneralPartner, on_delete = models.CASCADE) currency = models.CharField(max_length=3, default="") commitment = models.IntegerField(default=0) def __str__(self): return self.name @property def sum_commitment(self): return self.commitment I would like to show the sum of all commitments in my template via a simple {{ fund.sum_commitment }} tag in my template. What does my return statement has to look like to achieve this goal? I tried things like return self.sum(commitment) in all varieties but simply can't find the right solution. Many thanks for any help! -
Django 2.1.7 Clean Way to delete a single App?
i ask myself if there is a clean way/ procedure to ask Django to delete a single app. There are Topics with the same Question but they referencing to older Versions or i missed it. I am newbie i don´t want to mess around with the django db by simply delete the Setting.py App registration. Because I saw that in the Django DB, between all the model entries, there are also data records of migrations, sessions, data entries or how i would call it, django magic. I am using Django 2.1.7 within VirtualEnv. So Far my procedure. Delete the 'my_old_app' App-Registration in settings.py / INSTALLED_APPS Change all entries in views.py, urls.py that have a connection to my_old_app Deleting the model data of the old_app. (simply Migrate?) Thanks, for every Information. -
What could be wrong with this virtual host file in Apache?
I am trying to route an application to a sub route on an internal server, using Gunicorn with my Django app. My virtual host file looks like this: LoadModule proxy_module /usr/lib64/apache2/mod_proxy.so LoadModule proxy_http_module /usr/lib64/apache2/mod_proxy_http.so <VirtualHost *:80> ServerName 172.16.1.81 <Location "/mycustomapp"> ProxyPreserveHost On ProxyPass http://127.0.0.1:9090 ProxyPassReverse http://127.0.0.1:9090 </Location> ErrorLog /var/log/apache2/AccountingDashboard.log </VirtualHost> When I navigate to 172.16.1.81/mycustomapp , I keep getting a 404 not found error when trying to navigate to the application on that route. Is there something else I am doing wrong here? -
Custom price option in Django models..?
I want to create fields for custom price options in my models.py eg. a choice option between 1h, 5h, 1h, 20h and 50h rates and a value for that time option. Right now I have just normal integer fields but I want that there is a select option for the time options and a price for that selected. I know that Using the Django choice fields I can create the choices for the different time options but how can I save the actual price as integer related to that option? Basically I want a form in my frontend where I can choose between time options and submit a price for that option eg. $20/h. Should I make an own class for the price and relate that as foreign key to my time option or is there a better way? There is not much to show in my code since I only currently have an integer field for each price option, thanks! -
Understanding the Generic Foreign Key in Django
I am trying to understand the Generic Foreign Key in Django. I just ran an input script that worked, but I still have questions: All the inserted rows refer to the same content_type, so it makes sense that they all have the same content_type_id, in this case, 35. But where did the number 35 come from? Do I have 34 other content_types somewhere else, like in the default use Django has for content_type? (No, I checked that). How is the use of this number different from a PK or an FK? The object_id is, like my primary keys, a uuid. These all seem to be different per row. But what is the object being identified by this number? Since Generic Foreign Key takes GenericForeignKey('content_type', 'object_id') as args, maybe this is the ‘generic’ foreign key of that row’s relationship to my content_type? Or is it the generic foreign key to any and all future content_types this row might be connected to by me later? Since in this case they are all pointing to the same content object, why didn’t they all get the same object_id, just as they all got the same content_type_id?