Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Avoid multiple try catch in python3
I have created my custom exception and placed that in django settings file. I have a created a create api operation.My api takes data as input and calls multiple third party create api's if any one fails it reverts create operation of all third party api's. class InsertionOrderViewset(viewsets.ViewSet): #my api ''' Manages insertion order dsp operations''' def create(self, request, format=None): try: // create api 1 except error as e: return e try: // create api 2 except error as e: // undo api 1 return e try: // create api 3 except error as e: // undo api 1 // undo api 2 return e Is there a way to avoid writing multiple try catch in such rollback scenerios? -
Evaluate escape sequences in QR code generated by django-qr-code
In my project (Django 3.0 python 3.6) I'm using django-qr-code to generate a QR-code from internal data. This QR-code will be used to fill a form in another application. To do so "Tab Key" must be evaluated in the QR-Code. According to the Barcode Reference, the escape sequence for Horizontal Tab is \t. Now, here is the problem Lets say i want to generate a Qr-Code that populates two inputs firstname and lastname, i tried the following code : {% qr_from_text "firstname_value \t lastname_value" size="m" image_format="png" error_correction="L" %} The expected behavior is filling the first input and then the second one, but it only fills the first input with the sequence "firstname_value \t lastname_value", which means the the escape sequence \t is not interpreted correctly . Thanks in advance for your help -
Django problem, code cannot find css and js static files. Somehow I haven't django nginx conf
my problem is [18/Dec/2020 12:56:24] "GET /login/?next=/ HTTP/1.1" 200 6096 [18/Dec/2020 12:56:24] "GET /static/grappelli/stylesheets/screen.css HTTP/1.1" 404 179 [18/Dec/2020 12:56:24] "GET /static/grappelli/jquery/ui/jquery-ui.min.css HTTP/1.1" 404 179 [18/Dec/2020 12:56:24] "GET /static/grappelli/stylesheets/mueller/grid/output.css HTTP/1.1" 404 179 [18/Dec/2020 12:56:24] "GET /static/grappelli/jquery/jquery.min.js HTTP/1.1" 404 179 [18/Dec/2020 12:56:24] "GET /static/grappelli/jquery/jquery-migrate-3.0.1.min.js HTTP/1.1" 404 179 [18/Dec/2020 12:56:24] "GET /static/grappelli/jquery/ui/jquery-ui.min.js HTTP/1.1" 404 179 [18/Dec/2020 12:56:24] "GET /static/grappelli/js/grappelli.min.js HTTP/1.1" 404 179 But with DEBUG = True everything works well. But I want to work without Debug. I saw a similar problem here(stackoverflow) where STATIC_URL = '/static/' conflicted with nginx django, but I couldn't find any django config anywhere in /etc/nginx/. I installed nginx after django, I think this might be a problem. What to do now, how to fix it? Thanks for help. -
Name issue. Can't change the name of the Models in django database
from django.db import models # Create your models here. class Course (models.Model): name = models.CharField(max_length=100) language= models.CharField(max_length=100) price= models.CharField(max_length=100) def __str__(self): return self.name in django database the object dosent change name still named Course object (1) in the list. Why does it not change? def str(self): return self.name what should one do to make django show the courses names? This should be correct. no errors or anything it just simply dosent do what it should. it seems strange. -
Can't create Django superuser
There is no anything in my Django project (just two empty apps and their names in settings.py). The project is taken from git. I need to work on it locally. I worked fine, until I tried to change username to email in user registration. I did there some manipulations (don't remember which exactly, as I am stuck on this problem probably for a week or more). When I try to create superuser, there appears this error: Traceback (most recent call last): File "/home/laptop/WorkProjects/Mindsum/Apps/mindsum_be/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/laptop/WorkProjects/Mindsum/Apps/mindsum_be/env/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 413, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: auth_user The above exception was the direct cause of the following exception: 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 "/home/laptop/WorkProjects/Mindsum/Apps/mindsum_be/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/laptop/WorkProjects/Mindsum/Apps/mindsum_be/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/laptop/WorkProjects/Mindsum/Apps/mindsum_be/env/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/home/laptop/WorkProjects/Mindsum/Apps/mindsum_be/env/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "/home/laptop/WorkProjects/Mindsum/Apps/mindsum_be/env/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/home/laptop/WorkProjects/Mindsum/Apps/mindsum_be/env/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 100, in handle default_username = get_default_username() File "/home/laptop/WorkProjects/Mindsum/Apps/mindsum_be/env/lib/python3.8/site-packages/django/contrib/auth/management/__init__.py", line 140, in get_default_username auth_app.User._default_manager.get(username=default_username) File "/home/laptop/WorkProjects/Mindsum/Apps/mindsum_be/env/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), … -
Downloaded font face in django not working
I am trying to implement the downloaded font face either in the template or either in the css file both are not working. I have downloaded the fonts and store in the structure like this Static folder css (sub folder inside the static folder) --style.css file inside the css folder fonts (sub folder inside the static folder) --ZillaSlab-Regular.ttf file inside the fonts folder this is how implement the font face in django inside the css file @font-face { font-family: 'Zilla Slab', serif; src: local('ZillaSlab'), url("../fonts/ZillaSlab-Regular.ttf") format('truetype'); } body{ font-family: 'Zilla Slab', serif !important; } I have also tried to implement via static block in the template but it is also not working @font-face { font-family: 'Zilla Slab', serif; src: local('ZillaSlab'), url("{% static '/fonts/ZillaSlab-Regular.ttf' %}") format('truetype'); } body{ font-family: 'Zilla Slab', serif !important; } -
Updating specific files with git for django app on heroku
I deployed my django app to heroku and its working well. When I change something in project on local files and want to push to heroku It always push all files and it takes time. > git add templates/post/detail.html > git commit -am "read more" [master 153e38f] read more 2 files changed, 3 insertions(+), 3 deletions(-) > git push heroku master I use these commands. But it's deploying everything: Enumerating objects: 13, done. Counting objects: 100% (13/13), done. Delta compression using up to 8 threads Compressing objects: 100% (7/7), done. Writing objects: 100% (7/7), 695 bytes | 695.00 KiB/s, done. Total 7 (delta 5), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! Python has released a security update! Please consider upgrading to python-3.8.6 remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----> No change in requirements detected, installing from cache remote: -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: -----> $ python manage.py collectstatic --noinput remote: 1392 static files copied to '/tmp/build_57ea00eb/staticfiles', 3734 post-processed. remote: remote: -----> Discovering process types remote: Procfile declares types -> web remote: remote: -----> … -
Users can add a movie and other people, except the creator, can rate it. And remember a user can onlyrate a movie once
Users can add a movie and other people, except the creator, can rate it. And remember a user can only rate a movie once and even after logging in api, my database is not showing please help -
How to delete file in python inside docker container?
The code below is part of my code. In my local machine, everything is fine.However, I deploy my code and inside of docker container,it gives the error "result": "[Errno 13] Permission denied: path". What could be solution to delete in docker container also? I tried os.remove() also,It didn't work. path = "/mypath/" output = path + "myfile.pdf" result_file = open(output, "w+b") pisa_res = pisa.CreatePDF( source_html, dest = result_file) result_file.close() with open(output, "rb") as pdf_file: encoded_string = base64.b64encode(pdf_file.read()) os.system(f"rm -rf {output}") -
How to use mysql-connector mysql adapter with django??/
I cannot use mysqlclient package in the hosting server because it is a shared hosting server and they would not let me have a root privilige!! so I found about the mysql-connector adapter, I guess it is developed by MySQL but I could not find anyone using it to connect to the database, does someone know how to use it?? please help -
A timer button of a Door Lock with Raspberry Pi GPIO in a DJANGO view with multiple users
I want to build a django app in a Raspberry Pi so multiple users can press a button and open a lock connected with Raspberry Pi GPIO. When someone calls for the view in the django app, the door will open for 5 seconds. I tried to use the code below but it cannot work because the door will open for 10 seconds (run the script twice) instead of ~5.1 seconds if the user double tap the button. let alone multiple users may call for the view at the same time. from django.shortcuts import render from django.http import HttpResponse from openlock.openlock import openlockcommand # Create your views here. def opencommand(request): openlockcommand() return HttpResponse("opened") views.py import RPi.GPIO as GPIO import time def openlockcommand(): relay=18 GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(relay,GPIO.OUT) GPIO.output(relay,1) time.sleep(5) GPIO.output(relay,0) GPIO.cleanup() openlock.py Please help.. -
TemplateSyntaxError: Templates and static files
I have components for the website and they all work fine, for example I have a navbar.html and works flawlessly. However, I think the issue begins when I have a static file. I have another component called 'header.html' (which contains a profile picture) and SHOULD have loaded up a header in my index.html file. But it spits 'TemplateSyntaxError' and says that the issue is with the line code '{% static ... %}'. My settings.py seems correct (see below). I also included 'django.contrib.staticfiles' and {% load static %} in the main index.html. This is also the html part: The structure of my project is as such: -myproject --base --myproject --static --staticfiles -
Can I edit cronjobs using my Django application?
I am creating a Django application for school project. I want to schedule jobs (every (work)day on 9:00 and 17:00). I am trying to do it with Celery right now, but I stuck very hard on it, and as the deadline is in sight, I want to use alternative options: just a cronjob. I think just the cronjob works fine, but the user should be able to edit the times of the cronjobs using the Django web application (so not logging in to SSH, edit the crontab manually). Is this possible? Can't find anything about it on the internet. -
how to active a venv in a Django app that created in windows and we want continue in linux?
I know the way that we active it in Linux: source venv/bin/activate and in windows it just venv/Scripts/activate.bat but i have a project that started in windows and both command didnt work Does anyone have a solution? -
Issues with migrating Models in Django after doing inspectdb from an external database
I connected my external postgreSQL database to Django and ran inspect db to import models into my app. While migrating the changes, I am getting the following errors: python manage.py makemigrations 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 "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\prateek.jain\Anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\prateek.jain\OneDrive - XTRACAP FINTECH INDIA PRIVATE LIMITED\Desktop\XtraCap\django_api\api\models.py", line 1092, in <module> class Holidays(models.Model): File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\db\models\base.py", line 320, in __new__ new_class._prepare() File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\db\models\base.py", line 333, in _prepare opts._prepare(cls) File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\db\models\options.py", line 254, in _prepare model.add_to_class('id', auto) File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\db\models\base.py", line 326, in add_to_class value.contribute_to_class(cls, name) File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\db\models\fields\__init__.py", line 2393, in contribute_to_class assert not cls._meta.auto_field, ( AssertionError: Model api.Holidays can't have more than … -
maximum recursion depth exceeded even if i use Depth = 1
I am trying to use Follow system in Django Rest Framework.Here is my code: Models.py class User(AbstractUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.CharField(max_length=255,unique=True) username =models.CharField(max_length=80,unique=True,default='SOME STRING') USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() class Meta: verbose_name = _('user') verbose_name_plural = _('users') class FollowUserModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='follows') profile = models.ForeignKey(User,unique=True,on_delete=models.CASCADE,null=True) created = models.DateTimeField(auto_now=True) Serializers.py class UserSerializer(serializers.ModelSerializer): following_set = serializers.SerializerMethodField() def get_following_set(self, user): return UserSerializer(User.objects.filter(follows__author=user), many=True).data class Meta: model = User depth = 1 fields = ('id','following_set','email','username') Even if i use Depth = 1 in Serializer,i still get this error: RecursionError at /api/users/ maximum recursion depth exceeded solution please? -
Django unable to display the logout template provided
I have the following problem; Im trying to set up user login and logout using the default contrib.auth views but the logout page that is displayed is the default page of django admin while the login page has no problem and displays the support template that I have provided it django-tutorial/urls.py from django.contrib import admin from django.conf.urls.static import static from django.urls import path, include from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('landingpage.urls')), path('articles/', include('articles.urls')), path('accounts/', include('accounts.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) accounts/urls.py from django.urls import path from django.contrib.auth import views as auth_views app_name = 'accounts' urlpatterns = [ path('login/', auth_views.LoginView.as_view(), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('password_change/', auth_views.PasswordChangeView.as_view(), name='password_change'), path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'), path('password_reset/', auth_views.PasswordResetView, name='password_reset'), path('password_reset/done/', auth_views.PasswordResetDoneView, name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] login.html {% extends "landingpage/base.html" %} {% block page_content %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} {% if next %} {% if user.is_authenticated %} <p>Your account doesn't have access to this page. To proceed, please login with an account that has access.</p> {% else %} <p>Please login to see this page.</p> {% endif %} {% endif %} <form method="post" action="{% url 'accounts:login' %}"> … -
Django FormView: Add if record does not exist and update if it does exist
I created a FormView and it works fine if the user executed the process the first time. However when it is executed the second time I get an error that the record already exist. This is expected as the user in the model is unique. How can I overcome this problem so that the current record is overwritten by the form.save if the record already exist. models.py class ttemp_selection(models.Model): select_account = models.ForeignKey(tledger_account, on_delete=models.CASCADE) date_from = models.DateField(default=datetime.today) date_to = models.DateField(default=datetime.today) user = models.ForeignKey(custom_user, on_delete=models.CASCADE, unique=True) def __str__(self): return self.select_account forms.py class Meta: model = ttemp_selection fields = ['select_account', 'date_from', 'date_to', 'user'] def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super(SelectAccountForm, self).__init__(*args, **kwargs) user = self.request.user current_company = user.current_company self.fields['select_account'].queryset = tledger_account.objects.filter( company=current_company, gl_category='Cash and Bank') view.py class sasView(FormView): template_name = 'cashflow/select_account.html' form_class = SelectAccountForm success_url = 'home' def form_valid(self, form): form.save() return super().form_valid(form) def get_form_kwargs(self): kwargs = super(sasView, self).get_form_kwargs() kwargs['request'] = self.request return kwargs I can determine the record by using ttemp_selection.objects.get(user=request.user) I know I can make use of the UpdateView class but that will create a problem when the record does not exist. It will also add an extra step that is unnecessary. Assistance will be appreciated. -
Migrate from multi-table inheritance model to abstract base classes in Django
My current project uses multi-table inheritance models: from django.db import models class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) class Restaurant(Place): serves_hot_dogs = models.BooleanField(default=False) serves_pizza = models.BooleanField(default=False) class Cinema(Place): sells_tickets = models.BooleanField(default=False) sells_popcorn = models.BooleanField(default=False) I want to switch to abstract base classes instead. Since my model is already deployed I need to write some custom migrations to convert the above schema to this one: from django.db import models class AbstractPlace(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) class Meta: abstract = True class Restaurant(Place): serves_hot_dogs = models.BooleanField(default=False) serves_pizza = models.BooleanField(default=False) class Cinema(Place): sells_tickets = models.BooleanField(default=False) sells_popcorn = models.BooleanField(default=False) Does anyone have any advice on the steps to take to achieve this? -
Stock code request application in Django & SQL
I have a material excelfile and it has different type of material. Each category has start specific prefix like AB001 or BC001 I am planning to write a webservice for the request of this material stock codes. But I need to import the my old database and i have stucked how can i implement this? I have created a model in DJANGO like Materials, But i could not solve that if i import the my old excel file, the software how can understand the numbers will be correct. It must be consecutively. Like ( AB001 , AB002, AC001,AC002,AZ001) Thanks in advance! -
How can I connect my existing external PostgreSQL Database to automatically create my Models.py for a Django Rest Framework?
I have an existing PostgreSQL Database and I want to create APIs around it using Django Rest Framework. How do I display the tables in my Database as models in Django to further use them for the API? -
can i used model A field in model B as foregin key and model B field in model A as OnetoOneField in django
model A: field 1 field 2 --> foregin key model B model B: field 1 field 2 --> foregin key model A -
TypeError: unhashable type: 'dict' while annotate
for value in (annotated_qs.values('row', 'col').order_by('row', 'col').annotate(count=Count('row'))): print('---------value--------', value['row'],value['col]) -
How to use django rest framework [closed]
Thanks for your time. I'm a self taught Jr Developer and just re-done the Django rest-framework quick start for the third time. although i'm not beeing able to understand his usability and reasons. As far as i know the great part of a REST Full api is to receive the data as a common data format (ex: JSON, Xml, etc.), to be able to communicate with all type of API's. with the same database. allowing to comunicate with differents kind of OS. ----> Please correct me if i'm wrong <---- I'd like if i'm right and how to comunicate the rest framework system with the front end of the web api, should i use JS? is there any tutorial that you could recommend me to understand the whole picture of how a rest api should work and apply it on Django? -
Run server Django
I am trying to setup Django on my device but I am encountering issues. I am able to install python and setup a virtual environment, but I am unclear as to whether Django is established. I have tried reinstalling both Django and Python, but it does appear that Django is installed. The issue presents itself when I try to run the Django server in a virtual environment (or even not in a virtual environment). I am confronted by the following error: "Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?" Any advice would be gratefully received. Thanks. Screen shot