Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
get all value of foreign key table drf django
i have this tables. i want to get all the fields of teacher table from school. current its getting the name and employee field pointing to key of teacher class Teacher(models.Model): name = models.CharField(max_length=100) key = models.CharField(max_length=50,unique=True) value = models.CharField(max_length=50) def __str__(self): return self.name class School(models.Model): name= models.CharField(max_length=100) employee = models.ForeignKey(Teacher, to_field="key",on_delete=models.CASCADE) def __str__(self): return self.name serializers.py: class TeacherSerializer(serializers.ModelSerializer): class Meta: model = Teacher fields = ('name','key','value') class SchoolSerializer(serializers.ModelSerializer): teacher = TeacherSerializer(many=True, read_only=True) class Meta: model = School fields = ('name','employee','teacher') views.py: @api_view(['GET']) def SchoolList(APIView): queryset = School.objects.all().values('name','employee','employee__value') asd=[] for sdf in queryset: asd.append(sdf) serialized_obj = SchoolSerializer(queryset,many=True) return HttpResponse(json.dumps(serialized_obj.data)) traceback: traceback (most recent call last): File "/home/tboss/Desktop/environment/tryme/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/tboss/Desktop/environment/tryme/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/tboss/Desktop/environment/tryme/venv/lib/python3.7/site-packages/django /core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/tboss/Desktop/environment/tryme/venv/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/tboss/Desktop/environment/tryme/venv/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/tboss/Desktop/environment/tryme/venv/lib/python3.7/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "/home/tboss/Desktop/environment/tryme/venv/lib/python3.7/site-packages/rest_framework/views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "/home/tboss/Desktop/environment/tryme/venv/lib/python3.7/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception raise exc File "/home/tboss/Desktop/environment/tryme/venv/lib/python3.7/site-packages/rest_framework/views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "/home/tboss/Desktop/environment/tryme/venv/lib/python3.7/site-packages/rest_framework/decorators.py", line 50, in handler return func(*args, **kwargs) File … -
Facing ModuleNotFoundError: No module named 'blog_project.wsgi'
I am trying to deploy the django application on heroku. The build was successfull however when I launched the application, I faced the import error. " No module named 'blog_project.wsgi'" . The application is running fine on the local environment. (blog) ashish@tiwari:~/Documents/Django/blog$ heroku logs --tail › Warning: heroku update available from 7.39.0 to 7.39.1. 2020-03-23T02:37:56.149348+00:00 app[web.1]: [2020-03-23 02:37:56 +0000] [4] [INFO] Listening at: http://0.0.0.0:57707 (4) 2020-03-23T02:37:56.149552+00:00 app[web.1]: [2020-03-23 02:37:56 +0000] [4] [INFO] Using worker: sync 2020-03-23T02:37:56.160538+00:00 app[web.1]: [2020-03-23 02:37:56 +0000] [10] [INFO] Booting worker with pid: 10 2020-03-23T02:37:56.170494+00:00 app[web.1]: [2020-03-23 02:37:56 +0000] [10] [ERROR] Exception in worker process 2020-03-23T02:37:56.170497+00:00 app[web.1]: Traceback (most recent call last): 2020-03-23T02:37:56.170497+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2020-03-23T02:37:56.170498+00:00 app[web.1]: worker.init_process() 2020-03-23T02:37:56.170498+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 129, in init_process 2020-03-23T02:37:56.170499+00:00 app[web.1]: self.load_wsgi() 2020-03-23T02:37:56.170499+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi 2020-03-23T02:37:56.170499+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2020-03-23T02:37:56.170500+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi 2020-03-23T02:37:56.170500+00:00 app[web.1]: self.callable = self.load() 2020-03-23T02:37:56.170501+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load 2020-03-23T02:37:56.170501+00:00 app[web.1]: return self.load_wsgiapp() 2020-03-23T02:37:56.170501+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp 2020-03-23T02:37:56.170502+00:00 app[web.1]: return util.import_app(self.app_uri) 2020-03-23T02:37:56.170502+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 350, in import_app 2020-03-23T02:37:56.170503+00:00 app[web.1]: __import__(module) 2020-03-23T02:37:56.171265+00:00 app[web.1]: ModuleNotFoundError: No module named 'blog_project.wsgi' 2020-03-23T02:37:56.173904+00:00 app[web.1]: [2020-03-23 02:37:56 +0000] … -
how to check and pass the instance of the user in my form in Django?
Hi I'm trying to create a form that accepts Log from the user however I don't know how to pass the instance of the user. I'm used to creating a CreateView for this, however since I'm planning to use customized widgets and settings, I'm using a modelform to create logs for the user. My question is is this the same way as create view to check the instance of the user? Is it still the same as what I did to my createview which is: def form_valid(self,form) : form.instance.testuser = self.request.user return super().form_valid(form) Or do I have to do something else entirely? Here is my Forms.py: from django import forms from profiles.models import User from .models import DPRLog class DateInput (forms.DateInput): input_type = 'date' class Datefield (forms.Form): date_field=forms.DateField(widget=DateInput) class dprform(forms.ModelForm): class Meta: model = DPRLog widgets = {'reportDate':DateInput()} fields = ['status','login','logout','reportDate','mainTasks','remarks'] Models.py: from django.db import models from profiles.models import User from django.urls import reverse # 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): manager = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.manager.full_name class Member(models.Model): … -
show sub categories actual category
class Category(models.Model): parent_category = models.ForeignKey('self',related_name='child_category_list',on_delete=models.SET_NULL,blank=True,null=True) name = models.CharField(max_length=255) cat_id = models.CharField(max_length=255,null=True,blank=True) path = models.TextField(null=True,blank=True) def pre_save_parent_category(sender,instance,**kwargs): instance.path = instance.name parent_category_obj = instance.parent_category while parent_category_obj is not None: instance.path = parent_category_obj.name + " > " + instance.path parent_category_obj = parent_category_obj.parent_category pre_save.connect(pre_save_parent_category,sender=Category) I have numerous categories if user input category id how can i show the sub categories of that category -
Django Rest FrameWork // Conditional Model of OneToOneField
I'm developing restful API with Django Rest Framework for a statistics homepage for Admin. The service is already in progress, and I attached Django to the database that has already been created. models.py was created through managy.py inspectdb. There are no foreign keys(or OneToOneField) in the existing tables. So I am trying to create a foreign key myself in the generated models.py. But I found a table that inserts PKs of multiple tables in one column. # models.py Amodel(models.Model): consult_id = models.IntegerField(primary_key=True) # number start from 100,000 .... Bmodel(models.Model): note_id = models.IntegerField(primary_key=True) # number start from 1 .... Cmodel(models.Model): consult_note_id = models.IntegerField(primary_key=True) # saved 'consult_id from Amodel' and 'note_id from Bmodel' with unique property. ... what_is = models.CharField(max_length=7, ...) # saved 'consult' for consult table's data and 'note' for note table's data I'm trying to replace that consult_note_id in the Cmodel with OneToOneField for a smoother ORM use. Expected code below. Cmodel(models.Model): consult_note_id = models.OneToOneField(Amodel or Bmodel, on_delete=models.SET_NULL, null=True, blank=True, db_column='consult_note_id') ... what_is = models.CharField(max_length=7, ...) Expected serialized result {consult_note_id : 100001, ..., what_is : consult}, {consult_note_id : 1, ..., what_is : note}, {consult_note_id : 100002, ..., what_is : consult}, {consult_note_id : 100003, ..., what_is : consult}, {consult_note_id : 2, … -
Django Rest Framework, is it possible to organize uploaded files by associated user?
I'm planning out a backend which takes in an email associated with a file upload. Would it be possible to make the backend create a new sub-folder (with the name being the uploaded email address) in my main media folder every time a file was uploaded with a new email, or put files into the corresponding sub-folder? I've tried to look up any examples of this, but haven't come across any. Thanks! -
How to annotate a queryset with an indirectly related table?
I've got the following table: class Parent: pass class Child: fk_parent = models.OneToOneField(Parent, on_delete=models.CASCADE) class Cousin: fk_parent = models.OneToOneField(Parent, on_delete=models.CASCADE) I want to get a queryset of Child that is annotated with it's Cousin. In PSQL, I would simply write: SELECT a.*, b.* FROM child a INNER JOIN cousin b ON b.fk_parent_id = a.fk_parent_id Is this possible? -
How can I solve this error [ModuleNotFoundError: No module named 'django.utils.inspect']
When I launch my Django project in a local server, It doesn't work with the errors. It seems finally has an ImportError of the Django, but first I want to solve the error brow. ModuleNotFoundError: No module named 'django.utils.inspect' in this case, how should I do? Would you mind telling me how should I solve this problem? Thank you in advance. detailed error Traceback (most recent call last): File "/Users/apple/GoogleDrive/project_django/harvest_timer/manage.py", line 10, in main from django.core.management import execute_from_command_line File "/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 13, in <module> from django.core.management.base import ( File "/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages/django/core/management/base.py", line 11, in <module> from django.core import checks File "/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages/django/core/checks/__init__.py", line 8, in <module> import django.core.checks.caches # NOQA isort:skip File "/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages/django/core/checks/caches.py", line 2, in <module> from django.core.cache import DEFAULT_CACHE_ALIAS File "/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages/django/core/cache/__init__.py", line 18, in <module> from django.core import signals File "/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages/django/core/signals.py", line 1, in <module> from django.dispatch import Signal File "/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages/django/dispatch/__init__.py", line 9, in <module> from django.dispatch.dispatcher import Signal, receiver # NOQA File "/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 4, in <module> from django.utils.inspect import func_accepts_kwargs ModuleNotFoundError: No module named 'django.utils.inspect' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/apple/GoogleDrive/project_django/project/manage.py", line 21, in <module> main() File "/Users/apple/GoogleDrive/project_django/project/manage.py", line 16, in main ) from exc ImportError: … -
Why am I getting django.template.base.VariableDoesNotExist: Failed lookup for key [url] on all my Django webpages
Everything works as expected in my Django app, but I don't understand why I'm getting DEBUG messages as follows for all my webpages, the problem that I have with these messages is that it's unnecessarily filling up my log file (with about 300 lines at once): django.template.base.VariableDoesNotExist: Failed lookup for key [url] in [{'True': True, 'False': False, 'None': None}, {'csrf_token': <SimpleLazyObject: 'VBjv3GthwGz8kVX4aArtnnNKEpRzwtQvG4uv62GAQtXmJUOwtbP2zMiOBzWfigWgXha'>, 'request': <WSGIRequest: GET '/'>, 'user': <SimpleLazyObject: <function AuthenticationMiddleware.process_request.<locals>.<lambda> at 0x0000023C30CEEEA0>>, 'perms': <django.contrib.auth.context_processors.PermWrapper object at 0x0000023C3044C518>, 'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0x0000023C304C9F60>, 'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30, 'ERROR': 40}}, {}] django.template.base.VariableDoesNotExist: Failed lookup for key [title] in [{'True': True, 'False': False, 'None': None}, {'csrf_token': <SimpleLazyObject: 'VBjv3GthwGz8kVX4aArtnnNKEpRzwtQvG4uv62GAQtXmJUOwtbP2zMiOBzWfigWgXha'>, 'request': <WSGIRequest: GET '/'>, 'user': <SimpleLazyObject: <function AuthenticationMiddleware.process_request.<locals>.<lambda> at 0x0000023C30CEEEA0>>, 'perms': <django.contrib.auth.context_processors.PermWrapper object at 0x0000023C3044C518>, 'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0x0000023C304C9F60>, 'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30, 'ERROR': 40}}, {}] django.template.base.VariableDoesNotExist: Failed lookup for key [media] in [{'True': True, 'False': False, 'None': None}, {'csrf_token': <SimpleLazyObject: 'VBjv3GthwGz8kVX4aArtnnNKEpRzwtQvG4uv62GAQtXmJUOwtbP2zMiOBzWfigWgXha'>, 'request': <WSGIRequest: GET '/'>, 'user': <SimpleLazyObject: <function AuthenticationMiddleware.process_request.<locals>.<lambda> at 0x0000023C30CEEEA0>>, 'perms': <django.contrib.auth.context_processors.PermWrapper object at 0x0000023C3044C518>, 'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0x0000023C304C9F60>, 'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30, 'ERROR': 40}}, {}] I do have url variable in all my templates, used … -
How can I use filter() with Djongo to lookup a TextField?
Admin.py Models.py Example of a post at my Mongodb collection: My entire code: https://github.com/mtrissi/news_site_project So, I'm trying to develop an app with Django and with a Mongodb database. I'm using Djongo as the connector. All seems to work fine, except the search at the attribute 'content' of my model 'Post'. It should work fine with a simple posts = Post.filter(content__icontains=r_search). But it does not. My views.py are like this: How can I perform a search at the 'content' attribute? -
how to store conditional statement variable in django model?
i am trying to store manage_quota and govt_quota to my model choice_filling but the error says that above named variables are not defined. how do i store those values in database? here is my views.py def seat_info(request): global manage_quota, govt_quota if request.method == "POST": institute_code = request.POST['institute_code'] seats = request.POST['seates'] # s75 = int(seats) * 75 / 100 s25 = int(seats) * (25 / 100) # s25 = int(float(seats) * (25.0 / 100.0)) print("25% is ", s25) mq = request.POST['manage_quota'] mq15 = int(float(s25) * (15.0 / 100.0)) print("15% is ", mq15) # mq = float(mq) / 15.0 if float(mq) <= mq15: manage_quota = int(s25 * float(mq)) gov = request.POST['govt_quota'] gov10 = int(float(s25) * (10.0 / 100.0)) # gov = float(gov) / 10.0 if float(gov) <= gov10: govt_quota = int(s25 * float(gov)) clg_id = request.POST['clg_id'] fees = request.POST['fees'] course = request.POST['course'] s = seat_metrix(clg_id_id=clg_id, code=institute_code, total_seats=seats, course_id=course, govt_quota=govt_quota, manage_quota=manage_quota, fees=fees) s.save() return redirect('college-dashboard') strm = streams.objects.all() title = "Seat Information" page = "Seat Registration" return render(request, 'seat_info.html', {'strm': strm, 'title': title, 'page': page}) And the error traceback Traceback (most recent call last): File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) … -
I want to put html tag in password_reset_email.html but it doesn't render. How can I render it?
I want to put html tag in password_reset_email.html but it doesn't render. How can I render it? Django version is 1.4 There is no content in the document, is there any way? https://django-doc-test-kor.readthedocs.io/en/old_master/topics/auth.html -
How to Implement Cascading Dependent Drop Down List using Foreign Key Relationship in Django Admin GUI
Can anyone please provide me the resource or idea for the implementation of Cascading Dependent Drop Down List in Django Admin GUI. I don't want to create a new custom html page, I want to use the existing Admin GUI only. I've tried many things in the ModelForm and Model, but with not success. I have 4 tables: Person, Country, State and City. What I want to do is: In the New/Edit Admin Person GUI page, select the country, next select the state and at the end, select the city. Actually in the New/Edit Admin Person page I have only the city. My Actual database relationship: Country ----- State ---- City ----- Person -
I am receiving an error when try render template in django
I created a template.html from the pandas data frame em saved it to render in my HTML file. So, when I try to render it I receive an error: File "c:\users\eric2\appdata\local\programs\python\python37\lib\codecs.py", line 322, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xed in position 347: invalid continuation byte The complete output is: Internal Server Error: /analise Traceback (most recent call last): File "D:\Projetos Dev\.venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "D:\Projetos Dev\.venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "D:\Projetos Dev\.venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Projetos Dev\analise\views.py", line 100, in analise return result(request) File "D:\Projetos Dev\analise\views.py", line 23, in result return render(request, 'result.html') File "D:\Projetos Dev\.venv\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "D:\Projetos Dev\.venv\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "D:\Projetos Dev\.venv\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "D:\Projetos Dev\.venv\lib\site-packages\django\template\base.py", line 171, in render return self._render(context) File "D:\Projetos Dev\.venv\lib\site-packages\django\template\base.py", line 163, in _render return self.nodelist.render(context) File "D:\Projetos Dev\.venv\lib\site-packages\django\template\base.py", line 936, in render bit = node.render_annotated(context) File "D:\Projetos Dev\.venv\lib\site-packages\django\template\base.py", line 903, in render_annotated return self.render(context) File "D:\Projetos Dev\.venv\lib\site-packages\django\template\loader_tags.py", line 150, in render return compiled_parent._render(context) File "D:\Projetos Dev\.venv\lib\site-packages\django\template\base.py", … -
running migrations as a part of an MS Azure app service release pipeline for a Django web app
I am wondering if anybody has experience with integrating a python manage.py migrate command into a MS Azure release pipeline. The app is being deployed using CI/CD pipeline through DevOps. In the release pipeline portion, the app is being deployed to three different stages (dev, test and prod). I have not been successful in being able to integrate the migrate command into the deployment process. I have tried achieving this by using a post deployment inline script: /antenv/bin/python /home/site/wwwroot/manage.py collectstatic /antenv/bin/python /home/site/wwwroot/manage.py migrate If I run the above commands in the sandbox environment via SSH they are carried out successfully. However, including them in the release pipeline as a post deployment script raises the following error: 2020-03-22T19:00:32.8641689Z Standard error from script: 2020-03-22T19:00:32.8727872Z ##[error]/home/site/VSTS_PostDeployment_1321584903618191/kuduPostDeploymentScript.sh: 1: /home/site/VSTS_PostDeployment_1321584903618191/kuduPostDeploymentScript.sh: /antenv/bin/python: not found /home/site/VSTS_PostDeployment_1321584903618191/kuduPostDeploymentScript.sh: 2: /home/site/VSTS_PostDeployment_1321584903618191/kuduPostDeploymentScript.sh: /antenv/bin/python: not found 2020-03-22T19:01:34.3372528Z ##[error]Error: Unable to run the script on Kudu Service. Error: Error: Executed script returned '127' as return code. Error: /home/site/VSTS_PostDeployment_1321584903618191/kuduPostDeploymentScript.sh: 1: /home/site/VSTS_PostDeployment_1321584903618191/kuduPostDeploymentScript.sh: /antenv/bin/python: not found /home/site/VSTS_PostDeployment_1321584903618191/kuduPostDeploymentScript.sh: 2: /home/site/VSTS_PostDeployment_1321584903618191/kuduPostDeploymentScript.sh: /antenv/bin/python: not found Any ideas or suggestions would be very much appreciated! Thanks in advance. -
Filtering output of foreign key data
Since i am making a online futsal booking system, i am currently doing timeslot validation. If a timeslot is already booked, the user should not be able to book that timeslot again. models.py class futsals(models.Model): futsal_name = models.CharField(max_length=20) futsal_address = models.CharField(max_length=40) owner_email = models.EmailField(max_length=25) owner_name = models.CharField(max_length=25) def __str__(self): return f'{self.futsal_name}' class timeslot(models.Model): timesslot = models.CharField(max_length=15) name = models.CharField(max_length=15) def __str__(self): return f'{self.timesslot}' class Booking(models.Model): user_book = models.ForeignKey(User, on_delete=models.CASCADE) futsal = models.ForeignKey(futsals, on_delete=models.CASCADE) time_slot = models.ForeignKey(timeslot, on_delete=models.CASCADE) def validate_date(date): if date < timezone.now().date(): raise ValidationError("Date cannot be in the past") booking_date = models.DateField( default=None, validators=[validate_date]) def __str__(self): return f'{self.user_book}' forms.py def timeslot_validation(value): v = Booking.objects.all().values_list('time_slot') k = timeslot.objects.filter(pk__in=v) if value == k: raise forms.ValidationError("This timeslot is already booked!!") else: return value But i am not able to do the validation. Since the output of variable 'k' looks like: , , ]> the above shown timeslot are the timeslot booked by users. Now if another user enters this timeslot, it should show 'this timeslot is already booked.' now, i want this data to be shown as [(19:00 - 20:00), (18:00 - 19:00), (17:00 - 18:00)] any help would be appreciated. or if anyone could provide me a better solution for validation????? -
Method Not Allowed POST 405
I am trying to add a post to my website inDjango using Ajax. However, whenever, I click on the post button I get the error: 'Method Not Allowed: /home/ "POST /home/ HTTP/1.1" 405 0 I do not know what is causing the issue I have never seen it before. These are my views for creating a post and viewing them. @login_required def home(request): posts = Post.objects.all() context = {'posts':posts} return render(request, 'home/home.html', context) class PostListView(LoginRequiredMixin,ListView): model = Post #redirect_field_name = template_name = 'home/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] @login_required def post_create(request): data = dict() if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): form.save() data['form_is_valid'] = True posts = Post.objects.all() data['posts'] = render_to_string('home/home_post.html',{'posts':posts}) else: data['form_is_valid'] = False else: form = PostForm context = { 'form':form } data['html_form'] = render_to_string('home/post_create.html',context,request=request) return JsonResponse(data) These are my urls at home/urls.py: urlpatterns = [ path('',views.PostListView.as_view(), name='home'), path('post/<int:pk>/', views.post_detail, name='post-detail'), path('<int:pk>/like/', views.PostLikeToggle.as_view(), name='like-toggle'), path('api/<int:pk>/like/', views.PostLikeAPIToggle.as_view(), name='like-api-toggle'), path('post/<int:id>/update/', views.post_update, name='post-update'), path('post/<int:id>/delete/', views.post_delete, name='post-delete'), path('post/create/', views.post_create, name='post-create'), ] this is my post_create.html: {% load crispy_forms_tags %} <form method="POST" data-url="{% url 'home:post-create' %}" class="post-create-form"> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title" >Create a Post</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> … -
Django add custom search function with empty search_fields tuples
I have the following get_search_results within my ModelAdmin to search by user phone number and email: def get_search_results(self, request, queryset, search_term): queryset, use_distinct = super().get_search_results(request, queryset, search_term) try: search_string = str(search_term) users = User.objects.filter(Q(email__icontains=search_string) | Q(phone_number__icontains=search_string)) user_id_list = [int(user.pk) for user in users] queryset |= self.model.objects.filter(user__in=user_id_list) except Exception as e: pass So these search_term won't exist in my model column therefor i won't need model columns in the search_fields. But if i set my search_fields = () then it won't show the search box in the listing page. Are there anyway i can add search box to the list page without specify any columns from the model ? -
Looking in links: /usr/share/pip-wheels
I was using a virtualenv in Pythonanywhere and now after cloning my repo I tried to install all the packages by using this command pip install -r packageName/requrirements.txt What is get is this Looking in links: /usr/share/pip-wheels I don't know about pip a lot.So please tell me what this eror means and how can i fix it with examples!Thank you in advance. -
Django: Default ImageField Return
I have a Django ImageField with djangorestframework, and I want it to return a default image if it's none. How can I return an image from my staticfiles to replace this? class MyModel(models.Model): image = models.ImageField() ... def get_image(self): """ Returns an image, or the default image. """ if not self.image: # what goes here? <--- return self.image -
virtualenv: error: the following arguments are required: dest
enter image description here I can't install and configure virtual environment on python3 on my macbook pro. I was trying to install and try django for my next project but here problemts started arising. -
can we change the name of manage.py file in django?
In Django framework I need to rename manage.py file for the security reasons on production environment. I do not have any idea about this. could someone help me out for the same -
django.core.exceptions.FieldError: Unknown field(s) (datetime) specified for Class
So I have a class named InputArticle, and have a field named 'created' and 'modified.' Below is my code in models.py from django.db import models from django.contrib.auth.models import User from django.forms import ModelForm from django.utils import timezone class InputArticle(models.Model) ''' other fields ''' created = models.DateTimeField(editable=False) modified = models.DateTimeField() def save(self, *args, **kwargs): if not self.created: self.created = timezone.now() self.modified = timezone.now() return super(InputArticle, self).save(*args, **kwargs) However when I try to do python manage.py makemigrations I keep getting this error that says: django.core.exceptions.FieldError: Unknown field(s) (datetime) specified for InputArticle I have no idea on what the problem is. I very much appreciate your help :) -
Python Django request.GET.get method for urls with if statements
I'd want to filter the posts by its two different categories which are schools and category. models.py class Category(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name class School(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True) class Meta: ordering = ('name',) verbose_name = 'school' verbose_name_plural = 'schools' def __str__(self): return self.name class VideoPost(models.Model): category = models.ForeignKey('Category', on_delete=models.CASCADE) school = models.ForeignKey('School', on_delete=models.CASCADE) title = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique = True) author = models.ForeignKey(User, on_delete=models.CASCADE) video = models.CharField(max_length=100, blank=True) content = RichTextUploadingField() image = models.ImageField(upload_to='images', null=True, blank=True) date_posted = models.DateTimeField(default=timezone.now) def _get_unique_slug(self, *args, **kwargs): self.slug = slugify(self.title) super(VideoPost, self).save(*args, **kwargs) def __unicode__(self): return self.title School and Category are the foreignKeys for VideoPost, so in the db, it would only have its ids, not the slug or name. whcih are category_id & school_id views.py def post_list(request): school = request.GET.get('school', None) category = request.GET.get('category', None) posts = VideoPost.objects.all() if school: posts.filter(school=school).order_by('-date_posted') elif category: posts.filter(category=category).order_by('-date_posted') elif school & category: posts.filter(school=school).filter(category=category).order_by('-date_posted') else: posts.order_by('-date_posted') ## I wanted to filter them in multiple ways where the posts are filtered by either one of the category, or both. but It doesn't work. ## The … -
accessing javascript outside of django project
I have become the owner of an older webapp that uses django and esri/jsapi3.28. I am trying to reconstruct it in development environment. It works in production using apache2 with document root at the 'webapp' directory. I would like to create a development environment w/o apache2 and instead use django's runserver. But when trying to test in development using runserver, it cannot find the 'my_ext_js' directory. I believe this is because the document root is different? It appears I cannot change the document root. This is the webapp structure. webapp my_ext_js start.js django_app myapp django_app Again, in production, we run apache2 with mod_wsgi and document root is webapp. When running in development, I start runserver in django_app directory django_app> python manage.py runserver how can I run this using runserver in development and have it recognize/see the 'my_ext_js' folder? The production code does not have the 'my_ext_js' in a static folder. The html script just calls: <script src="/my_ext_js/start.js"></script> Any help would be great! Thanks!