Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can Email Validators overwrite clean() method?
Problem: I am attempting to write a clean() method on my Django forms class and for the most part, it is working (Password validation is working but not email?). My goal is to compare two email fields and two password fields to each other and raise a validation issue if they do not match. I have tried using the raise forms.ValidationError() as detailed in the Django docs here, however I would prefer to display the validation error on both fields so I am trying to use the self.add_error('field', msg) method instead as detailed on the same page. My attempt: forms.py class userRegistrationForm(forms.Form): # field definitions here def clean(self): cleaned_data = super(userRegistrationForm, self).clean() email1 = cleaned_data.get('email') email2 = cleaned_data.get('emailConfirm') password1 = cleaned_data.get("password1") password2 = cleaned_data.get("password2") if password1 != password2: msg = 'Your Passwords do not match...' self.add_error('password1', msg) self.add_error('password2', msg) elif email1 != email2: msg = 'Your emails do not match...' self.add_error('email', msg) self.add_error('emailConfirm', msg) Exact error: What ends up happening, is the first email field validates with no errors no matter what and if there is a mismatch, the error only shows up on the second field, unless I type out the full correct email address, then that field also … -
Django-allauth, how do I change the url in my email confirmation email?
friends. Used Django-allauth package for authorization in django project. The project is located in the Docker container (with parameter -p 8002:8001) on the server with the domain(testsite.com). When I run the container on the command line, I run the python command manage.py runserver 0.0.0.0:8001. In the admin panel specify the domain of the site. The problem is that django-allauth sends an email to confirm the email type - http://127.0.0.1:8002/accounts/confirm-email/MQ:1hjJgA:XFqIW130fMBQ5_blim_KVxYsVXg/. In the package code found that the url is used to build the site.domain - but when the variable is output to the console - get the correct domain of the form - testsite.com ahhh! I can not understand what variable to override or how to make to get the desired url of the form - http://testsite.com/accounts/confirm-email/MQ:1hjJgA:XFqIW130fMBQ5_blim_KVxYsVXg ahhh! Can who knows as solve this question? -
Django-Rest: Need to get all data in batch wise from oracle
I need to create Django rest API- fetching data from Oracle DB, apply pagination, send back to response. For that, I am taking no_of_rows_per_page and page_no, and fetching all data. I am using fetchall() method. By this method we are getting all data from DB first, then pagination apply and send back as response. By this process, we need to call next page data, we are getting the same process again(Loading all data again from DB). For that our application is taking too much time (Database connected through VPN and Table having millions of records) For this, I need to fetch data in batch, for that, I used fetchmany(no_of_rows_per_page) method and returning back as response. Since Oracle return each time random rows, getting duplicate/same rows in next page call. Help needed on this. Thank you. -
multitenant django db not migrate
i'm using django-db-multitenant this works ok but the problem is when i try run migrate get this error: [roo@rgmanagement_2 facturacion]$ TENANT_DATABASE_NAME=rg python manage.py migrate Operations to perform: Apply all migrations: correo, empresa, sessions, personal, admin, proveedores, ordenescompra, seguridad, auth, cartera, bodegas, movimientos, contenttypes, custodias, clientes, contabilidad, productos, secuencias, ordenespedido, ventas Running migrations: Rendering model states... DONE Applying seguridad.0004_auto_20190709_1300...Traceback (most recent call last): File "manage.py", line 8, in <module> execute_from_command_line(sys.argv) File "/usr/lib64/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/usr/lib64/python2.7/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib64/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/usr/lib64/python2.7/site-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/usr/lib64/python2.7/site-packages/django/core/management/commands/migrate.py", line 200, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/usr/lib64/python2.7/site-packages/django/db/migrations/executor.py", line 92, in migrate self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/lib64/python2.7/site-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/lib64/python2.7/site-packages/django/db/migrations/executor.py", line 198, in apply_migration state = migration.apply(state, schema_editor) File "/usr/lib64/python2.7/site-packages/django/db/migrations/migration.py", line 123, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/usr/lib64/python2.7/site-packages/django/db/migrations/operations/models.py", line 202, in database_forwards new_model._meta.db_table, File "/usr/lib64/python2.7/site-packages/django/db/backends/base/schema.py", line 359, in alter_db_table "new_table": self.quote_name(new_db_table), File "/usr/lib64/python2.7/site-packages/django/db/backends/base/schema.py", line 110, in execute cursor.execute(sql, params) File "/usr/lib64/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/usr/lib64/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/lib64/python2.7/site-packages/django/db/utils.py", line 95, in … -
Replacing Basic Auth in Django Rest Framework
I currently have Django basic auth setup with Knox token authentication. Basic Auth doesn't seem sufficient for production work, so I want to replace that. Does Django have another password-based authentication_class that I can easily replace BasicAuthentication with, or is this a more involved process? If so, where do I start? my login api view: class UserLoginView(GenericAPIView): serializer_class = UserOrganizationSerializer authentication_classes = (BasicAuthentication,) permission_classes = (IsAuthenticated,) def post(self, request): """User login with username and password.""" token = AuthToken.objects.create(request.user) return Response({ 'user': self.get_serializer(request.user).data, 'token': token }) my default authentication classes: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ], -
GIF Erroring on Network
I'm not quite sure if this is a Django issue, an HTML issue, or something else so apologies if this isn't properly tagged. I have an application where a user submits an Elasticsearch query and a report is then generated. Depending on the number of results the query returns, the report can take quite a while to generate. As a result, I'd like to put a gif of a spinner so the user understands that it's still processing (instead of me just explicitly saying it's still going). I have ajax-loader.gif in my project/static/ folder but it doesn't seem to recognize that it exists because it's giving me a 404 error. Additionally, it's classifying the type as "text/html" instead of "gif". How can I get the gif to load in? html <!-- templates/django_audit/check.html --> {% extends 'base_login.html' %} {% block title %}Please wait{% endblock %} {% load static %} {% block content %} <script type='text/javascript' src="{% static "bootstrap/js/jquery/1.7.1/jquery.min.js" %}"></script> <script type="text/javascript"> $(document).ready( function() { var fn = $('#fn').val() var checkInterval = setInterval(isFileComplete, 3000); //1000 is 1 second function isFileComplete() { $.ajax({ url: '/check_progress/', type: 'POST', data: { 'filename': fn, 'csrfmiddlewaretoken': '{{ csrf_token }}', }, dataType: 'json', success: function (data) { if … -
What's behind the mechanism of Django models and fields?
What is the Django/Python mechanism behind the Django model/field part of framework? To be exact, I am looking for a hint on how Django parses (?) class definition and then knows which fields are required? from django.db import models class Car(models.Model): name = models.CharField(max_length=255, null=True, blank=True) year_of_production = models.DateField(null=True) # the rest of fields... I think the same mechanism is behind Django Forms framework or DRF serializers. I checked repos of these projects but I still can't find any reasonable starting point. There's a architectural problem under my question. I think I need to implement something similar to this mechanism: class Field: def __init__(self, label: str, required: bool = True, **kwargs): self.label, self.required = label, required class CharField(Field): def __init__(self, max_length: int, **kwargs): self.max_length = max_length super().__init__(**kwargs) class DateField(Field): ... class BooleanField(Field): ... class Model: # the mechanisms I do not understand class MyModelInstance(Model): name = CharField(...) # etc. What I need is really simple solution that knows that field is required. But as I stated before I am not that advanced and I would really appreciate any hints. -
How can I know the space left in a pdf page?
I have a pdf with 3 sections and I had to add a page break for each section but now I have to know if the section 3 is smaller and can go into in the same page with section 2, but the tricky part is if section 3 is more than the space left in the page after section 2 I have to add the page-break. What I mean is if I can know where section 2 ends in a page and if I can know the space left in that page, and in the space left can section 3 be. The actual is that section 3 goes after section 2 and when section 3 is longer than the space left for section 2, it does in that way. I expected if section 3 is longer than the space left in the page after section 2 should be a page break, if not so section 3 should go after section 2 on the same page. -
Grabbing data from post request and creating new object model error: 'dict' object has no attribute 'data'
I have a django rest framework project. I want to take the standard create method for Model View Sets in django rest framework. I want to create a new model object based on the data passed in but I also wanted to override some of the fields if they are passed in through url arguments. So if there are no url arguments => just create a default object based soley on the post request. if there is a namespace arguments => create default object based on post request but use the namespace url argument. if there is a namespace and path arguments => create default object based on post request but use the namespace and path url arguments.: I am getting the following error: AttributeError at /api/v2/preferences/namespace1/ 'dict' object has no attribute 'data' Here is the model view set: @permission_classes((IsAuthenticated)) def create(self, request, *args, **kwargs): print(request) namespace = self.kwargs.get('namespace', None) path = self.kwargs.get('path', None) if namespace is None and path is None: return super().create(request) if namespace and path is None: data = { "person":self.request.user, 'version':request.POST['version'], 'namespace':namespace, 'path':request.POST['path'], 'value':request.POST['value'], 'user_id':request.user.id, } return super().create(data) if namespace and path: data = { "person":self.request.user, 'version':request.POST['version'], 'namespace':namespace, 'path':path, 'value':request.POST['value'], 'user_id':request.user.id, } return super().create(data) -
images not loading from HTML template using Django
Images on my Django website are not loading This is my settings.py: STATIC_URL = '/static/' STATICFILES_DIRS =[ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT= os.path.join(BASE_DIR,'assets') This is my index.html file code for images: I have used {% load staticfiles %} in the index.html file also have ran "python manage.py collectstatic" -
How to completely reset Postgres DB on Heroku?
I have a learning project deployed on Heroku. It had a Postgres database provisioned. I introduced some major changes in the models of my Django project and destroyed the old DB and provisioned a new one, which is totally empty, but it is not working like an empty database. When I run the command heroku run python manage.py makemigrations, I get the error message, You are trying to add a non-nullable field.... Why am I getting this message when I have destroyed the old database? -
Virtual Environment won't create
I am just getting into Django and I'm trying to create a virtual environment, I am using windows 10. I have Pip and Python installed. However, when I try to create a virtual environment, I keep getting this in the cmd prompt over and over again. The message is: Running virtualenv with interpreter c:\users\kenny james\appdata\local\programs\python\python37\python.exe How can I resolve this? -
How to Update Object in Django
I two functions which I am using to update an object when various user input is detected. I have two other functions which operate in a nearly identical manner, however, for some reason the object is not being updated upon submission like the other functions. views.py(working) def new_opportunity_engineer(request): id = request.GET.get('id') try: obj = Opportunity.objects.get(id=id) account_manager_obj = cwObj.get_member_by_id(obj.accountManger) account_manager = account_manager_obj[0]['firstName'] + ' ' + account_manager_obj[0]['lastName'] inside_solutions_obj = cwObj.get_member_by_id(obj.insideSolutions) inside_solutions = inside_solutions_obj[0]['firstName'] + ' ' + inside_solutions_obj[0]['lastName'] selected_company_obj = cwObj.get_company_by_id(obj.company) selected_company = selected_company_obj[0]['name'] selected_location = obj.location selected_contact_obj = cwObj.get_contact_by_id(obj.contact) selected_contact = selected_contact_obj[0]['firstName'] + ' ' + selected_contact_obj[0]['lastName'] company_id = obj.companyId selected_practice = obj.practice project_name = obj.projectName ware_type = obj.wareType estimate_id = obj.estimateId qualify = obj.qualify professional_services = obj.professionalServices total = obj.total maintenance = obj.maintenance sub_labor = obj.subLabor ga_contract = obj.gaContract cisco = obj.cisco cisco_question_1 = obj.ciscoQuestion1 cisco_question_2 = obj.ciscoQuestion2 cisco_question_3 = obj.ciscoQuestion3 close_date = obj.closeDate priority = obj.priority notes = obj.notes except Opportunity.DoesNotExist: obj = None context = { 'account_manager': account_manager, 'inside_solutions': inside_solutions, 'selected_company': selected_company, 'selected_location': selected_location, 'selected_contact': selected_contact, 'company_id': company_id, 'selected_practice': selected_practice, 'project_name': project_name, 'ware_type': ware_type, 'estimate_id': estimate_id, 'qualify': qualify, 'professional_services': professional_services, 'total': total, 'maintenance': maintenance, 'sub_labor': sub_labor, 'ga_contract': ga_contract, 'cisco': cisco, 'cisco_question_1': cisco_question_1, 'cisco_question_2': cisco_question_2, 'cisco_question_3': cisco_question_3, 'close_date': … -
Unable to get Django HttpResponse
A little description of what i m trying to do. I want to make a User Interface (web/HTML) through which i can send the commands to router and display the result on the Webpage/HTML. Here's the code i m using:- Views.py from django.shortcuts import render from first_app.forms import CmdForm from django.http import HttpResponse def index(request): my_dict = {'insert_me': ""} return render(request,'first_app/index.html',context=my_dict) def form_name_view(request): if request.method == "POST": form = CmdForm(request.POST) if form.is_valid(): from netmiko import ConnectHandler devices = { 'device_type':'cisco_ios', 'ip':'192.168.50.145', 'username':'kartik', 'password':'12345', 'secret':'12345', 'port':'22' } cmd = request.POST.get('command', '') netconnect = ConnectHandler(**devices) #print("connection established with", devices['ip']) output = netconnect.send_command(cmd) return render(request,'first_app/forms.html', {'form': form, 'output':output}) else: form = CmdForm() return render(request,'first_app/forms.html', {'form': form}) forms.py from django import forms class CmdForm(forms.Form): command = forms.CharField(label='Command to execute') urls.py from django.contrib import admin from django.urls import path from django.conf.urls import include from first_app import views urlpatterns = [ path('Automation_page/', views.form_name_view,name='IP form'), path('admin/', admin.site.urls), path('', views.index,name='first'), path('first_app/',include('first_app.urls')), ] forms.html <!DOCTYPE html> {% load staticfiles %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>FORMS</title> </head> <body> <h1> IP address form </h1> <p>Run command:</p> <form method="POST"> {% csrf_token %} {{ form }} <input type="submit" value="Run command!" /> </form><br> {% if request.POST %} <p>Command output:</p> <pre>{{ output }}</pre> … -
Can't create new model object within django rest framework model view set: 'User' object is not subscriptable
I have a django rest framework project. I am trying to override the create method so that if there are certain parameters or arguments passed into the url, it will ovverride some of the default informaiton passed in with the form. I am doing that by creating the data object that will be used to create the new object. Right now, I am grabbing the user by using request.user but it is giving me the following error: TypeError at /api/v2/preferences/namespace1/ 'User' object is not subscriptable and I am not sure how to fix it. Here is my code for the mode view set create method override: @permission_classes((IsAuthenticated)) def create(self, request, *args, **kwargs): print(request) namespace = self.kwargs.get('namespace', None) path = self.kwargs.get('path', None) if namespace is None and path is None: return super().create(request) if namespace and path is None: data = { "person":self.request.user, 'version':request.POST['version'], 'namespace':namespace, 'path':request.POST['path'], 'value':request.POST['value'], 'user_id':request.user['id'], } return super().create(data) if namespace and path: data = { "person":self.request.user, 'version':request.POST['version'], 'namespace':namespace, 'path':path, 'value':request.POST['value'], 'user_id':request.user['id'], } return super().create(data) -
Creating PDF based on user selected classes on webpage
I am trying to create a PDF based on information selected by a websites user. The way we currently handle the displayed information does not involve a PDF so we just created a JSON and then used Javascript to tear apart the data and display it. I have read and seen first hand that you cannot use javascript with the xhtml2pdf library. Therefor I was wondering if there is a way to pass multiple Model Objects so that I can access them in the HTML. Without knowing the total amount until the user selects them. I have tried passing multiple objects to the PDF but when I print the data it just displays list that I am seemingly not able to access. By using {{data.}} course_code is the list of objects: this is located in view.py data = CourseLookup().get_equivalent_courses(course_code) return Render.render('pdf_form.html', {'data': data,'response':'', 'request':request}) Located in pdf_form.html. {{data}}# I have tried data.QuerySet and data.Course and it displayed nothing. Displayed on the webpage. []>, ]>] I am trying to access an undetermined amount of class data and display their names in a HTML table that is made into a PDF Document with xhtml2pdf. The amount is determined after the user selects … -
Replace function of pandas does not seem to work
I looked around but I couldn't find something that could help me. I have a dataset which is composed like this: rsid name countexperiments 7 18 1 8 448 1 this dataset is later converted in a dataframe and then I call the replace function import pandas as pd filename = 'a.csv' df = pd.read_csv(filename) df.replace(7, 5, inplace=True) but after that the output is still rsid name countexperiments 7 18 1 8 448 1 -
Django: URLs in django and adding it into templates
How to write URL in the template to take the request to this kind of URL - path('category/<str:cat>/', CategoryView.as_view(), name='category') I am working on Django 2.1 and my urls.py contains multiple str path resolver. To differentiate them I want to write urls by adding some string but I can't find any way to add these urls into my template so that request can be made through templates. path('category/<str:cat>/', SomeView1.as_view(), name='view1'), path('tag/<str:tags>/', SomeView2.as_view(), name='view2'), Please suggest how to add these links to my template or is there any alternate way to solve this issue. -
Django Rest Framework quickstart Page not found 404
I'm trying to do a quickstart tutorial from https://django-rest-framework.org. And this is my urls.py from django.urls import path, include from rest_framework import routers from main.views import MovieViewSet, CommentViewSet router = routers.DefaultRouter() router.register(r'movies', MovieViewSet) router.register(r'comments', CommentViewSet) urlpatterns = [ path('', include(router.urls)), ] and when I go to http://127.0.0.1:8000/movies/ I get Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/movies/ Using the URLconf defined in movie_api.urls, Django tried these URL patterns, in this order: ^$ [name='api-root'] ^\.(?P<format>[a-z0-9]+)/?$ [name='api-root'] The current path, movies/, didn't match any of these. The viewsets and serializers are implemented as in tutorial. Am I tired and not seeing something? -
How to fix this error - 'validationError' object has no attribute get
I have custom login form . When I try to login with username/email that is in database and wrong password. It works fine - it says wrong credentials. But when I try to login with username/email that doesn't exist in database. ValidationError occur. -
Access Django Model Field from Javascript
I'm having some problems with a midi player. I want to reproduce automatically the midi file that is saved in my Django model Field, concretely mi field midi, which saves a real midi file. This is the HTML template that I'm using <body style="margin-top: 250px;"> <h2 style="margin: 115px auto 4px auto; font-size: 20px;">BareBones MIDI</h2> <button id="load">Choose Tune</button> <input id="filein" type="file" accept=".mid, .midi" style="display: none;"> <div id="title" style="margin: 3px; font-size: 10px; font-style: italic; white-space: nowrap;"></div> <div style="margin-left: 845px"> <button id="control">&#9654;</button> <progress style="width:800px; height: 30px"></progress> </div> </body> At the moment, It uses an input tu upload the file, but I want to modify this and change the code so the midi file of my django model field is reproduced automatically, without the input. In my JS code, I've tried to access the field the following way: let cancion_midi = {{cancion.midi}}; But it throws me the following error ReferenceError: tiger_qNDnPUI is not defined I'm losing my head and I don't find any solution. I'd be grateful if somebody could help me. If you have any questions, ask me anything. -
Django Rest Framework, POST request to url/group1/messages
I want to add a message inside a chat room I have made in django rest framework. My problem is that there is no page called: group1/messages. But if I go into url/group I can see all the messages on a different level. And if I go into url/messages, the messages of all the groups appear! How do I set this up so that I can make a post request to url/group1/messages? Django Models: class UserProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: verbose_name_plural = 'All Users' def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_data(sender, update_fields, created, instance, **kwargs): if created: user = instance profile = UserProfile.objects.create(user=user) class Message(models.Model): sender = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name="sendermessage") content = models.CharField(max_length=500) date = models.DateField(default=date.today) canview = models.ManyToManyField(UserProfile, blank=True, related_name="messagecanview") class Meta: verbose_name_plural = 'Messages' def __str__(self): return "{sender}".format(sender=self.sender) class Room(models.Model): name = models.CharField(max_length=50) members = models.ManyToManyField(UserProfile, blank=True) messages = models.ManyToManyField(Message, blank=True) class Meta: verbose_name_plural = 'Rooms' def __str__(self): return "{name}".format(name=self.name)enter code here Django Serializers: class UserProfileSerializer(serializers.ModelSerializer): username = serializers.CharField(source='user.username') class Meta: model = UserProfile fields = ('id', 'username') class MessageSerializer(serializers.ModelSerializer): sender = UserProfileSerializer() class Meta: model = Message fields = ('id', 'content', 'date', 'sender') class RoomSerializer(serializers.ModelSerializer): messages = MessageSerializer(many=True) members = UserProfileSerializer(many=True) class Meta: model … -
Inverse Django lookup filtering
So I have two models: class Member(models.Model): course_member = models.ForeignKey(CourseMember, on_delete=models.CASCADE class CourseMember(models.Model): name = models.CharField(max_length=30) How can I get all the CourseMembers that have 2 or more members? And, how do I stop CourseMember from having more than 1 Member. I was thinking about using Aggregate and Group by, but I wasn't sure how to do it. -
In Python, how do you do substitutions when the template file contains a "$"?
I'm using Python 3.7 and Django. I want to get a string from a template in Python and make the apporpriate substitutions like so ... src = Template(filein.read()) # document data relative_path = article.path.replace(settings.REDDIT_URL_PREFIX, "") d = {'relative_path': relative_path, 'comment': comment} # do the substitution result = src.substitute(d) However, there is one problem. My template contains this ["xpath=//a[@onclick='$(this).parent().submit()']", "xpath:attributes"], The dollar sign is usually used for substitution, and so maybe for this reason, my above code is dying with the error ... ValueError: Invalid placeholder in string: line 248, col 31 Does anyone know how I modify the above template line so that the substitution mechanism ignores the dollar sign on that line? -
PostgreSQL empty list VALUES expression
I am trying to take a list of points, and query a geospatial database, to find all matching rows. I have a computed SQL statement that looks like this: cursor = connection.cursor() cursor.execute( ''' SELECT g.ident FROM (VALUES %s) AS v (lon, lat) LEFT JOIN customers g ON (ST_Within(ST_SetSRID(ST_MakePoint(v.lon, v.lat), %s), g.poly_home)); ''', [AsIs(formatted_points), SRID] ) Here is an example of what the formatted_points variable looks like: (-115.062,38.485), (-96.295,43.771) So, when that is inserted into the SQL expression, then VALUES expression reads: (VALUES (-115.062,38.485), (-96.295,43.771)) AS v (lon, lat) So far so good. However, when the list of points is empty, the VALUES expression looks like this: (VALUES ) AS v (lon, lat) .. which causes me to get this error: django.db.utils.ProgrammingError: syntax error at or near ")" In other words, (VALUES ) is not legal SQL. Here's the question: How do I represent an empty list using VALUES? I could special case this, and just return an empty list when this function is passed an empty list, but that doesn't seem very elegant.