Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django failed to load static image
I have my django app hosted on pythonanywhere. I am using weasyprint to generate a pdf and there is an image to be shown in my pdf. The error in the error log is "Failed to load image at /static/images/logo.png". When I try to open the same path as url, it shows me the image in the browser. Which means it is getting the path right but something else is wrong. I have my static directory placed outside the app. And this path is added to the settings file. My folder structure: my_app static |__ css |__ images |__ logo.png |__ js templates |__ my_app |__ pdf.html settings.py: STATIC_DIR = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS =[ STATIC_DIR, ] pdf.html: {% load static %} <td><img class="my_logo" src="{% static 'images/logo.png' %}" alt="Temporarily Unavailable"></td> -
Django channels : why is channel_layer.gruop_send getting skipped?
I'm trying to send message though websocket in django-channgels using channel-layers but its getting skipped and doesn't even show any exception or error. I have tried to make it work even in without async and with async but none works. class stock_consumer(AsyncWebsocketConsumer): channel_layer = get_channel_layer() async def websocket_connect(self, event): await self.accept() await self.channel_layer.group_add("stock_group", self.channel_name) u = stock_market(api_key, access_token) u.subscribe(u.get_instrument_by_symbol('NYSE', 'AAPL')) u.start_websocket(True) def quote_update(message): stock_consumer.send_message(self, message) u.set_on_quote_update(quote_update) async def websocket_receive(self, event): print(event) async def websocket_disconnect(self, message): await self.channel_layer.group_discard('stock_grogup', self.channel_name) await self.close() def send_message(self, message): print("before") //runs ***SKIPPED BLOCK START*** self.channel_layer.group_send("stock_group", { "type": "send_message", "text": json.dumps(message) }) ***SKIPPED BLOCK END*** print("after") //runs -
DATABASES is improperly configured rds postgres django
i had deployed my django app on elasticbeanstalk but when i am connecting with rds is shows this error ImproperlyConfigured("settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. container_command 01_migrate in .ebextensions/django.config failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. heres my setting: if 'aam9tdmg0cwj1k.cugucrimdqma.ap-south-1.rds.amazonaws.com' in os.environ: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['aam9tdmg0cwj1k'], 'USER': os.environ['liveimage'], 'PASSWORD': os.environ['liveimage123'], 'HOST': os.environ['aam9tdmg0cwj1k.cugucrimdqma.ap-south-1.rds.amazonaws.com'], 'PORT': os.environ['5432'] } } there no indent error -
Django sending values of object with foreign key
I have a app that have 2 models: Projecto Model's class Projeto(models.Model): field1 = ........ field2 = ........ Aditamento Model's class Aditamento(models.Model): processo = models.ForeignKey(Projet, on_delete=models.CASCADE,verbose_name="Projecto",related_name='ProcessoObjects') field1 = ..... field2 = .... Projecto Admin class AditamentoInline(admin.StackedInline): form = AditamentoForm model = Aditamento extra = 0 max_num = 4 class ProjetoAdmin(admin.ModelAdmin): inlines = [AditamentoInline] I can have 1 projeto with several aditamento's ( max:4) Right now i want to send the field's of each aditamento to a page html to print. when i open my object project i have 4 buttons , and when i click on of them , i want to send the fields of that aditamento corresponding that object i open. So if i click in 3-aditamento i will send the values of aditamento i create in third and so for all. What is the best way to do this ? -
Django while returning values shows list out of index
I am trying to return values to a template using request method in a view. The values are in a list. When i try to access these values in return I get a list out of index error. But the values are proper when I print these values to a cmd. Error IndexError at / list index out of range Request Method: GET Request URL: http://localhost:8000/ Django Version: 1.11.20 Exception Type: IndexError Exception Value: list index out of range Python Version: 2.7.15 views.py file def index(request): req_val = [None] demo_text =[] if request.method == 'POST': req_val.append(request.POST.get('val1')) req_val.append(request.POST.get('val2')) req_val.append(request.POST.get('val3')) demo_text = package_name.classobj(req_val[0],req_val[1],req_val[2]).methodprintval() print demo_text #sample output: [1,2,3] return render(request, 'index.html',{'sampleval1':demo_text[0],'sampleval2':demo_text[1],'sampleval3':demo_text[2]}) #error list index out of range I tried finding solution but couldn't. How can I solve this? Thanks -
Celery worker receiving too many tasks
I have started my Celery worker like this: celery -A workerTasks worker --concurrency 1 --loglevel=info But i see that it is receiving multiple tasks: [2019-05-08 10:33:07,371: INFO/MainProcess] celery@2aaf46abfaed ready. [2019-05-08 10:33:07,372: INFO/MainProcess] Received task: workerTasks.do_processing_task[a3c19e7a-6b04-4236-8afc-0884547d3f39] [2019-05-08 10:33:07,373: INFO/MainProcess] Received task: workerTasks.do_processing_task[f22443c1-6dee-4ecf-8c54-7a7c4da5418e] [2019-05-08 10:33:07,373: INFO/MainProcess] Received task: workerTasks.do_processing_task[6eb501b7-c192-46db-be78-6061300b6bdf] [2019-05-08 10:33:07,373: INFO/MainProcess] Received task: workerTasks.do_processing_task[ec08b59f-541e-42fc-806d-cfbd40daf7b7] [2019-05-08 10:33:07,479: INFO/MainProcess] Received task: workerTasks.do_processing_task[deaaec17-b07c-4476-9b44-9f8e884b0b6e] Why is it not just receiving one? Thank you. -
AttributeError at has no attribute 'objects'
AttributeError type object 'Data_Point ' has no attribute 'objects'plz check and correct me AttributeError at / type object 'myProduction' has no attribute 'objects' from django.db import models from django.contrib.auth.models import User #My models class Production(models.Model): title=models.CharField(max_length=120) def __str__(self):return self.title #My Form from django import forms from.models import Production class myProduction(forms.ModelForm): class Meta: model=Production fields =['title'] class Raw_Pro(forms.Form): title = forms.CharField() #My View from django.shortcuts import render from .form import myProduction,Raw_Pro def my_index(request): my_form=Raw_Pro() if request.method=='POST': my_form=Raw_Pro(request.POST) if my_form.is_valid(): myProduction.objects.create(my_form.cleaned_data) else: print(my_form.errors) context={"form":my_form} return render(request, "index.html",context) -
how to fix database problem in django (postgresql)
I write some models in my project, then i deleted an uuid field from my book model and the deleted the 0001_initial.py file and run make migrations and migrate but when i run py manage.py migrate, show me this message: No migrations to apply. and when run makemigrations : Migrations for 'main_app': main_app\migrations\0001_initial.py Create model Author Create model Book Create model Genre Add field genre to book this are my models: class Genre(models.Model): genre = models.CharField(max_length=100) def __str__(self): return self.genre class Book(models.Model): book_name = models.CharField(max_length=150) summary = models.TextField(max_length=1000, null=True,blank=True) author = models.ForeignKey('Author', on_delete=models.CASCADE) genre = models.ManyToManyField(Genre) status = [ ('a', 'available'), ('b', 'borrowed'), ('r', 'reserved'), ] book_status = models.CharField(max_length=1, choices=status, default='a') isbn = models.CharField(max_length=13, help_text='read ' '<a href="https://www.isbn-international.org/content/what-isbn">' 'here' '</a>' ' to help ') def __str__(self): return '{0}({1})'.format(self.book_name, self.author) def get_absolute_url(self): return reverse('main_app:book-detail', args=[self.id]) class Author(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) rate = models.IntegerField(default=0) def __str__(self): return '{0} {1}'.format(self.first_name,self.last_name) -
Will connection.cursor() as cursor create new connection?
If am doing the following in Django, will a new connection object be created for every query execution. for query in query_list: with connection.cursor() as cursor: cursor.execute(query) -
Define weight for completion suggest field in elasticsearch-dsl
Using Elastic Search 5.2.x and elasticseach-dsl for bulk index creation in my Django app, I am trying to implement a completion suggest field like so: def indexing(self): obj = SchoolIndex( meta = {'id': self.pk}, name = self.name, name_suggest = self.name ) obj.save(index="school_index") return obj.to_dict(include_meta=True) Now, I need to define some weights for the suggest field-name_suggest, so that the suggestions get scored during querying, but I am not able to figure out elasticsearch-dsl specific syntax to do the same in the function above. I tried doing this, but it didn't work : name_suggest = {'input':self.name,'weight':100} Essentially, I am trying to implement in Django, what the docs show here : https://www.elastic.co/guide/en/elasticsearch/reference/5.6/search-suggesters-completion.html#indexing I am new to Elastisearch, please advise if I am assigning the weight at the right place in code and the syntax to do it in Django. Thanks. -
Reuse model choice variables across multiple models
If you have two models with choice fields that have the same choices, what is a DRY way to include the variables on both models? For example I'd like to include the following variables on Customer and Order models and ideally I'd like to be able to access the variable like Order.NP. class PaymentChoices: NP = 1 PUP = 2 REQUEST_CHOICES = ( (NP, 'No Payment'), (PUP, 'Pick up payment'), ) Including the PaymentChoices object like you would with and abstract model doesn't work as it's an unresolved reference. class Order(PaymentChoices, models.Model): ... -
How to load different html pages with the same url?
I have three functions in views.py and corresponding three html pages to render those views. All three views are made to render a table that contains different attributes. My purpose is to drill down the row contents of the first table and successively the second table. Since I have seperate view function I need to provide them separate URL's. My aim is to have one URL and render the multiple HTML pages. I am not much familiar with ajax. Is there a way to achieve this in ajax or in some other way? Please guide to sort out this issue. Thanks -
Setting up Digital Ocean firewall instead of ufw for Django
What is the equivalent of the following commands on Digital Ocean for setting up a firewall for ubuntu sudo ufw allow OpenSSH sudo ufw allow 8000 In the following firewall settings ? -
redirect() is redirecting to the specified view/url but the page against that view is not displaying
I am trying to redirect the user to index page(to see if things work, ultimately i would redirect it to login/singup page) if the user is not authenticated. redirect() is working just fine but i am unable to see the page specified against that url/view. In this view i am saving some information sent in the request before redirecting the user if he is unauthenticated. def post_shirt_specs(request): base_pattern = get_object_or_404(Pattern, name=request.GET.get('basePattern')) ocollar_pattern = get_object_or_404(Pattern, name=request.GET.get('outerCollarPattern')) icollar_pattern = get_object_or_404(Pattern, name=request.GET.get('innerCollarPattern')) collar_catagory = request.GET.get('collarDesign') ocuff_pattern = get_object_or_404(Pattern, name=request.GET.get('outerCuffPattern')) icuff_pattern = get_object_or_404(Pattern, name=request.GET.get('innerCuffPattern')) cuff_catagory = request.GET.get('cuffDesign') iplacket_pattern = get_object_or_404(Pattern, name=request.GET.get('innerPlacketPattern')) oplacket_pattern = get_object_or_404(Pattern, name=request.GET.get('outerPlacketPattern')) if request.user.is_authenticated: shirt = Shirt.objects.create( base = base_pattern.base, inner_collar = icollar_pattern.inner_collar.all().filter(catagory=collar_catagory, opened=False).first(), outer_collar = ocollar_pattern.outer_collar.all().filter(catagory=collar_catagory, opened=False).first(), collar_base = ocollar_pattern.collar_base.filter(opened=False).first(), yoke = base_pattern.yoke.all().filter(opened=False).first(), outer_placket = oplacket_pattern.outer_placket.all().filter(opened=False).first(), inner_placket = iplacket_pattern.innerplacket, outer_cuff = ocuff_pattern.outer_cuff.all().filter(catagory=cuff_catagory, opened=False).first(), inner_cuff = icuff_pattern.inner_cuff.all().filter(catagory=cuff_catagory, opened=False).first(), sess_id = "", ) creator = Creator.objects.all().filter(user=request.user).first() if creator: cart = creator.cart else: cart = Cart.objects.create( user = request.user, total_price = 1500, ) Creator.objects.create( shirt = shirt, user = request.user, cart = cart, ) else: uid = get_random_string( length=12, allowed_chars=u'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' ) date = datetime.datetime.now() session_id = "{0}{1}{2}{3}".format(date.year, date.month, date.day, uid) request.session['id'] = session_id shirt = Shirt.objects.create( base = base_pattern.base, inner_collar = icollar_pattern.inner_collar.all().filter(catagory=collar_catagory, opened=False).first(), … -
how to Validate Expire date is bigger than start date in Django Model Form
I am using Django model form, I want to Validate Expire date is bigger than start date. this is my code but it is not working. i used clean() method in form.py but after than form is not submitting. form.py class CertificateForm(forms.ModelForm): app_attributes = {'oninvalid': 'this.setCustomValidity("Application field is required")', 'oninput': 'this.setCustomValidity("")'} startdate = forms.DateField(widget = forms.SelectDateWidget(years=range(1995, 2100))) expiredate = forms.DateField(widget = forms.SelectDateWidget(years=range(1995, 2100))) application = forms.CharField(widget=forms.TextInput(attrs=app_attributes)) File= forms.FileField(required=True) class Meta: model = certificateDb fields = ('application', 'startdate', 'expiredate', 'environment_type','File' ) error_messages = { 'application': { 'required': ("Application field is required"), }, } def clean(self): startdate = cleaned_data.get("startdate") expiredate = cleaned_data.get("expiredate") if expiredate < startdate: msg = u"expiredate should be greater than startdate." self._errors["expiredate"] = self.error_class([msg]) model.py class certificateDb(models.Model): Dev = 1 QA = 2 UAT = 3 Production = 4 environment_TYPES = ( (Dev, 'Dev'), (QA, 'QA'), (UAT, 'UAT'), (Production, 'Production'), ) application = models.CharField(db_column='Application', max_length=255, blank=True, null=True) # Field name made lowercase. startdate = models.DateField(null=True) expiredate = models.DateField(null=True) environment_type = models.PositiveSmallIntegerField(choices=environment_TYPES) File = models.FileField(upload_to='CSR/', null=True , blank = True) def __str__(self): return self.applicationclass certificateDb(models.Model): Dev = 1 QA = 2 UAT = 3 Production = 4 environment_TYPES = ( (Dev, 'Dev'), (QA, 'QA'), (UAT, 'UAT'), (Production, 'Production'), ) application … -
Django authentication within twisted perspective broker
I've tried to use django authentication within twisted perspective broker, by creating a checker with django's orm and authentification modules but get hit with a: django.core.exceptions.ImproperlyConfigured. I've created the following checker inside the twisted server, I'll add the django imports there in case those are wrong. from django.contrib.auth.models import User from django.contrib.auth.hashers import check_password @implementer(checkers.ICredentialsChecker) class DjangoAuthChecker: credentialInterfaces = (credentials.ICredentialsChecker) credentialInterfaces = (credentials.IUsernamePassword, credentials.IUsernameHashedPassword) def _passwordMatch(self, matched, user): if matched: return user else: return failure.Failure(error.UnauthorizedLogin()) def requestAvatarId(self, credentials): try: user = User.objects.get(username=credentials.username) return defer.maybeDeferred( check_password, credentials.password, user.password, ).addCallback(self._password_match, user) except User.DoesNotExist: return defer.fail(error.UnauthorizedLogin) realm = ChatRealm() realm.server = ChatServer() checker = DjangoAuthChecker() p = portal.Portal(realm, [checker]) reactor.listenTCP(8800, pb.PBServerFactory(p)) reactor.run() The full error is : django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Have tried defining the enviroment variable by adding this line of code: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "webApp.settings") Also tried to call settings.configure() like this: import django from django.conf import settings settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(WEB_APP, 'db.sqlite3'), } }, INSTALLED_APPS=[ 'dashboard', 'django.contrib.auth', ] ) Also tried both setting the enviroment variable and calling settings.configure() in the same script but the error is still there. … -
Problem with custom authentication backend
I am trying to make a custom authentication for my django project.I am using a custom user model by subclassing AbstractUser. Now after creating a superuser account and trying to login from admin page, i am getting the error Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive..I've double checked that my username and password are right. After doing some research, found out that something is wrong with the custom authentication backend i am making. from support.models import CustomUser class UsernameIdModelBackend(object): def authenticate(self,username,password,uid): if username: try: user = CustomUser.objects.get(username=username) if user.check_password(password): return user except CustomUser.DoesNotExist: return None else: try: user= CustomUser.objects.get(uid=uid) return user except CustomUser.DoesNotExist: return None Ive also set AUTHENTICATION_BACKENDS in settings.py. What should be changed to correct this.Can someone please point me the right way. PS. iam new to custom authentication and is looking forward to create one with 2 types of login. -
Form is not valid
I am trying to pass data from a form to view, but form is not valid. I have 3 drop-downs on this form on clicking on submit, if any relavant data is available in the database it should be loaded on the template. Basically this form is a set of filters that load data based on selection. views.py def mentioe(request): emp_dd= request.user.username flag=0 if request.method == 'POST': form = Management_Collector(request.POST or None) if form.is_valid(): m_s = form.cleaned_data.get('month_start') m_e = form.cleaned_data.get('month_end') y = form.cleaned_data.get('process_select') mentione= mrg_bpo.objects.filter(Q(emp_id=emp_dd) & Q(month=m_s)) if not mentione: messages.error(request, 'Data is not available for your selection please consider re-selecting.') else: messages.success(request, 'Search Result Displayed Below') return render(request, 'mentione.html', {'form': form, 'mentione': mentione}) else: print(form.errors) print('some issue') else: print('i go to else') form = Management_Collector() return render(request, 'mentione.html', {'form': form}) forms.py class Management_Collector(forms.ModelForm): class Meta: model = mrg_bpo fields = ['month','year','process_select'] labels = { "month": _(""), } widget = { 'month':forms.HiddenInput(), 'year':forms.HiddenInput(), } index.html <form action="" method="POST"> {%csrf_token%} <select class="form-control" id="month_start" name="month_start"> {% for i in form.month %} <option>{{ i }}</option> {% endfor %}</select> <select class="form-control" id="month_end" name="month_end" > <option> </option> {% for i in form.month %} <option>{{ i }}</option> {% endfor %} </select> {{form.year}} {{form.process_select}} <button type="submit" class="btn … -
How to fix a Scrapy spider that, when executed as a script inside a Django package, won't go deeper into callbacks?
So basically, I'm trying to make a Django app where users could scrape information from all posts from all groups an FB user is in. I was planning to execute a scrapy spider from a view, maybe when a button is clicked or so. If you'd like to see, `(It said that I have to have a code before a pastebin link, sorry im new to SO)` https://pastebin.com/X1PqsFHu (note that the spider is not really that great, but it IS working (to some extent) I have plans to edit the code, instead of yielding information, I'd just import Models from my Django app and save it. so I saved it into a file called scraper.py and placed it inside the app package in the Django app. Now, to execute the spider, I just followed the Scrapy doc. I used the Crawler from scrapy to a module: import scrapy from scrapy.crawler import CrawlerProcess from scraper import GroupPostsSpider def scrape(inp_email, inp_pass): spider = GroupPostsSpider(email=inp_email, password=inp_pass) process = CrawlerProcess({ 'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)', 'ROBOTSTXT_OBEY': False, }) process.crawl(spider) process.start() Now, when I run the spider from a scrapy project, it actually executes from start to end, with the proper logs … -
Creating a custom import statement which accepts variables, used to import django models
I'm creating a simple script used to generate fixture data for a given django model. I cannot figure out how to create an import statement which accepts user input, to allow me to perform the actual logic on the selected model. I've tried various combinations of imp, importlib.util.spec_from_file_location, importlib.import_module, __import__, Create an import statement using variable "interpolation" The closest I've gotten is: def import_function(app, model): exec(f"from {app}.models import {model}") exec(f"print({model}.objects.all())") #This works. import_function("home", "Person") My thinking is: I create a module called 'fixture.py'. Within that module is a custom import function. I import the module into the environment created by python manage.py shell so as to obviate the need for modifying the PATH. Then, I call the function using fixture.import_function(app, model). I've managed to generate the fixture data this way, but only when I'm hardcoding the import statement, i.e. from home.models import Person. #fixture generating logic. -
Can't find template source file described in Django tutorial
I'm working through the official Django tutorial, using Django 1.8.7 for a certain reason. https://docs.djangoproject.com/en/1.8/intro/tutorial02/ I got stuck in part 2 near the end, where I should learn how to use edited template files from the Django source files to make changes of the admin site. I found the first template file in the described directory: django/contrib/admin/templates/admin/base_site.html I copied and changed it as described, and I was happy it worked. But now the issue I'm having, is this: I'm supposed to find another template file called site_header with the described package/directory django.contrib.admin.AdminSite.site_header, but I can't find it in the library of my project, which is runnig on a virtual env. -
How do I know the location of Python files from ajax on the Django server?
I need to send data to Python file with ajax, but I can't find a path, so I get 404 Not Found. So I tried to put that Python file in every folder and I tried to live it, but the same error occurred. $.ajax( { type: "POST", url: "test.py", data: params, dataType: "html", success: function (html) { alert("success"); }, error: function(request, ajaxOptions, thrownError) { alert("fail"); } }); error message is POST http://127.0.0.1:8000/test.py 404 (NOT FOUND) Do I have to add a path to urls.py? -
jquery widget for datetime picking in django-admin returns Error: 'Enter a list of values.' when i save the form
I created a custom widget in order to replace the default django's datetime picker in my administration site. To do so i followed these instructions but it ends up like this when i click save button: I have no other specific errors in the logs. For more details, here is the code: settings.py: DATE_INPUT_FORMATS = ['%d/%m/%Y %H:%M'] app/templates/widgets/xdsoft_datetimepicker.html {% include "django/forms/widgets/input.html" %} <!-- jQuery --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <!-- XDSoft DateTimePicker --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.min.css" integrity="sha256-DOS9W6NR+NFe1fUhEE0PGKY/fubbUCnOfTje2JMDw3Y=" crossorigin="anonymous" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.full.min.js" integrity="sha256-FEqEelWI3WouFOo2VWP/uJfs1y8KJ++FLh2Lbqc8SJk=" crossorigin="anonymous"></script> <script> $(function () { $("input[name='{{ widget.name }}']").datetimepicker({ format: 'd/m/Y H:i', }); }); </script> app/models.py: class DatesAndDates(models.Model): date_time_1 = models.DateTimeField() app/forms.py: class DateForm(forms.ModelForm): class Meta: model = DatesAndDates widgets = { "date_time_1": XDSoftDateTimePickerInput( ) } fields=["date_time_1"] And Finally app/admin.py: @admin.register(DatesAndDates) class DatesAndDatesAdmin(admin.ModelAdmin): form = DateForm list_display = ["date_time_1"] Before trying this i just used a Charfield for the date and time and added the jquery script by overriding the change_form.html template but i failed at converting the datetime string to a valid datetime type. Thanks for reading and for the help. -
I need to pass two foreign key values to my database to keep track of comments and the user
thank you in advance for reading this question and I hope someone is able to help me. I just began to work with Django a couple of weeks ago an I've been stuck with an issue for some time now. the purpose of the app is to have a page where people can post comments about an object, in this case a professor. So, when i submit my form, I need to store the professor's ID and the user ID to then display the comments on their respective pages. Right now I'm able to store the user ID but I can't get the professor ID. After looking through multiple questions I haven't been able to find a solution, so I'm hoping someone has had experience with a similar issue. I'm using Django 2.2 and MySQL, Here's the code I have so far. forms.py from django import forms from .models import ProfessorRating class CommentForm(forms.ModelForm): class Meta: model = ProfessorRating fields = ('body', ) views.py from .models import Professor from .forms import CommentForm from django.views.generic.edit import FormMixin from django.urls import reverse from django.views.generic import ( DetailView, ListView, ) # Create your views here. class ProfessorListView(ListView): model = Professor paginate_by = 9 template_name … -
custom field validation error does not show field name
I want to implement a change password endpoint, I have this view: def update(self, request): user_data = {} classname = __class__.__name__ function = 'update' try: user = request.user current = request.data['current'] password = request.data['password'] confirm = request.data['confirm'] serializer = serializers.ChangePasswordSerializer(user, data=request.data) if serializer.is_valid(): serializer.save(updated_by=request.user.username, updated_date=timezone.now()) logger(request, msg=_("Added Successfully"), level="normal", classname=classname, function=function, user_data=user_data, status=status.HTTP_205_RESET_CONTENT) return Response({"message": _("Added Successfully")}, status=status.HTTP_205_RESET_CONTENT) logger(request, msg=serializer.errors, level="error", classname=classname, function=function, user_data=user_data, status=status.HTTP_422_UNPROCESSABLE_ENTITY) return Response({'errors': serializer.errors}, status=status.HTTP_422_UNPROCESSABLE_ENTITY) except Exception as ValidationError: return Response({"errors": _("Current password is not correct")}, status=status.HTTP_422_UNPROCESSABLE_ENTITY) except Exception as e: elogger(msg=e.args) return Response({"message": _("status500")}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) and this is my serializer: class ChangePasswordSerializer(DynamicFieldsModelSerializer): current = serializers.CharField() confirm = serializers.CharField() def validate(self, data): if data['current'] == data['password']: raise serializers.ValidationError("Password and Current password should not be the same") if data['confirm'] != data['password']: raise serializers.ValidationError("Password and Confirm password did not match") return data class Meta: model = models.User fields = ('password', 'current', 'confirm') validators = [] def update(self, instance, validated_data): if not instance.check_password(validated_data.get('current')): raise serializers.ValidationError("Current password is not correct") else: instance.set_password(validated_data['password']) instance.save() return instance my first problem is that I get this validation error: { "errors": { "non_field_errors": [ "Password and Current password should not be the same" ] } } I want to have my field name instead …