Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django not accepting from that JavsScript has inserted a value into
I have a Django form uses FormBuilder.js. The intent is to use the JSON recieved from FormBuilder and have that JSON inserted into the JSON [Django] field using vanilla JavsScript (by directly setting it's .value). Django does not validate the form when using this method. However, if I hard type the JSON, or when the form fails and I return back to the page immediately, the form will validate. I have looked into the form itself on POST and the data is no different via any methods. Does anyone have a clue what's going on? -
How to create a Dynamic upload path Django
I have a Django rest api that converts user uploaded video to frame using Opencv. I also have a function upload_to that creates a dynamic path for the uploaded video. I want to write the frames from the video into the upload_to folder. I tried cv2.imwrite(os.path.join(upload_to,'new_image'+str(i)+'.jpg'),frame) but it yield an error. def upload_to(instance, filename): now = timezone.now() base, extension = os.path.splitext(filename.lower()) return f"SmatCrow/{instance.name}/{now:%Y-%m-%d}{extension}" Opencv script def video_to_frame(video): now = timezone.now() cap= cv2.VideoCapture(video) i=1 while(cap.isOpened()): ret, frame = cap.read() if ret == False: break if i%10 == 0: cv2.imwrite(('media/SmatCrow/new_image'+str(i)+'.jpg'),frame) i+=1 cap.release() cv2.destroyAllWindows() My model.py class MyVideo(models.Model): name= models.CharField(max_length=500) date = models.DateTimeField(auto_now_add=True) videofile= models.FileField(upload_to=upload_to) def __str__(self): return self.name + ": " + str(self.videofile) def save(self, *args, **kwargs): super(MyVideo, self).save(*args, **kwargs) tfile = tempfile.NamedTemporaryFile(delete=False) tfile.write(self.videofile.read()) vid = video_to_frame((tfile.name)) -
How to encrypt DjangoRESTFramework SimpleJWT's?
is there a way to encrypt the tokens the simple JWT backend for DRF creates? I want to store them as cookies, so want them to be obscured. Additionally, is it appropriate to name the cookies "refresh" and "access" in the browser? -
django form resubmitted upon refresh when using context_processors
I'm trying on creating a user registration form and able to succeed with the registration process and validation. The form is handled using context_processor because the form is on the base.html and in inside a modal. Upon submission, I need to redirect to the current page the user is in and it works. But my form keeps re-submitting upon refresh. context_processor.py def include_registration_form(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request, 'Account was created for {}. Now you can sign in.'.format(user)) else: messages.error(request, "Something went wrong. Account not created!") context = { 'registration_form': form, } return context forms.py class CreateUserForm(UserCreationForm): first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) email = forms.EmailField(required=True) class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2'] url patterns urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='index'), path('menu', views.menu, name='menu'), path('promo', views.promo, name='promo'), ] template(base.html) <form class="needs-validation" action="" method="post" novalidate> {% csrf_token %} {% for field in registration_form %} <div class="col-sm"> <label>{{ field.label }}</label> {% if registration_form.is_bound %} {% if field.errors %} {% render_field field class="form-control form-control-sm is-invalid" %} {% if field.name == 'username' or 'password1' %} <small> {{ field.help_text }} </small> {% endif %} <div … -
why django-mptt do not render children correctly
I'm developing a web app in Python3.7 with django (3.1.2). I would like to create app which will lists folders and files under some path. I would like to use django.mptt to do it. I have path declared in my settings.py: MAIN_DIRECTORY = r'D:\imgs' I created following model: class Folder(MPTTModel): name = models.CharField(max_length=30, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['name'] and view: class MainView(TemplateView): template_name = "main.html" def get_directories(self): path = settings.MAIN_DIRECTORY self.tree = self.get_folder_from_db(path, None) for root, dirs, files in os.walk(path): if root == path: continue root_folder = self.get_folder_from_db(name=root, parent=self.tree) for d in dirs: if os.path.isdir(d): tmp = self.get_folder_from_db(name=d, parent=root_folder) def get_folder_from_db(self, name, parent): try: obj = Folder.objects.get(name=name, parent=parent) except Folder.DoesNotExist: obj = Folder(name=name, parent=parent) obj.save() return obj def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) self.get_directories() context['tree'] = [self.tree] return context and of course I have template (copied from mptt tutorial): {% extends 'base.html' %} {% load mptt_tags %} {% block content %} <h2>Main page</h2> <ul class="root"> {% recursetree tree%} <li> {{ node.name }} {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> {% endblock %} I know that te tree structure is correct, … -
NOT ABLE TO RETURN TABLE IN DJANGO TEMPLATES USING PYTHON
I wrote a code in python to get stock data and return it inside html page in Django. I want to view it in table format in html page, Plz suggest how to call my python code in html webpage so that it will show output in html -
How can i filter a models property in django?
im quite new in backend development so i got a basic question. I've three different models one named Campaigns; class Campaigns(models.Model): channel = models.ForeignKey(Channels, blank=False, verbose_name="Channel Name", on_delete=models.CASCADE) campaign_name = models.CharField(max_length=255, blank=False, verbose_name="Campaign Name") Second one is; class CampaignDetails(models.Model): channel = models.ForeignKey(Channels, blank=False, null=True, verbose_name="Channel Name", on_delete=models.CASCADE) name = models.ForeignKey(Campaigns, blank=False, null=True, verbose_name="Campaign", on_delete=models.CASCADE) And the last one is; Class Channels(models.Model): name = models.CharField(max_length=50, null=False, blank=False, verbose_name="Tv Channel") I want to filter name in CampaignDetails by channel. Like if i choose channel 1 i want to filter name by campaign names that under that channel. How can i manage that? Any help is appreciated, thank you. -
my mysqlclient is not installing and it throws this error...someone help. am new to code btw
Collecting mysqlclient Using cached mysqlclient-2.0.1.tar.gz (87 kB) ERROR: Command errored out with exit status 1: command: /home/moonguy/Documents/smartbill/virtual/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-lp9dtwz6/mysqlclient/setup.py'"'"'; file='"'"'/tmp/pip-install-lp9dtwz6/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-m1qj8ead cwd: /tmp/pip-install-lp9dtwz6/mysqlclient/ Complete output (12 lines): /bin/sh: 1: mysql_config: not found /bin/sh: 1: mariadb_config: not found /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "", line 1, in File "/tmp/pip-install-lp9dtwz6/mysqlclient/setup.py", line 15, in metadata, options = get_config() File "/tmp/pip-install-lp9dtwz6/mysqlclient/setup_posix.py", line 65, in get_config libs = mysql_config("libs") File "/tmp/pip-install-lp9dtwz6/mysqlclient/setup_posix.py", line 31, in mysql_config raise OSError("{} not found".format(_mysql_config_path)) OSError: mysql_config not found ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. -
How to override serializers save method in django rest?
Here I have only one view for saving two serializer models. Now While saving the RegisterSerializer UserLogin serializer is also saving. But now what I want to change is, I want to change the status of is_active in UserLogin to True automatically without user input while saving the searializers. I don't want to change it to default=True at model. serializers class UserloginSerializer(serializers.ModelSerializer): class Meta: model = UserLogin fields = ['m_number'] class RegisterSerializer(serializers.ModelSerializer): user_login = UserloginSerializer() #...... class Meta: model = User fields = ['user_login',..] models class Memberlogins(models.Model): is_active = models.BooleanField(default=False) m_number = models.CharField(max_length=255, blank=True, null=True) views class RegisterView(APIView): serializer = RegisterSerializer def post(self, request): context = {'request': request} serializer = self.serializer(data=request.data,context) if serializer.is_valid(raise_exception=True): serializer.save() -
403 Forbidden You don't have permission to access this resource. - Django
I recently made some changes to my Django app and pulled them back to the server. After doing so I am experiencing some error messages when trying to access my website. When I visit the website I am given Forbidden You don't have permission to access this resource. and in my /var/log/apache2/portfolio-error.log i see the following error logs. [Wed Oct 28 08:51:06.883684 2020] [core:error] [pid 11345:tid 139674953709312] (13)Permission denied: [client xx.xx.xxx.xx:48690] AH00035: access to / denied (filesystem path '/svr/portfolio/portfolio') because search permissions are missing on a component of the path [Wed Oct 28 08:51:07.085543 2020] [core:error] [pid 11345:tid 139675068827392] (13)Permission denied: [client xx.xx.xxx.xx:48690] AH00035: access to /favicon.ico denied (filesystem path '/svr/portfolio/static') because search permissions are missing on a component of the path, referer: https://example.com/ [Wed Oct 28 08:51:34.899776 2020] [core:error] [pid 12041:tid 140689096595200] (13)Permission denied: [client xx.xx.xxx.xx:48694] AH00035: access to / denied (filesystem path '/svr/portfolio/portfolio') because search permissions are missing on a component of the path [Wed Oct 28 08:51:35.112403 2020] [core:error] [pid 12041:tid 140689088202496] (13)Permission denied: [client xx.xx.xxx.xx:48694] AH00035: access to /favicon.ico denied (filesystem path '/svr/portfolio/static') because search permissions are missing on a component of the path, referer: https://example.com/ Also here are the permissions on my project: drw-rw-r-- 9 … -
In my Django-project how can I dynamically append a script which is located in the static folder to the head-section?
In my Django-project I would like to dynamically append a script-tag to the head-section. The script I want to append is located in static-folder. The problem is that I don't know how to reference the static-folder in javascript, or if that is even pssible. This is (a part of) my Javascript: jQuery( window ).on( "load", () => { const script = document.createElement("script"); script.src = "{% static 'js/myScript.js' %}"; document.head.appendChild(script); }); myScript.js could look like this: console.log("This is myScript") Of course this does not work. In the console I get: GET http://127.0.0.1:8000/%7B%%20static%20'js/myScript.js'%20%%7D net::ERR_ABORTED 404 (Not Found). Is there a way to reference the static-folder inside a javascript? -
Python doesn't see packages in virtual environment
I try to deploy my first django project on heroku and for that i need to import whitenoise. I have it installed in site-packages, but have an ImportError when import it. And python doesn't see packages in there apart from django and default ones. I'm quite a novice and don't understand what it means and what to do. Tried to add PYTHONPATH to activate, add a new path in SystemPropertyAdvanced, didn't help -
datetime-local time format does not conform to the required format
I hope this question is not a duplicate - I was at least not able to fix the issue by looking at other similar Q&As. I'm making a web application using Django 2.2, Postgresql 9.5 and Django template language with bootstrap for front end. In settings.py I have the following time settings: TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True In some of my forms I have datetime-local fields: date = forms.CharField(required=False, widget=forms.DateTimeInput( attrs={ 'type':'datetime-local', 'class':'form-control', } )) In my Django template I render the date field as shown below: <input type="datetime-local" id="id_date" class="form-control" value="{{ basic_form.date.value|date:"c"}}"> I'm getting the following error when loading a page with date field having a date value retrieved from database. And I'm not able to display the date in the form date field: The specified value "2020-10-28T09:28:00+00:00" does not conform to the required format. The format is "yyyy-MM-ddThh:mm" followed by optional ":ss" or ":ss.SSS". I have also tried to 'render' the date field in the template directly from the form variable received by views.py: {{ basic_form.date }} ...and then I get a same warning, however the date value does not contain the T 'separator': The specified value "2020-10-28 09:28:00+00:00" does not … -
Connecting to Mongodb from Django application hosted on heroku
I am trying to connect my djnago application hosted on heroku. I have also changed the DATABASE_URL on heroku settings as: mongodb+srv://<name>:<password>@cluster0.wtnph.mongodb.net/test I am using python 3.9 and django 3.0.5 But when deploying to heroku, I am getting the error. > -----> Python app detected -----> No change in requirements detected, installing from cache -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 -----> Installing SQLite3 -----> Installing requirements with pip -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 345, in execute settings.INSTALLED_APPS File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 76, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/tmp/build_91bba5c0/kibo_skill_matrix_api/settings.py", line 176, in <module> django_heroku.settings(locals()) File "/app/.heroku/python/lib/python3.6/site-packages/django_heroku/core.py", line 69, in settings … -
Filter child related object and return empty list if none is found
Is there a way to filter child objects and return an empty list if no related object matching the query is found? At the moment I'm doing it in this way: Person.object.filter(item__is_active=True) If no active item is found, None is returned. I want to still get the Person object but with the items attribute as an empty list. -
Upload csv file and return back information in Django
views.py from django.shortcuts import render import pandas as pd import csv # Create your views here. def home(request): return render(request,'hello/home.html') def output(request): csvfile = request.FILES['csv_file'] data = pd.read_csv(csvfile.name) data_html = data.to_html() context = {'loaded_data': data_html} return render(request, "hello/home.html", context) Here I am trying to get the uploaded file and convert the file to table format. While doing this,I am getting No such file or directory: 'file.csv' Please help in solving this -
Nginx + uwsgi + Django
Django web application deployed with nginx + uwsgi. If we daemonize the application, the api request using fetch is leading to a 504 Gateway Time-out. I have tried to fix it by using proxy timeout and gateway timeout but no luck. Also after restarting the server I am able to see the output but this doesnt happen when we run uwsgi in normal mode (not daemonized) -
OSError: [Errno 24] Too many open files , [ django , python , PyCharm ]
I faced this problem when i tried to upload about 7000 images via django. I want all of them open to pass them to Yolo-core, who can help me? During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Asus\Anaconda3\lib\wsgiref\handlers.py", line 137, in run File "C:\Users\Asus\Anaconda3\lib\site-packages\django\contrib\staticfiles\handlers.py", line 66, in __call__ File "C:\Users\Asus\Anaconda3\lib\site-packages\django\core\handlers\wsgi.py", line 146, in __call__ File "C:\Users\Asus\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 81, in get_response File "C:\Users\Asus\Anaconda3\lib\site-packages\django\core\handlers\exception.py", line 37, in inner File "C:\Users\Asus\Anaconda3\lib\site-packages\django\core\handlers\exception.py", line 87, in response_for_exception File "C:\Users\Asus\Anaconda3\lib\site-packages\django\core\handlers\exception.py", line 122, in handle_uncaught_exception File "C:\Users\Asus\Anaconda3\lib\site-packages\django\views\debug.py", line 94, in technical_500_response File "C:\Users\Asus\Anaconda3\lib\site-packages\django\views\debug.py", line 331, in get_traceback_html File "C:\Users\Asus\Anaconda3\lib\pathlib.py", line 1176, in open File "C:\Users\Asus\Anaconda3\lib\pathlib.py", line 1030, in _opener OSError: [Errno 24] Too many open files: 'C:\\Users\\Asus\\Anaconda3\\lib\\site-packages\\django\\views\\templates\\technical_500.html' [28/Oct/2020 10:44:30] "POST /train HTTP/1.1" 500 59 Exception ignored in: <function TemporaryFile.__del__ at 0x000001F16A1EE488> Traceback (most recent call last): File "C:\Users\Asus\Anaconda3\lib\site-packages\django\core\files\temp.py", line 61, in __del__ File "C:\Users\Asus\Anaconda3\lib\site-packages\django\core\files\temp.py", line 49, in close AttributeError: 'TemporaryFile' object has no attribute 'close_called' -
i got pylint error how to fix this anyone please help i am working with django development server
enter image description here I got this pylint error please tell me how to fix this? -
Query the n-th most recent entries for each unique type, for all types in Django
I have researched this issue and answers are about getting the most recent for each type, e.g. this topic. The difference is I would like to get the n most recent items for each type, for ALL types. At the moment I get all items, then in python find the n-th most recent entries, which is very slow. e.g. class CakeType(models.Model): name = models.CharField() class CakeEntry(models.Model): cake_type = models.ForeignKey(CakeType, on_delete=models.CASCADE) created = models.DateTimeField() How would one get say the 5 most recent CakeEntry's for all the distinct/unique CakeType's? I migrated DB from MySQL to PostgreSQL (a lot of work) so I can use Postgres's DISTINCT ON. -
Events auto delete in Django / Python
I have an event calendar in Django / Python and I am trying to get it to automatically not show events that have already passed based on the current date. The code I am working with looks like this: {% for event in view.events %} <div class="py-2"> {% if event.date < Today %} <ul> <li class="font-bold text-gray-900">{{ event.date }}</li> <li class="font-medium text-gray-800">{{ event.name }}</li> <li class="font-medium text-gray-800">{{ event.description }}</li> <strong><p>Location:</p></strong> <li class="font-medium text-gray-800">{{ event.location }}</li> {% if event.website_url %} <a class="font-medium text-gray-800 hover:font-bold hover:text-blue-600" href="{{ event.website_url }}" target="blank">Information </a> {% endif %} {% endif %} </ul> </div> In the top of the code I have the line: {% if event.date > Today %} What can I replace Today with to make this work? Any ideas? -
The best way to make a matrix-like form in Django?
I'm making a booking site on Django with sqlite database. I want a model which has entries for data of day, and a form which has boolean fields for each booking slot. What is the best way to realize this? Do I need to use ForeignKey relationships between day, room and slot models? If yes, how do I do that? -
how to give custom validation in django and djangorestframework on creating an API?
Here is my question I am creating address model, in that city, district I am accepting null values, Because for some API View I will accept Null values, but another API I will call this same models that time I want to validate that field is required, How Its is possible Here is my below code example. models.py class Address(models.Model): address_line1 = models.CharField(max_length=250) address_line2 = models.CharField(max_length=250, blank=True, null=True) city = models.ForeignKey('Cities', on_delete=models.DO_NOTHING, blank=True, null=True) district = models.ForeignKey('Districts', on_delete=models.DO_NOTHING, blank=True, null=True) class Assignaddress(models.Model): address = models.ForeignKey(Address, on_delete=models.CASCADE) owner_name = models.CharField(max_length=255) class dont`Assignaddress(models.Model): address = models.ForeignKey(Address, on_delete=models.CASCADE) owner_name = models.CharField(max_length=255) Now in serializer.py class AddressSerializer(serializers.ModelSerializer): class Meta: model = Address fields = ('address_line1','address_line2','city','district') class AssignaddressSerializer(serializers.ModelSerializer): class Meta: model = Assignaddress fields = ('address ','owner_name ') class dont`AssignaddressSerializer(serializers.ModelSerializer): class Meta: model = dont`Assignaddress fields = ('address ','owner_name ') now How can I validate Assignaddress you have to pass city and district is required and don`tAssignaddress its not neccessary Sorry for not writting views.py -
Error when trying to decode json: simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I'm receiving this error when trying to decode json: simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0) Any help will be appreciated. views.py: from django.shortcuts import render import requests def home(request): response = requests.get('https://dev-api.prime.com/api/v1/hub/login') data = response.json() return render (request, 'home.html', { 'email': data['email'], 'password': data['password'] }) urls.py: path ('home/', views.home, name="home"), home.html {% extends 'main.html' %} {% block content %} <h2>API</h2> <p>Your email is <strong>{{ email }}</strong>, and password <strong>{{ password }}</strong></p> {% endblock %} -
How to reload html src of an image in django
My Django app import an image from the media_url and then it goes to the next page and shows the image and goes back to first page then a new image imported and the old image is removed. The problem is that at the first loop everything is good, in the second loop, it appears that html shows the old image not the new one. how can I apply a reloading in html. here is part of the code: settings.py: MEDIA_ROOT = 'media//' # I test the MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = 'media//' views.py: def scraping(request): .... template_name = "scraping.html" response2 = {'media_root': Config.MEDIA_ROOT, 'media_url': Config.MEDIA_URL} return render(request, template_name, response2) scraping.html <img src='{{media_url}}/pic.jpg//'> # I also tried {{media_url}}pic.jpg {{media_url}}/pic.jpg/ {{media_url}}//pic.jpg//