Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Form is invalid
Django==3.0.4 class LoginForm(forms.Form): login = forms.CharField() password = forms.CharField() return_url = forms.CharField(widget=forms.HiddenInput()) class Login(FormView): template_name = 'login/login.html' form_class = LoginForm success_url = "/" <form method="post">{% csrf_token %} {{ form.login }} {{ form.password }} <input type="hidden" name="return" value="{{ return_url }}" /> <input type="submit" value="Login"> </form> The problem is that the form is invalid. In the picture it is visible what I input in the fields. Could you help me here? -
How To Create Range of Weight in django-fliter
So every other filter is working well but not able to do filter by Weight. Want to filter weight in range.. filters.py class ProductFilter(django_filters.FilterSet): category = django_filters.ModelChoiceFilter(queryset=Category.objects.all()) sub_Category = django_filters.ModelChoiceFilter(queryset=subCategory.objects.all()) city = django_filters.ModelChoiceFilter(queryset=City.objects.all()) karat = django_filters.ModelMultipleChoiceFilter(queryset=Karat.objects.all(), widget=forms.CheckboxSelectMultiple) product_weight= django_filters.RangeFilter() class Meta: model = Product fields = ['category','sub_Category','city','product_weight'] models.py class Product(models.Model): .... product_weight = models.DecimalField(max_digits=5, decimal_places=3) views.py def filter_search(request): products = Product.objects.all() f = ProductFilter(request.GET, queryset=products) return render(request, 'home/list.html',{'filter':f}) -
Can't Save Formset with Files using Django and CrispyForm
I am trying to use crispyforms with a formset so that I can allow people to upload multiple files in separate fields in a form. However, I cannot get my CampaignFile model to save. It saves the Campaign model just fine, but it saves it with an empty CampaignFile field instead of the file that has been uploaded. models.py class Campaign(models.Model): """A typical class defining a model, derived from the Model class.""" # Fields company = models.CharField(max_length=32) email = models.EmailField(help_text='This is where we will send your results') pub_date = models.DateTimeField('date_published', auto_now_add=True) # Metadata class Meta: ordering = ['company', '-pub_date'] # # Methods # def get_absolute_url(self): # """Returns the url to access a particular instance of MyModelName.""" # return reverse('model-detail-view', args=[str(self.id)]) def __str__(self): """String for representing the MyModelName object (in Admin site etc.).""" return f'{self.id}' class CampaignFile(models.Model): content = models.FileField( validators=[validate_file_type], upload_to='ad_testing_form/') campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE, related_name='campaign') forms.py class CampaignFileForm(forms.ModelForm): class Meta: model = CampaignFile exclude = () widgets = { 'content': forms.ClearableFileInput(attrs={'multiple': False}) } CampaignFileFormSet = inlineformset_factory( Campaign, CampaignFile, form=CampaignFileForm, fields=['content'], extra=1, can_delete=True, labels={'content': 'Add Image/Video'} ) class CampaignForm(forms.ModelForm): class Meta: model = Campaign exclude = ['pub_date', ] def __init__(self, *args, **kwargs): super(CampaignForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = … -
django-concurrency: TriggerVersionField not creating trigger
Doing my first django project and following the tutorial. After creating my first model I ran manage.py makemigrations myapp and get an error from django-concurrency: WARNINGS: ?: (concurrency.W001) Missed trigger for field myapp.myclass.myfield Looking at the database, nothing was created, eg. no new table for the Model (django admin tables exist). The model uses django-concurency like this: version = TriggerVersionField(trigger_name='trg_component_version') What am I doing wrong? -
The variables for my Job model is not showing
I have created a Job model that contains Member and Manager info. It looks great imo. I created a class based view that translates the job if the user has one. Right now it's not showing. It just shows as a blank with an empty image file. I don't know what I did wrong or if I mistakenly used the wrong variables in the html file. Here's my views.py: from django.shortcuts import render from django.views.generic import ListView, CreateView from .models import Job from profiles.models import User # Create your views here. class jobs(ListView): model = Job template_name = 'users/user_jobs.html' context_object_name = 'jobs' def get_queryset(self): return Job.objects.filter(member__member=self.request.user) class createjob (CreateView): model = Job fields = ['member','title', 'description', 'file' My Models.py: from django.db import models from profiles.models import User # Create your models here. class Points (models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) points = models.IntegerField(default=0, null=False) def __str__(self): return self.user.username class Profile (models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.png',upload_to='profile_pics') def __str__(self): return f'{self.user.username}Profile' class Manager (models.Model): name = models.CharField(max_length=30, blank=True, null=True) manager = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.name class Member (models.Model): name = models.CharField(max_length=30, blank=True, null=True) manager = models.ForeignKey(Manager, on_delete=models.CASCADE) member = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.name class Job (models.Model): manager = … -
Reverse for "URL" with arguments '(id)' not found. 1 pattern(s) tried: 'URL< int:ID >'
I'm stock with this error i can't get the "id" of my list i get an error. i'm trying to crete an UPDATE button to edit the data i add to my database. Here's my views.py in my apps from django.shortcuts import render, redirect from gomo_web_system.forms import UserForm,NewMasterForm from django.contrib.auth import authenticate, login, logout from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django.contrib.auth.decorators import login_required from gomo_web_system.models import masterList from django.contrib import messages def index(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) return render(request, 'gomo_web_system/main_menu.html') else: messages.info(request, 'Username or Password is incorrect') context = {} return render(request, 'gomo_web_system/index.html', context) def user_logout(request): logout(request) return HttpResponseRedirect(reverse('index')) @login_required def main_menu(request): return render(request, 'gomo_web_system/main_menu.html') @login_required def it_home(request): return render(request, 'gomo_web_system/IT/it_home.html') @login_required def it_master_list(request): master_list = masterList.objects.order_by('projectName') master_dict = {'master':master_list} return render(request, 'gomo_web_system/IT/it_master_list.html', context=master_dict) @login_required def it_create_master_list(request): form = NewMasterForm() if request.method == 'POST': #print('printring POST:', request.POST) form = NewMasterForm(request.POST) if form.is_valid(): form.save() return redirect('gomotion:master_list') context = {'form':form} return render(request, 'gomo_web_system/IT/it_add_master_list.html', context) def it_update_master_list(request, id): form = NewMasterForm() context = {'form':form} return render(request, 'gomo_web_system/IT/it_add_master_list.html', context) Here's my in my apps myapp/urls.py from django.conf.urls import url from gomo_web_system import views … -
Heroku DataTables warning: table id=vtable - Ajax error
I get this error when my app running in cloud server but in local server everything is working. How can I fixed this error? thank you. DataTables warning: table id=vtable - Ajax error. For more information about this error, please see http://datatables.net/tn/7 Table.html <table id="vtable" class="display" style="width:100%" data-server-side="true" data-ajax="/api/masterlist/?format=datatables"> <thead> <tr> <th>Employee ID:</th> <th>Company:</th> Ajax $(document).ready(function() { var table = $('#vtable').DataTable({ "processing": true, "serverSide": true, "scrollX": true, "ajax": { "url":"/api/masterlist/?format=datatables", "type":"POST" }, "columns": [ {"data": "Employee_Id"}, {"data":"Company"}, -
Issue with conda env while using uwsgi
I'm trying to run django server with uwsgi using anaconda python on Ubuntu 16.04.6 LTS. I've created a conda environment and installed all the dependencies. If I run the django server in dev(i.e python manage.py runserver), it's working without any issues. But, when I run it with uwsgi, I'm getting "ImportError: cannot import name _remove_dead_weakref stackoverflow" Error: Traceback (most recent call last): File "wsgi.py", line 11, in <module> from django.core.wsgi import get_wsgi_application File "/opt/myproj/venvs/api/lib/python2.7/site-packages/django/core/wsgi.py", line 2, in <module> from django.core.handlers.wsgi import WSGIHandler File "/opt/myproj/venvs/api/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 5, in <module> import logging File "/opt/myproj/venvs/api/lib/python2.7/logging/__init__.py", line 26, in <module> import sys, os, time, cStringIO, traceback, warnings, weakref, collections File "/opt/myproj/venvs/api/lib/python2.7/weakref.py", line 13, in <module> from _weakref import ( ImportError: cannot import name _remove_dead_weakref unable to load app 0 (mountpoint='') (callable not found or import error) I've set the path to anaconda $ echo $PATH /home/baji/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/home/baji/anaconda2/bin $ echo $PYTHONPATH /opt/myproj/venvs/api/bin/python The uwsgi command that I'm trying is $ /opt/myproj/venvs/api/bin/uwsgi -H /opt/myproj/venvs/api/ -i /opt/myproj/api/wsgi.ini This is the wsgi.ini file [uwsgi] module = wsgi:application master = true processes = 1 chmod-socket = 666 socket = /tmp/api.sock check-static = ./static wsgi-file = wsgi.py touch-reload = /tmp/api.txt buffer-size = 65535 post-buffering = 1 listen = 65535 vacuum = … -
json.dumps generates a string and returning it as dict is making a string inside another string, how to avoid it and get just a single string
class_object = ModelClass(title=entity_object['title'], entities_definition_key=entity_object['entities_definition_key'], orderId=entity_object['orderId'],uid = json.dumps( uuid.uuid4(), cls=UUIDEncoder)) ModelClass is mongoengine model class json_output = class_object.serializing_method() final_list.append(json_output) another_class_object = AnotherModelClass(workflowId=body['workflowId'],entities_list=final_list) another_class_object.save() save() to mongodb final_dict={} final_dict['entities_list'] = another_class_object.entities_list return HttpResponse(json.dumps({'entity_definition_dict':entity_definition_dict})) output-{'uid': "\"74b1900ccfbd44234563805ac0279d\""} -
Django: How to set up a test server with fixtures but Django models containing ForeignKeys?
I'm trying to directly test my client code (with requests module) to call my Django API. However, I want to automate this. What I'm trying to do is create a model with test server running. How am I able to populate my testdb with fixtures if one of my models has a ForeignKey? class Customer(models.Model): name = models.CharField(max_length=150) phone = models.CharField(max_length=12) email = models.CharField(max_length=250) class Load(models.Model): load_id = models.CharField(max_length=100, blank=True) invoice_id = models.CharField(max_length=100, blank=True) >customer = models.ForeignKey(Customer, on_delete=models.CASCADE, blank=True, null=True) notes = models.CharField(max_length=500, blank=True) carrier = models.ForeignKey(Carrier, on_delete=models.CASCADE, null=True, blank=True) driver = models.ForeignKey(Driver, on_delete=models.CASCADE, null=True, blank=True) active = models.BooleanField(default=True) -
ModelMultipleChoiceField not validating empty label
I have a ModelForm: class MCQuestionForm(forms.ModelForm): quiz = forms.ModelMultipleChoiceField( queryset=None, required=False, widget=forms.CheckboxSelectMultiple, help_text='Which tests this question applies to.') class Meta: model = MCQuestion exclude = () def __init__(self, *args, **kwargs): self.user = (kwargs.pop('user', None)) super(MCQuestionForm, self).__init__(*args, **kwargs) super_role = self.user.role subs_id = self.user.subordinates.values_list('role', flat=True) sub_roles = EmployeeType.objects.filter(pk__in=subs_id) cats = Category.objects.filter(groups=super_role) | Category.objects.filter(groups__in=sub_roles) self.fields['quiz'].queryset = Quiz.objects.filter(category__in=cats) Which I need to allow an empty choice on. I have tried initializing: self.fields['quiz'].choices = [('', 'None for now')] + \ [(quiz.pk, quiz.title) for quiz in self.fields['quiz'].queryset] and I have also tried: empty_label=False I have even tried: self.fields['quiz'].empty_label = 'Empty' But I always seem to get the form validation error: "" is not a valid value. How can I add an empty label here? -
Difference between Model serializer and base serializer django
What is the difference between a rest framework model serializer and base serializer. What are pros and cons of each. I referred the docs but couldn't understand in what scenario would each be used. -
python: can't open file 'manage.py': [Errno 2] No such file or directory docker-compose run
MY EGLISH IS NOT GOOD. SORRY! I tried run django project with code docker-compose -f local.yml run --rm django python manage.py runserver, but i had such problem "python: can't open file 'manage.py': [Errno 2] No such file or directory" in another computer this project runenter image description here but this code work docker-compose -f local.yml run django python enter image description here -
jQuery & Django, update div with different intervals
I've been making a Moon Info Display for a project of mine. I've been using Python to calculate the moon info values and used Django to send the info to the front-end. To update the page, I've been using a solution from Django, update part of the page. This allowed me to refresh the page automatically within an interval. However, now I wanted to update some part of the page with different interval, how would I do this? My jQuery code is as follows: $(document).ready(function() { $.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh var my_refresh = setInterval(function() { $('#moonphase').load('/getPhase/'); $('#alti').load('/getAlt/'); $('#az').load('/getAz/'); $('#elong').load('/getElong/'); $.get( '/getImage/', function(data){ img = parseInt(data); if (img === 1){ document.getElementById("imgphase").src = "{% static "lunarphase/0_0.png" %}"; } else if (img === 2){ document.getElementById("imgphase").src = "{% static "lunarphase/2_0.png" %}"; } else if (img === 3){ document.getElementById("imgphase").src = "{% static "lunarphase/5_0.png" %}"; } else if (img === 4){ document.getElementById("imgphase").src = "{% static "lunarphase/8_0.png" %}"; } else if (img === 5){ document.getElementById("imgphase").src = "{% static "lunarphase/14_0.png" %}"; } else if (img === 6){ document.getElementById("imgphase").src = "{% static "lunarphase/17_0.png" %}"; } else if (img === … -
Django contenttypes: null value in column "object_pk" violates not-null constraint
I'm trying to create an instance of my Comment model below. class Comment(models.Model): author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True ) body = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) deleted_at = models.DateTimeField(blank=True, null=True) votes = JSONField(default=list, blank=True, null=True) total_vote = models.IntegerField(default=0) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_pk = models.PositiveIntegerField() content_object = GenericForeignKey("content_type", "object_pk") avatar_string = models.CharField(blank=True, max_length=100) I'm creating it by using a model form with the following definition. class CommentForm(forms.ModelForm): event = forms.ModelChoiceField(queryset=Event.objects.all(), required=False) class Meta: model = Comment fields = ["body", "author"] The form is being saved by this view function: def comment_create(request): print("foobar") comment_form = CommentForm(request.POST) print(comment_form.data) if comment_form.is_valid(): comment_form.save(commit=False) comment_form.author = request.user comment_form.content_type = ContentType.objects.get_for_model(Event) comment_form.content_object = comment_form["event"] comment_form.save() return HttpResponse() else: return HttpResponseBadRequest() How do I get it to populate the content_object field on my comment model from the ModelChoiceField in my form? -
How to use AbstractUser to customize django User model
I am working on a Django project and I am trying to customize the Django User model by inheriting AbstractUser in my models.py but when I run my server I get this error message. AttributeError: Manager isn’t available; ‘auth.User’ has been swapped for ‘django_starter_app.User’ What I am doing wrong here? below is my code models.py from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): STUDENT = 1 TEACHER = 2 SECRETARY = 3 SUPERVISOR = 4 SITE_ADMIN = 5 USER_TYPE_CHOICES = ( (STUDENT, 'student'), (TEACHER, 'teacher'), (SECRETARY, 'secretary'), (SUPERVISOR, 'supervisor'), (SITE_ADMIN, 'site_admin'), ) user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES) phone = models.CharField(max_length=12, blank=True, null=True) address = models.TextField(blank=True, null=True) on settings.py AUTH_USER_MODEL = 'django_starter_app.User' -
uwsgi arrange django on the server, and uwsgi load the static, but the SVG not display
I use UWSGI to proxy static resources. SVG images load successfully and return 200 but do not display. django admin django admin cosole I go directly to the SVG link and only return the SVG code. But my browser can load SVG pictures. open SVG link on browser -
Updating Form.intial does not change intial value in Django template
Goal I want to retain the query when a search result renders. Here is an example where the search bar contains stackoverflow on the results page. Failed Solutions These are minimal code examples # search_results.html <form action="/search" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Search"> </form> # views.py ... class SearchView(TemplateView): """Search view""" def get_context_data(self. **kwargs): context = super().get_context(**kwargs) user_query = self.request.GET.get('q', None) form.initial = {'user_query': user_query} return context The first time I search in the browser, the template renders as expected. If I search foo the following is rendered <form action="/search" method="post"> <input type="text" value="foo" name="search"> <input type="submit" value="Search"> </form> But searching a second time doesn't change the string in the search bar. If I search bar after searching foo, the search bar's value does NOT change to bar as expected. <form action="/search" method="post"> <input type="text" value="foo" name="search"> <input type="submit" value="Search"> </form> What am I doing wrong? Below is the form code. # forms.py from django import forms class SearchBar(forms.Form): user_query = forms.CharField() -
How to remove some unused feature in cloned django project?
I'm currently working in a deployed django project (django-rest-framework), but for now, my leader want to clone that project into a new one, the clone project just keep some feature in original, and remove all the unnecessary. So I wondering how to remove some model or part of model without blow up the project? -
Django displays form-error messages by default when visiting a url
Good day. I'm trying to override basic authentication with custom one. Whenever i visit user/login/ url i get error messages displaied. urls.py app_name = 'user' urlpatterns = [ path('user/login/', LoginView.as_view( template_name='registration/login.html', authentication_form=LoginForm), name='login'), path('user/', include(urls)), ] forms.py class LoginForm(AuthenticationForm): def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(args, kwargs) username = forms.EmailField(widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Email address', 'type': 'email', 'id': 'inputEmail'} ), label='') password = forms.CharField(widget=forms.PasswordInput( attrs={'class': 'form-control', 'placeholder': 'Password', 'type': 'password', 'id': 'inputPassword'} ), label='') login.html <div class="container text-center"> <h1 class="h3 mb-3 font-weight-normal">Sign-in</h1> <form action="." method="post" class="form-signin"> {{ form.as_p }} {% csrf_token %} <input type="hidden" value="{{ next }}"> <input type="submit" value="Login" class="btn btn-primary"> </form> </div> -
django version 1.8 'ForeignKey' object has no attribute
In my models.py I have 3 classes Project Finding FindingType Relationship between entities: Project can have 0 to N Finding. Each Finding has one Finding type. class Project(models.Model): completed_date = models.DateField(blank=True, null=True) .. and some other attributes class RA_Finding_type(models.Model): finding_title = models.CharField(max_length=40) finding_desc = models.TextField() remediation_desc = models.TextField() trc_control_number = models.TextField() display = models.BooleanField(blank=True) class RA_Finding(models.Model): project = models.ForeignKey(Project) if (not project.completed_date): # Error here. finding_type = models.ForeignKey(RA_Finding_type, limit_choices_to={'display': True},verbose_name='Weakness Type') else: finding_type = models.ForeignKey(RA_Finding_type, limit_choices_to={'display': False},verbose_name='Weakness Type') ... other attributes I want to populate finding_type attribute based on closed date. This is primary for legacy data. When I try to do this, I get an error - 'ForeignKey' object has no attribute. Is there a way to achieve this in Django? Appreciate all help. -
Django KeyError when starting
I accidentally pulled an old git repo of my Django build ( It's running on a Heroku dyno ) and it had overwritten my entire local build, I managed to restore it back to the latest git repo which was previously working on my local build ( but not my Heroku dyno ) and the server now won't run locally or on my live build? Error from the shell: python manage.py runserver File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/johnnie/.local/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/johnnie/.local/lib/python3.7/site-packages/django/core/management/__init__.py", line 345, in execute settings.INSTALLED_APPS File "/home/johnnie/.local/lib/python3.7/site-packages/django/conf/__init__.py", line 76, in __getattr__ self._setup(name) File "/home/johnnie/.local/lib/python3.7/site-packages/django/conf/__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "/home/johnnie/.local/lib/python3.7/site-packages/django/conf/__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/johnnie/myproject/myproject/mysite/mysite/settings.py", line 141, in <module> del DATABASES['default']['OPTIONS']['sslmode'] KeyError: 'OPTIONS' -
How do I format my MySql table to avoid a "Incorrect string value" error?
I'm using Python 3.7, Django 2.0 and Mysql 5.7, all set up through docker containers. I'm trying to insert the following seed data into one of my tables ... - model: address.state pk: 14970 fields: name: "Xocal\u0131" code: XCI country: 266 This results in the MySql error, "Could not load address.State(pk=14750): (1366, "Incorrect string value: '\xC4\x81n' for column 'name' at row 1")" web_1 | File "/usr/local/lib/python3.7/site-packages/MySQLdb/cursors.py", line 209, in execute web_1 | res = self._query(query) web_1 | File "/usr/local/lib/python3.7/site-packages/MySQLdb/cursors.py", line 315, in _query web_1 | db.query(q) web_1 | File "/usr/local/lib/python3.7/site-packages/MySQLdb/connections.py", line 239, in query web_1 | _mysql.connection.query(self, query) web_1 | django.db.utils.OperationalError: Problem installing fixture '/app/maps/fixtures/state_data.yaml': Could not load address.State(pk=14750): (1366, "Incorrect string value: '\\xC4\\x81n' for column 'name' at row 1") Below is my table description ... +---------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | address_state | CREATE TABLE `address_state` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(165) NOT NULL, `code` varchar(3) NOT NULL, `country_id` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `address_state_name_country_id_a46a5987_uniq` (`name`,`country_id`), KEY `address_state_country_id_0a4efd43_fk_address_country_id` (`country_id`), CONSTRAINT `address_state_country_id_0a4efd43_fk_address_country_id` FOREIGN KEY (`country_id`) REFERENCES `address_country` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 | +---------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ 1 row in set (0.00 sec) What can I do to format my table so that I can insert my value properly? The table was … -
Django Rest Framework request header based permission
I'm building a Django app with Django Rest Framework to host it on my organisation's domain. The domain implements a custom authentication protocol. When someone accesses the domain, say to app1.domainname.com, they are redirected to the organisation's login page (login.domainname.com) and they have to log in with their staff account. After the user is authenticated, the user is redirected back to their initial destination (app1.domain.com). The information of the user is then stored in some custom header fields of the HTTP request sent to the app. E.g. GET / HTTP/2 Content-Type: User-Agent: ... ... X-Username: johndoe1 X-Firstname: John X-Lastname: Doe X-Email: johndoe@domainname.com etc. I'm trying to implement custom permission for my REST API that looks for these fields in the headers, and then authorise the user based on their user information. This is what I'm currently having: from rest_framework.permissions import BasePermission allowed = ['johndoe1', 'dicksmith2', 'username3'] class CutomPerm(BasePermission): message = "You don't have permission to access this object" def has_object_permission(self, request, view, obj): print(request.headers) username = request.headers['X-Username'] return username in allowed But when I run the server, it seems like the custom headers are passed through to the backend. For some requests they are, but ultimately the user is not … -
RecursionError when trying to save image
I am attempting to create a model with an image input that is to be resized and hashed on save. However, I appear to to have created an infinite recursive call. I am basing the code for my resize_and_hash_image() method off of this answer to a previous question of mine. Is there a way I can save the image without calling self.instance.save()? Any help is appreciated. models.py import hashlib from base64 import b16encode from functools import partial from io import BytesIO from PIL import Image from django.db import models class Person(models.Model): prefix = models.CharField(blank=True, null=True, max_length=5) first_name = models.CharField(max_length=35) last_name = models.CharField(max_length=35) suffix = models.CharField(blank=True, null=True, max_length=5) image = models.ImageField(default=None, upload_to='people/') _image_hash = models.BinaryField(blank=True, null=True, default=None, max_length=16) bio = models.TextField() phone = models.CharField(max_length=10) email = models.EmailField() def __str__(self): return self.full_name def save(self, *args, **kwargs): if self.image: self.resize_and_hash_image() super().save(*args, **kwargs) def hash_file(self, file, block_size=65536): hasher = hashlib.md5() for buf in iter(partial(file.read, block_size), b''): hasher.update(buf) return hasher.digest() def resize_and_hash_image(self): img = Image.open(self.image).convert('RGB') width, height = img.size longest, shortest = 960, 720 if (width >= height and (width > longest or height > shortest)) or (height > width and (height > longest or width > shortest)): if width > height: if (height * …