Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError when setting custom DEFAULT_METADATA_CLASS
I have written a custom metadata class for OPTION requests. This class is located in myproject.api.metadata.py and is called PermissionsMetadata. On individual views, I can set metadata_class = PermissionsMetadata and it works as expected. However, when setting DEFAULT_METADATA_CLASS in my settings like so: REST_FRAMEWORK = { 'DEFAULT_METADATA_CLASS': 'api.metadata.PermissionsMetadata', ... } ... I get the following when running any test: ImportError: Could not import 'api.metadata.PermissionsMetadata' for API setting 'DEFAULT_METADATA_CLASS'. AttributeError: module 'rest_framework.views' has no attribute 'APIView'. I just need the metadata class to apply to all views by default without having to set the metadata_class attribute on every view. I don't mind moving the class elsewhere. By the way, setting the default metadata class to rest_framework.metadata.SimpleMetadata doesn't result in this exception. Help greatly appreciated. -
How to fix ImageField upload in django rest framework?
I am trying to upload a profile image to the media folder, while this works perfectly from the django admin web interface, it doesn't upload from the api endpoint, it gives the media root with image name, but i cannot access the image nor is it in the location pointed to by the get_upload_path method. Any help would be greatly appreciated. settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") This is expected result: '"http://127.0.0.1:8000/media/profile_photo/aafaaaaaa2a%40gmail.com/lol.jpg"' This is what am getting: "http://127.0.0.1:8000/media/test.jpg" -
install django on centos 6 (sqlite3 error)
I am trying to install Django 2.1 on Centos6 but I'v got no success. according to this issue and this documentations of Django 2.1, Django 2.1 needs SQLite 3.7.15 and later. after knowing this I tried to upgrade sqlite and sqlite-devel to 3.7.17 by CERT Forensics repo but nothing changed after upgrading to 3.7.17 and I still get this error at running server by manage.py: Performing system checks... System check identified no issues (0 silenced). Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f7561c29950> Traceback (most recent call last): File "/root/django-project/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/root/django-project/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/root/django-project/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 159, in get_new_connection conn = Database.connect(**conn_params) sqlite3.NotSupportedError: URIs not supported The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/root/django-project/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/root/django-project/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check_migrations() File "/root/django-project/venv/lib/python3.6/site-packages/django/core/management/base.py", line 442, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/root/django-project/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/root/django-project/venv/lib/python3.6/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/root/django-project/venv/lib/python3.6/site-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "/root/django-project/venv/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 61, in applied_migrations if self.has_table(): File "/root/django-project/venv/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 44, in has_table return self.Migration._meta.db_table … -
How to set field value based on what user click in Django ListView
I have two models Parent and Child. I would like to display both values in a ListView, whereby there is an Add Child button for each family. Supposed that the parents are already populated, when I click Add Child, I would love that in the form of Child, the parent field are already set to the corresponding family name (please see code below). Simple model would be: class Family(models.Model): family_name = models.CharField(max_length=100, default='', blank=False) father_name = models.CharField(max_length=100, blank=False, default='') mother_name = models.CharField(max_length=100, blank=False, default='') def get_absolute_url(self): return reverse('family-list') def __str__(self): return str(self.family_name) class Children(models.Model): parent = models.ForeignKey(Family, blank=False, default=None, null=True, on_delete=models.PROTECT, related_name='their_child') child_name = models.CharField('4Jet ID', max_length=100, default='', blank=False) birth_date = models.DateField(default=timezone.now, blank=False) def get_absolute_url(self): return reverse('family-list') # both return to family list view The View using simple generic view: class FamilyList(ListView): model = Family template_name = '/family_list.html' context_object_name = 'fam_list' # class NewParent omitted class NewChild(CreateView): model = Children template_name = '/child_new.html' context_object_name = 'child' fields = [ 'parent', 'child_name', 'birth_date' ] and the simplified template: <!--file: family_list.html--> {% for fam in fam_list %} <table> <tr> <th class="header"></th> <th class="header">Family Name</th> <th class="header">Father's First Name</th> <th class="header">Mother's First Name</th> <th class="header">Add Child</th> </tr> <tr> <td>+</td> <td>{{ fam.family_name }}</td> <td>{{ … -
Use Celery with 2 Django applications
I have a question about Celery with 2 Django applications on the same server (server is a FREEBSD server). Let suppose that we have app1 and app2. App1 gets a celery.py file like this : import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'main.settings.base') app = Celery('main-app1') app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() The second one has the same file but I changed app = Celery('main-app1') to app = Celery('main-app2') On my server, I have a celeryd file configured for app1 like this : # Names of nodes to start # most people will only start one node: CELERYD_NODES="worker" # but you can also start multiple and configure settings # for each in CELERYD_OPTS #CELERYD_NODES="worker1 worker2 worker3" # alternatively, you can specify the number of nodes to start: #CELERYD_NODES=10 # Absolute or relative path to the 'celery' command: #CELERY_BIN="/usr/local/bin/celery" #CELERY_BIN="/usr/local/www/app1/venv/bin/celery" CELERY_BIN="/usr/local/bin/celery" # App instance to use # comment out this line if you don't use an app CELERY_APP="main-app1" # Where to chdir at start. CELERYD_CHDIR="/usr/local/www/app1/src/web/" # Extra command-line arguments to the worker CELERYD_OPTS="--time-limit=300 --concurrency=8" # Configure node-specific settings by appending node name to arguments: #CELERYD_OPTS="--time-limit=300 -c 8 -c:worker2 4 -c:worker3 2 -Ofair:worker1" # Set … -
'NoneType' object has no attribute 'name'. Why i am getting this error?
Below is my code. please review it. I never got this error before, is it due to the below code or some conflict with other codes in production system. def put(self, request, domain, pk="me", **kwargs): object = DomainConfiguration.objects.get() partial = kwargs.pop('partial', False) serializer = DomainConfigSerializer(object, data=request.data, partial=partial) if serializer.is_valid(): object = serializer.save() company_data = request.data.get('company', None) if company_data: if not partial: object.company.name = company_data.get('name') object.company.address = company_data.get('address') object.company.city = company_data.get('city') object.company.state = company_data.get('state') object.company.position = company_data.get('position') object.company.postcode = company_data.get('postcode') object.company.country_iso3 = \ company_data.get('country_iso3') object.company.industry = company_data.get('industry') object.company.size = company_data.get('size') object.company.revenue = \ company_data.get('revenue') object.company.fax = company_data.get('fax') object.company.save() tenantuser = get_current_tenant_user() poolhistory = PoolHistory._default_manager.filter(tenant=tenantuser, profile=True) if object.company.industry is not None and object.company.size is not None and object.company.position is not None\ and object.company.address is not None and object.company.city is not None\ and object.company.state is not None and object.company.postcode is not None \ and object.company.country_iso3 is not None and tenantuser.profile_details==False \ and tenantuser.is_business==True and not poolhistory: tenantuser = get_current_tenant_user() coins = ProfileCoins._default_manager.get(is_active=True) PoolHistory._default_manager.create( tenant=tenantuser, coins=coins.coins, profile=True) object.profile=True object.save() tenantuser.profile_details=True tenantuser.save() user = tenantuser.user user.coins = get_coins(tenantuser) user.save() if object.company.address is not None and object.company.city is not None\ and object.company.state is not None and object.company.postcode is not None \ and object.company.country_iso3 is not None … -
How to add pagination in Classed Based View with get_context_data
I want to add pagination to my List View. I have used paginated_by=10 but it not working. Please help me to add pagination to my view in my template. What HTML should i put in my template View.py class CompanyListView(LoginRequiredMixin, generic.TemplateView): template_name = 'superadmin/company/company.html' def get_context_data(self, **kwargs): context = super(CompanyListView, self).get_context_data(**kwargs) context['companies'] = Company.objects.exclude(company_name='Apollo').exclude(company_is_deleted = True).annotate(number_of_company_users=Count('userprofile')) return context -
submit a form with file not working using django ajax jquery
Upload image beside other data when user submit the form. using formData in jquery. I added picture field to the model added picture element in the form added the input tag in the html send the data through AJAX to the view getting the data from ajax request and added to the view function the system display error : valid form Internal Server Error: /create/te2chira Traceback (most recent call last): File "C:\Users\LT GM\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\LT GM\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\sqlite3\base.py", line 296, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: blog_te2chira.num n models.py class te2chira(models.Model): te2chira_id = models.AutoField( primary_key=True) num = models.IntegerField() # year = models.IntegerField() te2chira_date = models.DateField() title = models.CharField(max_length=250,default='DEFAULT VALUE', blank=True, null=True) description = models.CharField(max_length=500,default='DEFAULT VALUE', blank=True, null=True) is_sent=models.IntegerField() picture = models.ImageField(upload_to = 'pictures/%d/%m/%Y/',null=True, blank=True) def __str__(self): return str(self.te2chira_id) form.py from django import forms from blog.models import te2chira, destination class SaveTe2chira(forms.ModelForm): class Meta: model = te2chira fields = ['title', 'description','picture' ] html <form method="POST" class="form-style-9" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <li> <input type="file" id="img" name="img"/> </li> <li> <input type="submit" class="field-style field-full align-none" id="save" value="save" /> <script type="text/javascript"> $(function(){ $('#save').on('click',function(e){ e.preventDefault() var formData = new FormData(); formData.append('num',$('#num').val()) formData.append('title',$('#title').val()) formData.append('text',$('#text').val()) formData.append('issent', … -
Why am I getting the error local variable 'user_form' referenced before assignment
In the code, why am I getting "local variable 'user_form' referenced before assignment" error? from django.shortcuts import render from basic_app.forms import UserForm,UserProfileInfoForm def index(request): return render(request,'basic_app/index.html') def register(request): registered=False if request.method=="POST": user_form=UserForm(data=request.POST) profile_form=UserProfileInfoForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user=user_form.save() user.set_password(user.password) #Hashing the password user.save() profile=profile_form.save(commit=False) profile.user=user #Sets up one to one relationship if 'profile_pic' in request.FILES: profile.profile_pic=request.FILES['profile_pic'] profile.save() registered=True else: print(user_form.errors,profile_form.errors) else: user_form=UserForm() profile_form=UserProfileInfoForm() return render(request,'basic_app/registration.html',{'user_form':user_form,'profile_form':profile_form,'registered':registered}) This is in the views.py file. Have been stuck on this project since a while. Please help? -
Service Provider initiated Single Logout in Django
I work on a project with SAML authentication implemented using python-social-auth. I am trying to implement a view that initiates Single Logout (i.e. logout from all Service providers and Identity provider) on Service provider side. Currently, being logged in via SAML, I can access specific Identity provider page (ADFS, if that matters) and initiate Single Logout from there. So at the end there should be two options for logout - Django normal logout and the view that initiates Single Logout. I was able to extract name_id and session_index, and put it in request.session because, if I understand correctly, they are required for Single Logout. Also, the code from https://github.com/python-social-auth/social-core/issues/199 looks very similar to what I need, but I didn't manage to get solution with it. Particularly, I don't know where and how I should use process_logout(). What is correct approach to this problem? Is the code by the link above related to my problem. And if so, should I add some more code to make it work? -
MultiValueDictKeyError request.POST request.FILES
this is my problem: I have a form that allows to post a part in the database and another part that allows to upload a file to a folder in my hard drive, my problem is that I only valid the first part I have an error : MultiValueDictKeyError at/newrelease/ I do not know at all how to do the else or the return!! :s Thank you for your help def newrelease(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = UploadFileForm(request.POST, request.FILES) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required project = form.cleaned_data['project'] manufacturer = form.cleaned_data['manufacturer'] model = form.cleaned_data['model'] version = form.cleaned_data['version'] date = form.cleaned_data['date'] file = form.cleaned_data['file'] #upload files uploaded_file = (request.FILES['document']) fs = FileSystemStorage('/home/voirinj/workspace/uploads') print(project, manufacturer, model, version, date, file, uploaded_file) #importer une release dans Release new_release = Release( project = project, manufacturer = manufacturer, model = model, version = version, date = date, file_name = '', file_id = '', ) #save a release new_release.save() #save a file "obligation : (uploaded_file.name, uploaded_file)" fs.save(uploaded_file.name, uploaded_file) #message release … -
After getting the data from ajax POST method open another window in django
I want to pass data in views and open another html file in window.open("{% url 'view_detail' %}", "_self"), when i use ajax it post data successfully in views, Now i have to open this url, when i use this syntax window.open("{% url 'view_detail' %}", "_self"), it goes to same function and return nothing, How should i avoid this, .js file <script> function myFunction() { console.log("======") $('#NextButton').on('click', function () { console.log('After Clicking Next Buttton') $.ajax({ url : "/analytics/show_analytics/", type : "POST", async: true, data : { industry: $("input[name='analyticsindustry']:checked").val(), domain: $("input[class='analyticsdomain']:checked").val(), functions: $("input[class='analyticsfunctions']:checked").val(), csrfmiddlewaretoken: '{{ csrf_token }}', }, success : function(data) { var c = document.getElementById('domaincheckbox2').value; alert(data) window.open("{% url 'show_analytics', '_self' %)}") show_a(data) } }) return false; }) } </script> views.py def show_analytics(request): cursor = connection.cursor() #posts = analyticsreport.objects.values('Domain', 'Analytics').distinct() #print('POSTS', posts) total_analytics = [] if request.method == 'POST': industry = request.POST.get('industry') domain = request.POST.get('domain') functions = request.POST.get('functions') print("Industry", industry) print("Domain", domain) print("Functions", functions) #total_analytics = [] query = ('select id, Analytics from analytics_analyticsreport where Industry = ' + "'" + industry + "'") result = analyticsreport.objects.raw(query) print(len(result)) print(result) for i in range(len(result)): analytics = result[i].Analytics print('Analytics', analytics) if analytics not in total_analytics: total_analytics.append(analytics) print('Total_Analytics', total_analytics) return render_to_response('analytics/demo.html', {'posts': total_analytics}) -
Trying to save a PDF string results in UnicodeDecodeError with WeasyPrint
So far this is my code: from django.template import (Context, Template) # v1.11 from weasyprint import HTML # v0.42 import codecs template = Template(codecs.open("/path/to/my/template.html", mode="r", encoding="utf-8").read()) context = Context({}) html = HTML(string=template.render(context)) self.pdf_file = html.write_pdf() Actually it works via web request (returning the PDF as response) and via shell (manually writting the code). The code is tested and never gaves me problems. The files are saved with correct encoding, and setting the encoding kwarg in HTML doesn't help; also, the mode value of the template is correct, because I've seen other questions whose problem could be that. However, I was adding a management command to use it periodically (for bigger PDFs I cannot do it via web request because the server's timeout could activate before finishing), and when I try to call it, I only get a UnicodeDecodeError saying 'utf8' codec can't decode byte 0xe2 in position 10: invalid continuation byte. The PDF (at least from what I see) renders initially with this characters: %PDF-1.3\n%\xe2\xe3\xcf\xd3\n1 0 which translates into this: %PDF-1.3 %âãÏÓ 1 0 obj So the problem is all about the character â. But it's a trap! Instead, the problem is this line of code: self.pdf_file = html.write_pdf() Changing … -
Django problem, Exception Value: Friend matching query does not exist
I'm doing a Django blog website project. One of my feature is when you login, you can click on the tab Other member to show you a list of other members like in this picture. However, this feature only works when I login as the admin, when I log in as other members (not the admin), click the tab Other Member it will display errors Friend matching query does not exist. I'm really confused and getting stuck on this one. Here is my code: list_users.html {% extends "blog/base.html" %} {% block content %} <div class="container"> <div class="col-sm-6"> <h2>Other People</h2> {% for user in users %} <a href="{% url 'view_profile_with_pk' pk=user.pk %}"> <h3>{{ user.username }}</h3> </a> {% if not user in friends %} <a href="{% url 'change_friends' operation='add' pk=user.pk %}"> <button type="button" class="btn btn-success">Add Friend</button> </a> {% endif %} {% endfor %} </div> <br> <div class="col-sm-6"> <h2>Friends</h2> {% for friend in friends %} <a href="{% url 'view_profile_with_pk' pk=friend.pk %}"> <h3>{{ friend.username }}</h3> </a> <a href="{% url 'change_friends' operation='remove' pk=friend.pk %}"> <button type="button" class="btn btn-default">Remove Friend</button> </a> {% endfor %} </div> </div> {% endblock content %} views.py function listusers def listusers(request): posts = Post.objects.all().order_by() users = User.objects.exclude(id=request.user.id) friend = Friend.objects.get(current_user=request.user) friends = … -
custom template loader Django
i am trying to write a custom template loader in django which serves index.html which is present in a s3 bucket. Following is my loader file from django.conf import settings from django.template import Origin, Engine from django.template.loader import TemplateDoesNotExist from django.template.loaders.base import Loader from boto3.session import Session ACCESS_KEY_NAME = getattr(settings, 'AWS_TEMPLATE_LOADING_ACCESS_KEY_ID', getattr(settings, 'AWS_TEMPLATE_LOADING_ACCESS_KEY_ID', None)) SECRET_KEY_NAME = getattr(settings, 'AWS_TEMPLATE_LOADING_SECRET_ACCESS_KEY', getattr(settings, 'AWS_TEMPLATE_LOADING_SECRET_ACCESS_KEY', None)) TEMPLATE_BUCKET = getattr(settings, 'AWS_TEMPLATE_BUCKET_NAME') class Loader(Loader): is_usable = True def __init__(self, *args, **kwargs): params = args[0] options = params.pop('OPTIONS').copy() options.setdefault('autoescape', True) options.setdefault('debug', settings.DEBUG) options.setdefault('file_charset', settings.FILE_CHARSET) libraries = options.get('libraries', {}) session = Session(aws_access_key_id=ACCESS_KEY_NAME, aws_secret_access_key=SECRET_KEY_NAME) s3 = session.resource('s3') self.bucket = s3.Bucket(TEMPLATE_BUCKET) super(Loader, self).__init__(*args, **kwargs) self.engine = Engine(dirs=params['DIRS'], context_processors=options, loaders=Loader) def getKeys(self): keys_objects = [] for obj in self.bucket.objects.all(): key = obj.key keys_objects.append({ 'key': key, 'object': obj }) return keys_objects def get_contents(self, origin): try: keys_objects = self.getKeys() for key_object in keys_objects: if key_object['key'] == origin: return key_object['object'].get()['Body'].read() except FileNotFoundError: raise TemplateDoesNotExist(origin) def get_template_sources(self, template_name, template_dirs=None): tried = [] yield Origin( name=template_name, template_name=template_name, loader=self, ) tried.append('/index.html') if tried: error_msg = "Tried Keys %s" % tried else: error_msg = "Your TEMPLATE_DIRS setting is empty. Change it to point to at least one template directory." raise TemplateDoesNotExist(error_msg) get_template_sources.is_usable = True and in my settings i … -
Datetime in django with template filter will show different value
I'm using Django Template Filters to format datetime, looks like its value differs from raw date in Datebase. I used datetime.now() in Python to create and then {{ modeltest.date }} will show "Jan. 3, 2019, 5:27 a.m." on the page. {{ modeltest.date | date:"Y-m-d H:m:s" }} displays "2019-01-03 05:01:19" I'm getting a little confused here. Does anyone know this? Thanks. -
Appendix text to a reference in django template
I am trying to prepend my domain name to an image url passed to sorl-thumbnail, to prevent a SuspiciousFile Error, as the source images are located in my static folder and sorl-thumbnail creates stuff in my media dir. Prepending a domain name to the url passed to sorl-thumbnail is the advice given in a bug report, so I thought I would try it. I am trying like so: {% for instance in prods %} {% thumbnail "https://mydomainname.com/"instance.image_url "300x300" crop="smart" as im %} <img src="{{ im.url }}" > {% endthumbnail %} {% endfor %} However, putting a string before instance.image_url does not work. What is the correct way to do this? -
upload file in djago using FormData in jquery & ajax
Upload image beside other data when user submit the form. using formData in jquery. I added picture field to the model added picture element in the form added the input tag in the html send the data through AJAX to the view getting the data from ajax request and added to the view function the system display error : File "C:\Users\LT GM\Desktop\Final new\djangoWeb\views.py", line 160 request.session['idTe2chira']=id TabError: inconsistent use of tabs and spaces in indentation models.py picture = models.ImageField(upload_to = 'pictures/%d/%m/%Y/',null=True, blank=True) form.py from django import forms from blog.models import te2chira, destination class SaveTe2chira(forms.ModelForm): class Meta: model = te2chira fields = ['title', 'description','picture' ] html <form method="POST" class="form-style-9" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <li> <input type="file" id="img" name="img"/> </li> <li> <input type="submit" class="field-style field-full align-none" id="save" value="save" /> <script type="text/javascript"> $(function(){ $('#save').on('click',function(e){ e.preventDefault() var formData = new FormData(); formData.append('num',$('#num').val()) formData.append('title',$('#title').val()) formData.append('text',$('#text').val()) formData.append('issent', 0) formData.append('img', document.getElementById('img').files[0]) $.ajax({ url:'/create/te2chira', method:'POST', data:formData, processData:false, contentType:false, headers:{ 'X-CSRFToken':'{{csrf_token}}' } }).done(function(msg) { document.location = "/creativePageSend.html" alert('data saved') }).fail(function(err){ alert('no data was saved') }) }) }) </script> </li> </ul> </form> views.py def post_new(request): if request.method =='POST': form = SaveTe2chira(data = request.POST, files = request.FILES) if form.is_valid(): form.save() id=form.te2chira_id request.session['idTe2chira']=id return render(request,'./creativePageSend.html',{'id':id}) print("valid form") else: print("invalid … -
How to fix 'Django: table doesn't exist' when migrating from someone else's project?
I get the following error while trying to run python manage.py makemigrations invigilators: django.db.utils.ProgrammingError: (1146, "Table 'mydatabase.invigilators_shift' doesn't exist") class Shift(models.Model): shiftName = models.CharField(max_length=255,blank=False,unique=True) exam = models.ForeignKey(Exam,on_delete=models.CASCADE,related_name="shifts") startTime = models.TimeField() endTime = models.TimeField() def __str__(self): return self.shiftName I have already cleared all previous migrations and empty database is already created. -
Dango login, next url redirect to external links
One application was allowing redirection to external links after login using the next parameter, for instance if I'm login with https://myawesomeapp.com/en/auth/login?next=http://google.be I would be redirected to Google. The issue is fixed using is_safe_url function (from django.utils.http) and I also should use built-in LoginView from Django. My question is: Is it a security security breach ? What an hacker can achieve with that breach ? -
django decorator_from_middleware settings
I'm trying to avoid adding corsheaders middleware from django-cors-headers to my MIDDLEWARE_CLASSES variables cause this project is in production and damn fragile. So basically question is - is there any method to do setup for middleware used like this? Seems middlware variables in settings.py not working for this method -
How do I protect a password stored on server?
So, I set up a Django project and I'm done with it. Anyway, there's a function in the views.py script that is meant to send an email. I'm using the smtplib library and of course I need to login to send the email through my email address, so in that script my email and my password are written. I'll publish this project (hosted by Heroku) so I'm worring about the password protection. What do you think? Is the password protected or do I need to protect it in some way? I don't think it could be possible to access the views.py script but I'm not sure. -
how to skip an existing object instance when creating resources in bulk python
I am trying to create a resources in bulk, while the resources are created i have the matric_no has to be unique ,if the value of an existing matric_no is uploaded together with the some new entries , i get an integrity error 500 because the value already exists and it stops the rest value from being created. How can i loop through these values and then check if the value exist then skip so that the others can be populated. Here is my code: **models.py** from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Undergraduate(models.Model): id = models.AutoField(primary_key=True) surname = models.CharField(max_length=100) firstname = models.CharField(max_length=100) other_names = models.CharField(max_length=100, null=True, blank=True) card = models.CharField(max_length=100, null=True, blank=True) matric_no = models.CharField(max_length=20, unique=True) faculty = models.CharField(max_length=250) department_name = models.CharField(max_length=250) sex = models.CharField(max_length=8) graduation_year = models.CharField(max_length=100) mobile_no = models.CharField(max_length=150, null=True, blank=True) email_address = models.CharField(max_length=100) residential_address = models.TextField(null=True, blank=True) image = models.CharField(max_length=250, default='media/undergraduate/default.png', null=True, blank=True) def __str__(self): return "Request: {}".format(self.matric_no) ***serializers.py*** from .models import Undergraduate from .models import Undergraduate class UndergraduateSerializer(serializers.ModelSerializer): class Meta: model = Undergraduate fields ='__all__' class CreateListMixin: """Allows bulk creation of a resource.""" def get_serializer(self, *args, **kwargs): if isinstance(kwargs.get('data', {}), list): print(list) kwargs['many'] = True return super().get_serializer(*args, **kwargs) **api.py** from .models import … -
Timestamp with time zone, unknown using django ORM
After shifting from MariaDB to postgres-10 i am getting below error I am using Django-orm function date_format(timestamp with time zone, unknown) does not exist LINE 1: SELECT (DATE_FORMAT(created_at,'%h %p')) AS "in_hours", SUM(... HINT: No function matches the given name and argument types. You might need to add explicit type casts. Model.objects.filter(franchise=franchise)\ .filter(created_at__date=date)\ .extra(select={'in_hours': "DATE_FORMAT(created_at,'%%h %%p')"}) \ .values('in_hours')\ .order_by('created_at__hour')\ .annotate(total_amount=Sum('amount')) Can anyone please explain where its going wrong. Thank you -
Wrong configuration for database in seetings.py or docker
I'm learning how to work with Compose + Django using this manual https://docs.docker.com/compose/django/ Here are my configuration files docker-compose.yml version: '3' services: db: image: postgres web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'db', 'PORT': 5432, } } When I run using docker-compose up everything is fine. But when I run using python manage.py runserver I got this error psycopg2.OperationalError: could not translate host name "db" to address: Name or service not known Guess, I have wrong cofiguration