Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework custom serializer's ValidationError not working
I am trying to set up a custom login serializer in Django and want a custom response but the default one always show: { "username":[ "This field is required." ], "password":[ "This field is required." ] } I tried to set up my serializer like so: class MyLoginSerializer(serializers.Serializer): username = serializers.CharField(required=True, allow_blank=True) email = serializers.EmailField(required=False, allow_blank=True) password = serializers.CharField(style={'input_type': 'password'}) def authenticate(self, **kwargs): return authenticate(self.context['request'], **kwargs) def _validate_email(self, email, password): user = None if email and password: user = self.authenticate(email=email, password=password) else: msg = _('Must include "email" and "password".') raise serializers.ValidationError(msg) return user def _validate_username(self, username, password): print("in username") user = None if username and password: print("in username 2") try: user = self.authenticate(username=username, password=password) except Exception: raise serializers.ValidationError("Wrong") else: print("in username 3") msg = _('Must include "username" and "password".') raise serializers.ValidationError(msg) return user def _validate_username_email(self, username, email, password): user = None if email and password: user = self.authenticate(email=email, password=password) elif username and password: user = self.authenticate(username=username, password=password) else: msg = _( 'Must include either "username" or "email" and "password".' ) raise serializers.ValidationError(msg) return user def validate(self, attrs): username = attrs.get('username') email = attrs.get('email') password = attrs.get('password') user = None if 'allauth' in settings.INSTALLED_APPS: from allauth.account import app_settings # Authentication through … -
Django ORM Query Multiple Models Reverse Relationship
I have the main model and five sub-models out of five four models have foreignkey relationship and one model has a one-to-one relationship to the main model. I am trying to execute a query on the main model and fetch related records from the sub-model sorted by 'id' and select the first record. I tried multiple ways to achieve this but still, the total operation takes around 20secs to fetch around 6000 records. I would really appreciate any help to efficiently fetch data from these models. Model M: id name status Model SA: m = Foreignkey(M) sa1 Model SB: m = Foreignkey(M) sb1 Model SC: m = Foreignkey(M) sc1 Model SD: m = Foreignkey(M) sd1 Model SE: m = OneToOne(M) se1 I tired select_related, prefetch_related, but still not able to reduce the turn-around-time. After trying different ways, currently, I am using the below, but from that, I get the only records which has data in the sub-models. But I would need to fetch all records from the main model irrespective of data in the sub-models. data = M.objects.exclude( SA=None, SB=None, SC=None, SD=None, SE=None, ) I am looking for output like: {'id': 1212, 'name':'asdasd', 'sa1':'asdasda, 'sb1':'asdasda, 'sc1':'asdasda, 'sd1':'asdasda, 'se1':'asdasda} -
Getting approval from Admin first before posting a blog in Django
I have made a blog as a project and I have set users to submit posts for the blog directly but i want to direct this post to the admin first for approval before showing on the website. here is the Post Create View Class. class PostCreateView(CreateView): model = Post fields = ['title', 'content'] template_name = "post_form.html" def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) Thank you in Advance -
Permanent Superuser Django Docker
So, I have a dockerfile that I run Django via CapRover to run the backend of my website. Amongst the components, I have an admin panel that I log into using a superuser that I've created by ssh-ing into the docker container. The problem is that whenever I change my backend by uploading it as a .tar via CapRover, I have to create my superuser again. My question is, is there any way to avoid this by creating some sort of persistance? Or is there any way of automating this via my dockerfile? Thanks! -
Django, get canvas data and using it in views.py
I'm new to web development. I research this question online but can not find a proper solution yet. I want to create a web site that allows the user to draw a number on a canvas and the website can predict the number after clicking the button. My idea is to get the canvas data by using getImageData and put the data into the views.py. Right now I can saw my ImageData in the console, but I don't know how to load the data to views.py where I will run python code for the classification. function hwdClick() { document.getElementById("hwdB").innerHTML = "YOU CLICKED ME!"; var canvas = document.getElementById("hwdcanvas"); var ctx = canvas.getContext("2d"); var canvasData = ctx.getImageData(0,0,350,350); console.log(canvasData); } Do I have to use database in this case? Please give me some hint on this problem. -
"Base classes have conflicting values for attribute" when using a Python mixin to overide a base class method
I have a django mixin: class PublicSchemaOnlyAdminAccessMixin: def has_view_or_change_permission(self, request, obj=None): return connection.schema_name == get_public_schema_name() def has_add_permission(self, request): return connection.schema_name == get_public_schema_name() def has_module_permission(self, request): return connection.schema_name == get_public_schema_name() That is used in many of my ModelAdmin classes, for example: class BlockAdmin(PublicSchemaOnlyAdminAccessMixin, admin.ModelAdmin): pass But I'm getting warning about this structure from LGTM: Base classes have conflicting values for attribute 'has_add_permission': Function has_add_permission and Function has_add_permission. However, none of their proposed solutions seem to be practical for this, since I am using this in about half of my Admin classes. Is there either A. A better way for me to resolve this bad code structure or B. Is this code structure fine (as long as I understand the classes are read from right to left and the mixin must go on the left for consistant behaviour) -
How to save a HTML Canvas content to Google Storage
I am trying to save an html canvas content to Google Storage. What I do is as following : Create a signed url for the image file. class ThumbnailUploadSignedURL(APIView): @method_decorator(login_required(login_url='/login/')) def post(self, request): filename = request.POST.get('filename') filetype = request.POST.get('type') filesize = request.POST.get('size', 0) path = '{0}-{1}/{2}/'.format(request.user, request.user.id, thumbnail.name) blob = default_storage.open(full_path, 'wb') signed_url = blob.blob.generate_signed_url(expiration=default_storage.expiration, method='PUT', content_type='image/png') return Response({"thumbnail_signed_url":signed_url}) Get the content of canvas and send it to Google Storage. var image = canvas.toDataURL("image/png"); const xhr = new XMLHttpRequest(); xhr.open("PUT", data.thumbnail_signed_url, true); xhr.setRequestHeader('Content-Type', 'image/png'); xhr.send(image); The file is successfully being created on Google Storage, however the content is stated as corrupt, it is indeed basically base64. I also tried ways to convert base64 to png, yet unsuccesfully, as it was suggested here php-js-canvas example. How can I achieve this with js and google storage ? -
Django - recycle form field variable twice
I have a page where the user can create a new team, the html page is divided as such: user inputs a team name (if they want to, the page can return an animation with JS) First form by clicking next, it brings to the 2nd part: where the user inputs the team key others can use to join the team Second form Once the user clicks submits, it needs to be submitted as one form (team name + team key) to process. My problem is that I wish to reuse the {{form.team_name}} value for the 2nd part that I will use for a team creation. The form.py values look like this: class TeamCreationForm(forms.Form): team_name= forms.CharField(max_length=100, widget= forms.TextInput (attrs={ 'placeholder': 'MY TEAM', 'id':'inputText'})) team_k = forms.CharField(max_length=100, widget= forms.TextInput (attrs={ 'placeholder': 'ENTER KEY', 'id':'inputText'})) my team creation page looks like this: [...] <button style="float:left;">Go Back</button> <div> <canvas id="text" width="500" height="100"></canvas> <canvas id="stage" width="500" height="100"></canvas> </div> <div> <div id="Div1"> <form id="form"> {{form.team_name}} <input type="submit" value="TRY IT"> </input> <button type="button" id="nextBtn" onclick="switchVisible();">Next</button> </form> </div> <div id="Div2"> <form id="form" method="POST" style="top:342px; left:340px;">{% csrf_token %} {{form.team_k}} <input type="submit" value="CREATE"> </input> <button type="button" id="nextBtn" onclick="switchVisible();">Previous</button> </form> </div> </div> [...] For it to work, I would need … -
Heroku app crashes after pushing change with new dependencies
So I have a Django web app running on Heroku. I recently pushed an update where I added some API functionality via the Django Rest Framework. I installed this via pip. Now my Heroku app crashes. I assume I somehow need to install this dependency on Heroku? Here is the error message: An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail I tried entering the Heroku CLI and typing pip install djangorestframework but and running Heroku restart but it still crashes. -
Integrate twilio into webapp using postgres
I have a django app which stores phone numbers into a postgres database, I am looking to send sms to each of the numbers in the database as they are added via the webapp. I'm using pgadmin to monitor the database and it's all running on my localhost as of now, do I need to deploy it to get twilio working with the database? I can't seem to find any clear explanation as to how I can send the messages to the numbers stored as records in postgres, any help would be awesome! -
Issue with accessing Django Admin with the User table on the remote database and Django Native Admin related tables on the local databases
I'm trying to access the Django Admin using two databases. One is a local, while the other remote readonly legacy database has the User table. After logging in I get an error because the django_admin_log table is on the local database can't access the user table on the remote database. I'm using Django version 3.0.5. How could I fix this issue? -
django orderered model package
I use django ordered model to order my lines. when i drag and drop the file order from the front end. I call and endpoint to move the file to the next position. but in the response the order doesn't change. here is code models.py class Line(OrderedModel): """ Represents a segmented line from a document """ # box = gis_models.PolygonField() # in case we use PostGIS content = models.CharField(max_length=200,null=True,blank=True) document = models.ForeignKey(Document, on_delete=models.CASCADE, related_name='lines') # text direction order_with_respect_to = 'document' version_ignore_fields = ('document', 'order') external_id = models.CharField(max_length=128, blank=True, null=True) class Meta(OrderedModel.Meta): pass serializers.py class LineMoveSerializer(serializers.ModelSerializer): index = serializers.IntegerField() class Meta: model = Line fields = ('index',) def __init__(self, *args, line=None, **kwargs): self.line = line super().__init__(*args, **kwargs) def move(self): self.line.to(self.validated_data['index']) views.py @action(detail=True, methods=['post']) def move(self, request, document_pk=None, pk=None): line = get_object_or_404(Line, pk=pk) serializer = LineMoveSerializer(line=line, data=request.data) if serializer.is_valid(): serializer.move() lines = Line.objects.filter(document_part=part_pk).values('pk','order') return Response(status=status.HTTP_200_OK,data= {'moved': lines}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
How to change the default image location in the Django ImageField?
Having trouble trying to change where Django looks for the default image in the ImageField. I am trying to store a default image within a folder in my "media" file. Code from models.py below: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='profile_pics/default.jpg', upload_to='profile_pics') When I load the page I get a 404 error: Not Found: /media/default.jpg [21/Apr/2020 18:11:48] "GET /media/default.jpg HTTP/1.1" 404 1795 Any ideas on how to add the "profile_pics" piece to the path? -
How to serve static files using Traefik and Nginx in docker-compose
I am trying to serve static files using Traefik and Nginx, also docker. My Django application works well, I can access all pages, but can't setup static files serving. Here is my docker configuration. For the code skeleton, I am using cookiecutter-django django: build: context: . dockerfile: ./compose/production/django/Dockerfile image: dreamway_team_production_django depends_on: - postgres - redis env_file: - ./.envs/.production/.django - ./.envs/.production/.postgres command: /start postgres: ** traefik: build: context: . dockerfile: ./compose/production/traefik/Dockerfile image: dreamway_team_production_traefik depends_on: - django - nginx volumes: - production_traefik:/etc/traefik/acme ports: - "0.0.0.0:80:80" - "0.0.0.0:443:443" redis: ** nginx: image: nginx:1.17.4 depends_on: - django volumes: - ./config/nginx.conf:/etc/nginx/conf.d/default.conf - ./dreamway_team/static:/static and my config for traefik log: level: INFO entryPoints: web: address: ":80" web-secure: address: ":443" certificatesResolvers: letsencrypt: acme: email: "mail" storage: /etc/traefik/acme/acme.json httpChallenge: entryPoint: web http: routers: web-router: rule: "Host(`[DOMAIN_NAME]`)" entryPoints: - web middlewares: - redirect - csrf service: django web-secure-router: rule: "Host(`[DOMAIN_NAME]`)" entryPoints: - web-secure middlewares: - csrf service: django tls: certResolver: letsencrypt middlewares: redirect: redirectScheme: scheme: https permanent: true csrf: headers: hostsProxyHeaders: ["X-CSRFToken"] services: django: loadBalancer: servers: - url: http://django:5000 providers: file: filename: /etc/traefik/traefik.yml watch: true Any help would be appreciated! Thanks! -
Cannot install whitenoise
I am attempting to run the command pip install django-heroku, but whenever I do, it stops with the error ERROR: Package 'whitenoise' requires a different Python: 2.7.16 not in '>=3.5, <4'. I have tried to run pip install whitenoise, but that doesn't work. Same error. I am using Python 3.8.2 -
Django model form, not saving to DB correctly
I've looked at a couple of other questions on here, but can't seem to get any results.. I don't seem to get any errors thrown at me, so I'm not sure where I'm going wrong. I believe I may be using the primary key incorrectly. I do not want to put 'User' under my model form as it would allow someone to change someone else's fields. class history(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) gallons_requested = models.IntegerField() delivery_address = models.CharField(max_length=100) delivery_date = models.DateField() suggested_price = models.DecimalField(max_digits=6, decimal_places=2) total_amount_due = models.DecimalField(max_digits=6, decimal_places=2) def testing(request): if request.method == 'POST': form = RequestForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('pricing_module') else: form = RequestForm(instance=request.user) args = {'form': form} return render(request, 'pricing_module.html', args) -
how can i get all the data from my model booking having date less than today i want to show the booking history of customer
view.py def Profile(request,uid): book =booking.objects.filter(user=uid) user =User.objects.get(id=uid) books = booking.objects.filter(created__lt=datetime.today(),user=uid) params={'book':book,'user':user,'books':books} return render(request, 'hotel/userProfile.html',params) -
windows django data source name not found and no default driver specified
I'm trying to connect to SQL Server studio v17.2 This is the code that works fine in my local computer DATABASES = { 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'ENGINE': 'sql_server.pyodbc', 'NAME': 'database', 'HOST': '10...', 'USER': 'user', 'PASSWORD': 'password', #'DRIVER':'ODBC Driver 17 for SQL Server' 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server',} } } This is the error I am getting: windows django data source name not found and no default driver specified -
How to test if the billing address provided is linked to the card number Stripe
I am trying to implement stripe in my website. I am using the test mode of stripe and using their provided card numbers for testing purpose. But I also want to check if any random billing address is linked to the card. I want to create a test scenario in which a card number is linked to a billing address and later in my website I want to enter random data billing to address if the payment fails or not. Is there anything in stripe that would help me achieve this functionality. -
Django, how can open modal form with value using jquery?
I'm new at django and jquery, I have a data table in which in the last column I have created the bottom "edit" that give me the possibility to modify the value of the row data. But when I clcik on the bottom and open the html modal, all fields are empty, but I want that it give me the value of single items as stored. My Modal: <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> <h4 class="modal-title" id="myModalLabel">Modifica Materia Prima</h4> </div> <form id="updateUser" action=""> <div class="modal-body"> <input class="form-control" id="form-id" type="hidden" name="formId"/> <label for="codice">codice</label> <input class="form-control" id="form-codice" type="text" name="formCodice"/> <label for="tipologia">tipologia</label> <input class="form-control" id="form-tipologia" type="text" name="formTipologia"/> <label for="sottocategoria">sottocategoria</label> <input class="form-control" id="form-sottocategoria" type="text" name="formSottocategoria" min=10 max=100/> </div> <div class="modal-footer"> <button type="submit" class="btn btn-primary" >Save changes</button> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </form> </div> </div> My Javascript $("form#updateUser").submit(function() { var idInput = $('input[name="formId"]').val().trim(); var codiceInput = $('input[name="formCodice"]').val().trim(); var tipologiaInput = $('input[name="formTipologia"]').val().trim(); var sottocategoriaInput = $('input[name="formSottocategoria"]').val().trim(); if (codiceInput && tipologiaInput && sottocategoriaInput) { // Create Ajax Call $.ajax({ url: '{% url "crud_ajax_update" %}', data: { 'id': idInput, 'codice': codiceInput, 'tipologia': tipologiaInput, 'sottocategoria': sottocategoriaInput }, dataType: 'json', success: function (data) { if … -
module 'django.contrib.messages.constants' has no attribute 'success'
The documentation of django says 'success' is a function of django.contrib.messages.constants but when I execute django.contrib.messages.constants.success ,error comes as module 'django.contrib.messages.constants' has no attribute 'success' Error AttributeError at /contact module 'django.contrib.messages.constants' has no attribute 'success' Request Method: POST Request URL: http://127.0.0.1:8000/contact Django Version: 3.0.5 Exception Type: AttributeError Exception Value: module 'django.contrib.messages.constants' has no attribute 'success' Exception Location: C:\Users\User\PycharmProjects\Django\Hello\home\views.py in contact, line 35 Python Executable: C:\Users\User\AppData\Local\Programs\Python\Python38\python.exe Python Version: 3.8.0 Python Path: ['C:\Users\User\PycharmProjects\Django\Hello', 'C:\Users\User\AppData\Local\Programs\Python\Python38\python38.zip', 'C:\Users\User\AppData\Local\Programs\Python\Python38\DLLs', 'C:\Users\User\AppData\Local\Programs\Python\Python38\lib', 'C:\Users\User\AppData\Local\Programs\Python\Python38', 'C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages', 'C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\pyzmail-1.0.3-py3.8.egg', 'C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\distribute-0.7.3-py3.8.egg', 'C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\win32', 'C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\win32\lib', 'C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\Pythonwin'] views.py from django.shortcuts import render, HttpResponse from datetime import datetime from home.models import Contact from django.contrib.messages import constants as messages def contact(request): if request.method == 'POST': name = request.POST.get('name') email = request.POST.get('email') phn = request.POST.get('phn') desc = request.POST.get('desc') cont = Contact(name=name,email=email,phn=phn,desc= desc,date=datetime.today()) cont.save() messages.success(request, 'Your mesaage has been sent') return render(request, 'contact.html') models.py from django.db import models class Contact(models.Model): name = models.CharField(max_length=122) email = models.CharField(max_length=122) phn = models.CharField(max_length=13) desc = models.TextField() date = models.DateField() admin.py from django.contrib import admin from home.models import Contact # Register your models here. admin.site.register(Contact) settings.py """ Django settings for Hello project. Generated by 'django-admin startproject' using Django 3.0.5. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their … -
Django html extends tags
This is my base.html <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> </head> <body> {% block content %}{% endblock content %} </body> </html> This is home_page where I am using the {% extends 'base.html' %} {% load static %} {% block content %} <div class="container"> <h1>{{ title }}</h1> <h1>Hello, world!</h1> <img src="{% static 'img/myImage.jpg' %}" class='img-fluid'> </div> {% if premium_content %} <div class="row"> <div class="col"> <h1>Premium</h1> {{ premium_content }} </div> {% endif %} </div> {% endblock content %} The here is my views.py where I have the home_page and before using the extends tag I could render this page properly def home_page(request): context = { "title":"Hello World We Working" } if request.user.is_authenticated: context["premium_content"] = 'Only premium users see this' return render(request, 'MainApp/home_page.html', context) The error message that I am getting is TemplateDoesNotExist at / Which I do not understand I even tried putting the two html files in the same directory but still I get the same error message -
Django Vote System - django-secretballot and django-vote both are falty for me, should I write voting system myself?
I would like to ask you for your help. I want to have some simple voting system on my django app. I googled it and I found two systems and some posts about not reinventing wheel and I am all for that :P First I tried to go with django-vote, it was updated two years ago. I setup it, added into apps, models, created function for it with user_id but I got error with "LazyObject". user_id from django-vote was expecting int, and not actual user name like it is in my app. So I went with django-secretballot next. But soon after adding it into middleware and apps I am getting error while I want to migrate: ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding' And right now I am lost. Should I try to ask for help and try to fix any of those two applications or I should look for another one or try to write it myself since I need only basic functions? Which approach would be better? Thanks and Cheers! -
DJANGO_SETTINGS_MODULE
Regarding : django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I have tried every possible solution that is out there on the web, but unfortunately without any luck so far. I have noticed however that Django is not appearing under 'File -> Settings -> Languages & Frameworks', although it seems I have installed it properly (I am able to retrieve Django version number 3.0.5 and when I run manage.py, I get a list of the available subcommands). Also 'os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Eric.settings')' is properly set in manage.py file. Still I am running into the above error whenever I try to run 'django-admin runserver' ! I was expecting to find Django in the Languages & Frameworks section, but it seems to be missing there. Is this OK or NOK ? Thanks -
IntegrityError (1452, 'Cannot add or update a child row: a foreign key constraint fails)
I'm using a custom user model (following this tutorial) and all works well. When I'm logged in with the admin user I created with createsuperuser in the /admin session I can add/remove/edit anything I want. When I'm logged in with some other user, to which I've given staff and admin powers, I get this error whenever I want to add something to the database: IntegrityError at /admin/users/user/13/change/ (or whichever action I'm doing) (1452, 'Cannot add or update a child row: a foreign key constraint fails (`NMS_database`.`django_admin_log`, CONSTRAINT `django_admin_log_user_id_c564eba6_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`))') [...]Exception Location: /home/me/python_ve/lib/python3.8/site-packages/MySQLdb/connections.py in query, line 239 This is my user model: class User(AbstractBaseUser): email = models.EmailField(verbose_name="email", unique=True, max_length=255) first_name = models.CharField(max_length=30, blank=True, null=True) surname = models.CharField(max_length=30, blank=True, null=True) additional = models.BooleanField(default=False) individual = models.BooleanField(default=True) active = models.BooleanField(default=True) #can they login? staff = models.BooleanField(default=False) #staff user non superuser admin = models.BooleanField(default=False) #superuser date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' # default identifier for that user which will used for logging in #email (USERNAME_FIELD in this case) and password are required by default REQUIRED_FIELDS = ['first_name', 'surname'] def __str__(self): return "%s %s" % (self.first_name, self.surname) def get_full_name(self): return self.first_name def has_perm(self, perm, obj=None): return self.admin def has_module_perms(self, app_label): …