Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to add custom error messages in modelform widgets in django
these are fields of the model form class Meta: model = Employee exclude = ('user', 'created_by', 'is_deleted', 'created') theses are the widgets widgets = { 'first_name': forms.TextInput(attrs={'placeholder': _('First name')}), 'last_name': forms.TextInput(attrs={'placeholder': _('Last name')}), 'house_name': forms.TextInput(attrs={'placeholder': _('House name / flat No')}), 'street_name': forms.TextInput(attrs={'placeholder': _('Street Name / No')}), 'locality_name': forms.TextInput(attrs={'placeholder': _('Locality Name / No')}), 'pin_code': forms.TextInput(attrs={'placeholder': _('Zip Code')}), } -
"badly formed hexadecimal UUID string" when filtering a GraphQL query on multiple IDs (Graphene-Django)
I have Django models Photo and Tag which have a many-to-many relationship joined through the model PhotoTag. This is the relevant bit from models.py - note they inherit from UUIDModel so have UUIDs as the primary key rather than the default auto-increment ID. Models class Photo(UUIDModel): taken_at = models.DateTimeField(null=True) taken_by = models.CharField(max_length=128, blank=True, null=True) aperture = models.DecimalField(max_digits=3, decimal_places=1, null=True) exposure = models.CharField(max_length=8, blank=True, null=True) iso_speed = models.PositiveIntegerField(null=True) ... class Tag(UUIDModel): name = models.CharField(max_length=128) ... class PhotoTag(UUIDModel): photo = models.ForeignKey(Photo, related_name='photo_tags') tag = models.ForeignKey(Tag, related_name='photo_tags') ... For the Graphene-Django schema I have two filters defined for all_photos - fetching photos by tag names and fetching by tag ids where tag is assigned through the photo_tags relationship. The schema definition is below - photo_tags__tag__id = graphene.String() is my attempt to prevent the error badly formed hexadecimal UUID string and I hoped that making it a graphene.String() would allow it to be split. Schema class CustomNode(graphene.Node): class Meta: name = 'Node' @staticmethod def to_global_id(type, id): return id class PhotoInterface(graphene.Interface): photo_tags__tag__id = graphene.String() class PhotoNode(DjangoObjectType): class Meta: model = Photo interfaces = (CustomNode, PhotoInterface) class PhotoFilter(django_filters.FilterSet): class Meta: model = Photo fields = { 'photo_tags__tag__id': ['exact', 'in'], 'photo_tags__tag__name': ['exact', 'icontains', 'in'], } class Query(object): … -
Django ForeignKey Model Form
I'm newbie on Django. I have two model and one of this model have Foreign Key. I'm using Model Form in forms and when I fill the form my foreign key field return null. What I want is when I fill the form foreign key field, fill according to the pointed out by the foreign key. Models: class customerInfo(models.Model): customerName = models.CharField(max_length = 50) customerContent = models.TextField(max_length = 50) createdDate= models.DateTimeField(auto_now_add = True) def __str__(self): return self.customerName class productInfo(models.Model): username = models.CharField(max_length = 50) passwd = models.CharField(max_length = 50) destIp = models.CharField(max_length = 50) hostname = models.CharField(max_length = 50) productName = models.CharField(max_length = 50) customer = models.ForeignKey(customerInfo,on_delete = models.CASCADE,null=True) def __str__(self): return self.productName Forms: class customerForm(forms.ModelForm): class Meta: model = customerInfo fields = ( "customerName", ) class addProductForm(forms.ModelForm): class Meta: model = productInfo fields = ( "productName", ) class productInfoForm(forms.ModelForm): class Meta: model = productInfo fields = ( "username", "passwd", "destIp", "hostname", ) Views: @login_required(login_url = "/") def addCustomer(request): form = customerForm(request.POST or None) content = {"form" : form,} if form.is_valid(): form.save() customerName = form.cleaned_data['customerName'] return redirect("addproduct") else: return render(request,"addcustomer.html",content) @login_required(login_url = "/") def addProduct(request): form = addProductForm(request.POST or None) content = {"form" : form} if form.is_valid(): global productName productName … -
Validate each value of an ArrayField of emails in Django
I am using PostgreSQL with Django and am trying to use ArrayField(models.EmailField(max_length=200)) but i am ending up with an 500 error code(TypeError) when giving invalid email address. #models.py billing_emails = ArrayField(models.EmailField(max_length=200)) company = models.OneToOneField(Company, on_delete=models.CASCADE) How can i validate each email in the ArrayField.I have tried writing validate method in both serializer and models....but nothing helped..What is the right way to validate ArrayFields.I am using django 2.1 and python 3.6 Thanks in advance -
how to access non defined database in django?
I have a problem with my application. i dont how to access non defined database in Django. where in my application user creates his own database if they needed. but Django cannot support database which is not defined. how to solve this issue. -
Why is Django blog app throwing FileNotFoundError / Errno2 No such file or directory?
I have a Django based blog application that is currently connected to Heroku. Media files are being served from S3 Bucket AWS and are displayd on my index page: Image of my index page The issue arises when I attempt to update the image in Profile OR create a new Profile OR when I am attempting to log into a profile that has an image stored on my s3 bucket, I get the error: FileNotFoundError at /login/ [Errno 2] No such file or directory 'profile_pics/Screen_Shot_2018-09-30_at_6.51.47_PM.png' AND notice this code near the bottom of the error: /app/users/signals.py in save_profile instance.profile.save() ... ▶ Local vars /app/users/models.py in save img.save(self.image.name) ... ▶ Local vars /app/.heroku/python/lib/python3.6/site-packages/PIL/Image.py in save fp = builtins.open(filename, "w+b") I am also using PIL to resize the image in my models.py file: from django.db import models from django.contrib.auth.models import User from PIL import Image from django.core.files.storage import default_storage as storage class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, **kwargs): super().save() #img = Image.open(self.image.path) img = Image.open(storage.open(self.image.name)) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.name) Just for context this is my settings.py: import os # Build paths … -
Nested Serializer Problem in showing reverse
I defined this model: class city (models.Model): city_name = models.CharField(max_length=100) state = models.ForeignKey(state,related_name='state', on_delete=models.CASCADE) def __str__(self): return self.city_name and this serializer: class citySerializers(serializers.ModelSerializer): class Meta: model = city fields = ('city_name') If I add the state to my serializers field it shows me state_id of the table but I want it to show me state_name(another field of the state table ) I found this tutorial:https://www.django-rest-framework.org/api-guide/relations/ but here inside parent model shows child model item, I want inside child model show parent name(reverse of what tutorial do) how can I do? -
TemplateDoesNotExist at /board/boards
I got this error during the python django project I do not understand why the template does not connect. Please let me know which part of the error it is and let me know how to fix it. How can I to do? Attach an error picture. enter image description here settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] These are my project sub-lists /mysite /board /migrations /templates /board board_list.html board_detail.html search.html __init__.py admin.py apps.py forms.py models.py tests.py urls.py views.py /mysite __init__.py settings.py urls.py views.py wsgi.py /static css js image /templates base.html main.html db.sqlite3 manage.py /mysite/mysite/urls.py from django.contrib import admin from django.conf.urls import url, include from .views import MainHome urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', MainHome.as_view(), name='main'), url(r'^board/', include('board.urls', namespace='board'), ] /mysite/board/urls.py from django.conf.urls import url from .views import * from mysite.views import MainHome app_name = 'board_app' urlpatterns = [ url(r'^$', MainHome.as_view(), name='main'), url(r'^search/$', SearchFormView.as_view(), name='search'), url(r'^boards/$', BoardList.as_view(), name='board_list'), url(r'^boards/(?P<slug>[-\w]+)/$', BoardDetail.as_view(), name='board_detail'), ] /mysite/borad/views from .models import Board from django.views.generic import ListView --- skip --- class BoardList(ListView): model = Board template_name = 'board_list.html' content_object_name = 'boards' paginate_by = 10 --- skip --- -
Uploading images to amazon s3 using boto3 from django
import boto3 from botocore.client import Config ACCESS_KEY_ID = 'XXXXXXXXXXXXXXXX' ACCESS_SECRET_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXX' BUCKET_NAME = 'https://s3.amazonaws.com/test-dev-bkt' data = open('/home/kuliza270/Desktop/workspace/hdfc-csrm-backend/webapp/statics/img/headerLogoNew.jpg', 'rb') s3 = boto3.resource( 's3', aws_access_key_id=ACCESS_KEY_ID, aws_secret_access_key=ACCESS_SECRET_KEY, config=Config(signature_version='s3v4') ) s3.Bucket(BUCKET_NAME).put_object(Key='logo.jpg', Body=data) print ("Done") -
How use python-docx to stream a file from template
Ok so right now I have a function in my django app that creates a word document like so: def form_view(request): if request.method == 'POST': #do a bunch of things context = { 'model_1' : model_1, } in_template = "Forms/mytemplate.docx" doc = DocxTemplate(in_template) doc.render(context) out_filename = "outfile.docx" http_word_response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document') http_word_response['Content-Disposition'] = 'attachment; filename=%s' % out_filename doc.save(http_word_response) return http_word_response else: return render( request, 'mysite/form.html', context) So right now, the file is served up as the http_word_response variable and it works great I want to change this so that the file is actually created and saved into S3, but I'd like to not save the file locally first and just use the stream function of the python-docx package: https://python-docx.readthedocs.io/en/latest/user/documents.html#opening-a-file-like-document Here's the sample it gives: with open('foobar.docx', 'rb') as f: source_stream = StringIO(f.read()) document = Document(source_stream) source_stream.close() ... target_stream = StringIO() document.save(target_stream) I'm not sure how to translate that sample into reading in my template file and outputting a file/object I can then send to S3 and do something with. My best guess would start like this: with open(in_template, 'rb') as f: source_stream = StringIO(f.read()) doc = DocxTemplate(source_stream) source_stream.close() target_stream = StringIO() document.save(target_stream) But then I get confused on where my doc.render(context) … -
Why does the PATCH of the HTTP method run the model save() method?
I use serializers.ModelSerializer and viewsets.ModelViewSet of Django REST Framework in my REST API. While I was testing, I found out that the PATCH of HTTP method was running model save(). I know PATCH is for updating data, Why DRF use save() instead of update()? -
Async await in django channels cannot get object with id
My consumers.py: async def user_taskcompleted(self, event): me = User.objects.get(username=event['username']) print("ME",me) mentor=me.mentor print("MY MENTOR", mentor) id_task =event['task'] print("GETTING ID",id_task) notification = event['username'] + ' Completed new Task ' + event['title'] print("notification", notification) task = await Task.objects.get(id=id_task) obj = await self.create_notification_to_trainer(me,notification,task) obj.receiver.add(mentor) await self.send_json(event) print("Got message {} at {}".format(event, self.channel_name)) @database_sync_to_async def create_notification_to_trainer(self, sender,notification,task): return Notification.objects.create(sender=sender ,notification=notification,task=task) My signals.py: @receiver(post_save, sender=Task) def create_task_notification(sender, instance, created, **kwargs): if Task.objects.filter (student=instance.student,student__mentor__isnull=False).exists(): if created: channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( "gossip", {"type": "user.taskcompleted", "event": "New Task", "task": instance.id, "username": instance.student.username, "title": instance.title, "mentor": instance.student.mentor.username }) print("TASK ID",instance.id) else: print("NO TRAINER") Im trying to save data to the model in my consumers.py to save a notification on a Task save.The problem is that im not able to get the task using the task id in my consumers.py.It shows Task matching query does not exist in my terminal. THe print statements for all other fields are showing in my terminal and im also able to get the correct task id returned As shown in my terminal: TASK ID 323 ME mohitharshan123 MY MENTOR rohitharshan GETTING ID 323 notification mohitharshan123 Completed new Task safasfa The error is showing at Task.objects.get(id=id_task) -
Silencing exceptions in `makemigrations` can be silenced by in `check`, Django. 2.0
Using a version of django-proxy-overrides, I'm overriding a field in a Proxy model that appears a the base model. I'm using Django 2.0 This causes Django's system-check framework to complain, but in my settings file I have set: SILENCED_SYSTEM_CHECKS = ["fields.E305", "fields.E304", "models.E006", "models.E017"] so python manage.py runserver works fine (and the overriding works beautifully). However, when I run python manage.py makemigrations, Django raises an exception complaining about the clash in names: django.core.exceptions.FieldError: Local field 'person' in class 'ProxyBillSponsorship' clashes with field of the same name from base class 'BillSponsorship'. Is there anyway around this? I have tried setting class Meta: managed=False on the the proxied models in the hope that makemigrations would ignore these models, but no luck. -
django:ModuleNotFoundError: No module named 'pure_pagination'
I used "pip install django-pure-pagination", and regiter "pure_pagination" into seetings.py. By use "help('pure_pagination')", I can find the module. But when I debug it on the PycharmIDE. It showes "ModuleNotFoundError: No module named 'pure_pagination' ". enter image description here enter image description here -
How to compare 2 fields in django 2.1?
Models.py This is my model class where i have 2 tables .on each table we have a field called label.My question is that how will i compare the 2 labels and return values to a new field (returnlabel) class Server(models.Model): label = models.TextField(max_length=200,null=True) #compare this upload1 = models.FileField(null=True, blank=True) Image1 = models.TextField(upload1, null=True) class Android(models.Model): label=models.TextField(max_length=200,null=True) #with this imagestring=models.TextField(null=True,blank=True) returnlabel=models.TextField(null=True,blank=True) #return to this Serializers Class class FoodSerializers(serializers.HyperlinkedModelSerializer): class Meta: model=Server fields=('url','label','Image1','upload1') class AndroidSerializers(serializers.ModelSerializer): class Meta: model = Android fields = ('label', 'imagestring', 'returnlabel') Views class FoodViewSet(viewsets.ModelViewSet): queryset = Server.objects.all() serializer_class =FoodSerializers class Androids(viewsets.ModelViewSet): queryset =Android.objects.all() serializer_class = AndroidSerializers -
Single javascript controller for a audio files generated through loop in Django
I am trying to find a way to have a single javascript controller so i could play the audio files that were shown on the list using a loop in my django app : <script type="text/javascript"> {% for m_word in movie_vocab %} ## here i could generate the ids for each instance of movie_vocab {% endfor %} {% for b_word in blog_vocab %} ## here i could generate the ids for each instance of blog_vocab {% endfor %} {% for e_word in event_vocab %} ## here i could generate the ids for each instance of blog_vocab {% endfor %} var music = document.querySelectorAll([here i could have a list of ids so i can play and pause them ]) function play() { if (music.paused) { music.play(); pButton.value = "Pause"; pButton.className = "btn btn-primary"; } else { music.pause(); pButton.value = "Continue"; pButton.className = "btn btn-light"; } } </script> Hopefully this kind of solution could also pause a previous audio when i would click on the different button Is it possible to do sth like that in javascript ?? -
Program hangs after docker-compose up command for django app
I am trying to run a simple django app through a docker container, using docker-compose. Everything works perfectly down to when I insert the commands 'docker-compose up', which then performs system checks, has no issue, but then hangs. -
Django-Import-Export to import CSV, how to work with u'\\ufeff, UTF-8 BOM issue?
When I'm trying to import CSV file using django-import-export modules gives this error, KeyError: u"Column 'id' not found in dataset. Available columns are: [u'\ufeffid', u'username', u'name', u'email']" -
How to get current user in forms.py def save(self)?
How to get user logged in def save(self, commit=True) at forms.py. I tryed self.request.user, but doesn't work...self doesn't have request :/ Can anyone help me? -
Django deploy Gunicorn and NginX
While trying to finally deploy my NEW rover web app a problem occured. I already configured Gunicorn and bind it to 0.0.0.0:80 (with wsgi). Website loads, but without any images, css, javascript files (even "admin" site is without any style). Postgres is installed and running fine. I already did python manage.py collectstatic python manage.py migrate I watched tons of tutorials how to do it. But still after I try to run: systemctl status nginx.service i get an error: Job for nginx.service failed because the control process exited with error code. See "systemctl status nginx.service" and "journalctl -xe" for details. #systemctl status nginx.service output: ● nginx.service - A high performance web server and a reverse proxy server Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since śro 2018-11-28 02:57:12 CET; 1min 13s ago Process: 14721 ExecStop=/sbin/start-stop-daemon --quiet --stop --retry QUIT/5 --pidfile /run/nginx.pid (code=exited, status=2) Process: 25481 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=1/FAILURE) Process: 25477 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS) Main PID: 10279 (code=exited, status=0/SUCCESS) nginx[25481]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use) nginx[25481]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use) nginx[25481]: nginx: [emerg] … -
Using {{ form.media }} for multiple forms is causing jquery to be loaded multiple times?
I am restoring an old Django project and noticed I was getting a console error when I loaded a page: TypeError: $(...).select2 is not a function. After some searching on the internet I found that the error could be related to Jquery being loaded more than once. So I looked at the rendered source for all of my pages and saw that where ever in my template I use {{form.meda}} it adds all of these scripts in: <link href="/static/admin/css/vendor/select2/select2.css" type="text/css" media="screen" rel="stylesheet" /> <link href="/static/admin/css/autocomplete.css" type="text/css" media="screen" rel="stylesheet" /> <link href="/static/autocomplete_light/select2.css" type="text/css" media="screen" rel="stylesheet" /> <script type="text/javascript" src="/static/admin/js/vendor/jquery/jquery.js"></script> <script type="text/javascript" src="/static/autocomplete_light/jquery.init.js"></script> <script type="text/javascript" src="/static/admin/js/vendor/select2/select2.full.js"></script> <script type="text/javascript" src="/static/autocomplete_light/autocomplete.init.js"></script> <script type="text/javascript" src="/static/autocomplete_light/forward.js"></script> <script type="text/javascript" src="/static/autocomplete_light/select2.js"></script> <script type="text/javascript" src="/static/autocomplete_light/jquery.post-setup.js"></script> Keep in mind that I have multiple forms in other templates and use {{form.media}} all over. I didn't realize it all of those scrips were being added each time for every {{form.media}} and I feel it might be causing problems. I am also using Django Autocomplete-light (dal) for some of my form widgets and notice that it also is not working. Is it normal to have all of those scrips added from form.media? Why would it be adding /static/admin/js/vendor/jquery/jquery.js multiple times (or at all) … -
Django Rest Framework : Authentication credentials were not provided
Images in the current database have one piece of data. But, I am currently experiencing the following error "GET /images/all/ HTTP/1.1" 401 58" "detail": "Authentication credentials were not provided." My Git Hub URL : https://github.com/Nomadcoders-Study/Nomadgram Which part of the setup went wrong? -
Breadcrumbs Django python
Can any one help me in creating breatingcrumbs dynamically for Django 2.1versions.i have tried so many plugins but am getting the errors in plugin code itself.. Pl help me. Waiting for the response -
Displaying different Django forms at different template locations
I have a model like this: models.py from django.db import models class Foo(models.Model): text = models.TextField() Example instances of this model are: Foo.objects.create(text="My first text [[@shorttext_1@]] random text.") Foo.objects.create(text="Select something from below [[@multipleselect_1@]]. text.") Foo.objects.create(text="A different form [[@shorttext_1@]] and another" "form [[@shorttext_2@]] random texts.") Foo.objects.create(text="Mixed form [[@shorttext_1@]] and another" "form [[@multipleselect_1@]] random text.") The values [[@shorttext_1@]], [[@multipleselect_1@]] represent the location and the type of the forms to be placed in the template below. [[@ @]] is a randomly chosen markdown style placeholder. forms.py from django import forms class ShortTextForm(forms.Form): # [[@shorttext_1@]] form short_text = forms.CharField(max_length=300) class MultipleSelectionForm(forms.Form): # [[@multipleselect_1@]] form selection = forms.ChoiceField( choices=[('A', 'A text'), ('B', 'B text')], widget=forms.RadioSelect()) views.py from django.shortcuts import render def text_view(request): if request.method == 'POST': # get the info for each form else: foo = Foo.objects.order_by('?').first() return render( request=request, template_name='templates/index.html', context={'text': foo.text}) templates/index.html {% extends "base.html" %} {% block body %} {{ text }} {% endblock %} Is it possible to show the foo.text in template and render the desired forms? Currently, I have a type variable in my Foo class to designate the type of the form. And my view can render only one desired type of form which can only placed at … -
Encrypt InMemoryUploadfile and save the encrypted file on disk
I searched for different solution for encryption for user uploaded file. All of the tutorials or solution which i found where about opening an existing file on the disk encrypting it and and saving it to the disk. I am trying to encrypt the user uploaded file with out saving the original file and directly saving the encrypted file. Right now user upload > save to disk > open the file > encrypt it >save the encrypted file > delete the original file i am doing this now.