Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SESSION_EXPIRE_AT_BROWSER_CLOSE not working
I'm trying to close the session when the user closes the browser or the tab. I saw that SESSION_EXPIRE_AT_BROWSER_CLOSE is supposed to do that. However it doesn't seem to work. I have successfully implemented the session_security plugin (as suggested in this answer). My settings look as follows: SESSION_SAVE_EVERY_REQUEST = True SESSION_EXPIRE_AT_BROWSER_CLOSE = True SESSION_SECURITY_WARN_AFTER = 120 SESSION_SECURITY_EXPIRE_AFTER = 240 I've tried both with SESSION_SAVE_EVERY_REQUEST set to Trueand False, but the session is still open when I relaunch the browser. Any tips? -
cannnot get article to template
hello guys I want to create post list with 2 col mid i upload the picture and you can see my problem exactly. I have to lines of post-left and right side with images but when I'm uploading post on left is only one art and on the right side, there is 4 article and when I want to add the new article it's should be the second on left side column but it's replacing latest article enter image description here my template code {% for post in postlist %} <!-- POST PREVIEW --> <div class="post-preview medium movie-news"> <!-- POST PREVIEW IMG WRAP --> <a href="post-v3.html"> <div class="post-preview-img-wrap"> <!-- POST PREVIEW IMG --> <figure class="post-preview-img liquid"> <img src="{{ post.Post_image.url }}" alt="post-03"> </figure> <!-- POST PREVIEW IMG --> </div> </a> <!-- /POST PREVIEW IMG WRAP --> <!-- TAG ORNAMENT --> <a href="news-v3.html" class="tag-ornament">{{ post.category }}</a> <!-- /TAG ORNAMENT --> <!-- POST PREVIEW TITLE --> <a href="post-v3.html" class="post-preview-title">{{ post.Post_title }} </a> <!-- POST AUTHOR INFO --> <div class="post-author-info-wrap"> <!-- USER AVATAR --> <a href="search-results.html"> <figure class="user-avatar tiny liquid"> <img src="{{ post.Post_image.url }}" alt="user-03"> </figure> </a> <!-- /USER AVATAR --> <p class="post-author-info small light">ავტორი <a href="search-results.html" class="post-author">{{ post.Post_author }}</a> <span class="separator">|</span>{{ post.Post_created_on }}<span … -
I want to run django and php site on one ip and port?
My local ip is 192.168.29.248. And i want to run php site normally when i run 192.168.29.248:8086 and django website as 192.168.29.248:8086/django/.How can I achieve this? My current vhosts.conf is: <VirtualHost *:8086> ServerName localhost ServerAlias localhost DocumentRoot "${INSTALL_DIR}/www" <Directory "${INSTALL_DIR}/www/"> Options +Indexes +Includes +FollowSymLinks +MultiViews AllowOverride All Require all granted </Directory> </VirtualHost> Please help? -
Django Zappa Lambda Deploy "botocore.errorfactory.ResourceNotFoundException"
I am trying to deploy simple django application from zappa (https://romandc.com/zappa-django-guide/) I am getting the following error. Is there any permission issue or some other issue with the dev setup? Traceback (most recent call last): File "e:\personal\envs\py3\lib\site-packages\zappa\cli.py", line 753, in deploy function_name=self.lambda_name) File "e:\personal\envs\py3\lib\site-packages\zappa\core.py", line 1286, in get_lambda_function FunctionName=function_name) File "e:\personal\envs\py3\lib\site-packages\botocore\client.py", line 314, in _api_call return self._make_api_call(operation_name, kwargs) File "e:\personal\envs\py3\lib\site-packages\botocore\client.py", line 612, in _make_api_call raise error_class(parsed_response, operation_name) botocore.errorfactory.ResourceNotFoundException: An error occurred (ResourceNotFoundException) when calling the GetFunction operation: Function not found: arn:aws:lambda:ap-south-1:122866061462:function:frankie-dev During handling of the above exception, another exception occurred: Traceback (most recent call last): File "e:\personal\envs\py3\lib\site-packages\zappa\cli.py", line 2778, in handle sys.exit(cli.handle()) File "e:\personal\envs\py3\lib\site-packages\zappa\cli.py", line 512, in handle self.dispatch_command(self.command, stage) File "e:\personal\envs\py3\lib\site-packages\zappa\cli.py", line 549, in dispatch_command self.deploy(self.vargs['zip']) File "e:\personal\envs\py3\lib\site-packages\zappa\cli.py", line 786, in deploy self.lambda_arn = self.zappa.create_lambda_function(**kwargs) File "e:\personal\envs\py3\lib\site-packages\zappa\core.py", line 1069, in create_lambda_function response = self.lambda_client.create_function(**kwargs) File "e:\personal\envs\py3\lib\site-packages\botocore\client.py", line 314, in _api_call return self._make_api_call(operation_name, kwargs) File "e:\personal\envs\py3\lib\site-packages\botocore\client.py", line 586, in _make_api_call api_params, operation_model, context=request_context) File "e:\personal\envs\py3\lib\site-packages\botocore\client.py", line 641, in _convert_to_request_dict api_params, operation_model) File "e:\personal\envs\py3\lib\site-packages\botocore\validate.py", line 291, in serialize_to_request raise ParamValidationError(report=report.generate_report()) botocore.exceptions.ParamValidationError: Parameter validation failed: Unknown parameter in input: "Layers", must be one of: FunctionName, Runtime, Role, Handler, Code, Description, Timeout, MemorySize, Publish, VpcConfig, DeadLetterConfig, Environment, KMSKeyArn, TracingConfig, Tags -
How to automate the coverage report generation and rendering?
I am trying to automate the coverage report generation such that there would be a URL which when hit the corresponding view should generate the coverage report and render the coverage report. I have done the same via command line operation, such that on giving the command to run coverage tests, it would generate the report and mail the generated report. Can I do the same via a URL where the corresponding view would run the command for coverage report and render it as an HTML?? -
Django weighted query
I have a query in Django which I order by the last updated timestamp and returns me a queryset of Orders which currently returns based on the timestamp a supplier last updated. The query is currently a simple select with ordering Order.objects.filter(fulfilled=False).order_by('updated') Currently I have id, updated, supplier 1 2019-03-03 10:00 ABC 2 2019-03-03 10:00 ABC 3 2019-03-03 10:00 ABC 4 2019-03-03 12:00 DEF 5 2019-03-03 12:00 DEF 6 2019-03-03 12:00 DEF How will I achieve a result that's ordered by updated but also by supplier. id, updated, supplier 1 2019-03-03 10:00 ABC 4 2019-03-03 12:00 DEF 2 2019-03-03 10:00 ABC 5 2019-03-03 12:00 DEF 3 2019-03-03 10:00 ABC 6 2019-03-03 12:00 DEF -
zsh: abort pipenv shell
On attempts to install psycopg2, postgresql, django-Heroku, gunicorn, I am now getting the below error. Unable to successfully run pipenv shell or pipenv install; can't run python manage.py runserver, which means I can't open my project! Appreciate anyone who can reach out with fix for this issue. dyld: Library not loaded: @executable_path/../.Python Referenced from: /usr/local/Cellar/pipenv/2018.11.26_3/libexec/bin/python3.8 Reason: image not found zsh: abort pipenv shell -
Why am I getting IntegrityError at /signup/taxpayer/ NOT NULL constraint failed: accounts_taxpayer.aadhar
from django import forms from .models import User, TaxpayerProfile, OfficialProfile class UserForm(forms.ModelForm): class Meta: model = User fields = ['first_name', 'last_name', 'email'] class TaxpayerProfileForm(forms.ModelForm): class Meta: model = TaxpayerProfile fields = ['aadhar'] class OfficialProfileForm(forms.ModelForm): class Meta: model = OfficialProfile fields = ['aadhar', 'uid'] Above is the forms.py file Below is the views.py file from django.contrib.auth import login from django.shortcuts import redirect, render from django.http import HttpResponse, HttpResponseRedirect from django.views.generic import CreateView from .forms import OfficialProfileForm, TaxpayerProfileForm, UserForm from .models import User def taxpayer_profile_view(request): if request.method == 'POST': user_form = UserForm(request.POST) taxpayer_profile_form = TaxpayerProfileForm(request.POST) if user_form.is_valid() and taxpayer_profile_form.is_valid(): user = user_form.save(commit=False) user.save() user.taxpayer_profile.aadhar = taxpayer_profile_form.cleaned__data.get('aadhar') user.taxpayer_profile.save() return HttpResponseRedirect('/thanks/') else: user_form = UserForm() taxpayer_profile_form = TaxpayerProfileForm() return render(request, 'accounts/taxpayer_profile.html', {'user_form':user_form, 'taxpayer_profile_form':taxpayer_profile_form}) else: user_form = UserForm() taxpayer_profile_form = TaxpayerProfileForm() return render(request, 'accounts/taxpayer_profile.html', {'user_form':user_form, 'taxpayer_profile_form':taxpayer_profile_form}) def official_profile_view(request): if request.method == 'POST': user_form = UserForm(request.POST) official_profile_form = OfficialProfileForm(request.POST) if user_form.is_valid() and official_profile_form.is_valid(): user = user_form.save(commit=False) user.save() user.official_profile.aadhar = official_profile_form.cleaned__data.get('aadhar') user.official_profile.uid = official_profile_form.cleaned__data.get('uid') user.official_profile.save() return HttpResponseRedirect('/thanks/') else: user_form = UserForm() official_profile_form = OfficialProfileForm() return render(request, 'official_profile.html', {'user_form':user_form, 'official_profile_form':official_profile_form}) else: user_form = UserForm() official_profile_form = OfficialProfileForm() return render(request, 'officialr_profile.html', {'user_form':user_form, 'official_profile_form':official_profile_form}) I have included the proper url path in my urls file and the models have fields … -
How to parse data from website at the touch of a button from /admin. Django
I wrote aa simple parser which takes books authors from website and load them to DataBase. But i have some questions: -Where to place it (I gues in models.py)? -How to write it better (I made class, may be it isn't best way)? -How to call it at the touch of a button from /admin? Here it is: class Parsing: def __init__(self, page): self.page = page self.html_doc = urlopen(f'https://www.litmir.me/bs?rs=5%7C1%7C0&o=20&p={self.page}').read() self.soup = BeautifulSoup(self.html_doc) self.cards = self.soup.find_all('div', itemtype='http://schema.org/Book') def get_author(self, card): return card.find('span', itemprop='author').find_all('a')[0].get_text() def load_authors(self): for card in self.cards: Author.objects.create(f'{self.get_author(card)}') -
Django and alwaysdata: internationalization not applied
I developed a Django application that I deployed in tests on alwaysdata The application is easily accessible but internationalization does not apply However, I did 'execute' the internationalization during the deployment in my virtual environnement (/home/mereva/intensetbm-etool) (django-admin makemessages -l fr and django-admin compilesmessages) and I don't have an error message (normal command return) Locally, I have no problem, my site is well translated into French when the web browser is in French ... Deployment on alwaysdata is not trivial ... architecture of my project: /home/mereva/envTbm (virtual environment) /home/mereva/intensetbm-etool (project folder containing manage.py) /home/mereva/intensetbm_static (static file) /home/mereva/intensetbm-etool/intenseTBM_eTool/settings.py (root of the project containing settings.py) /home/mereva/intensetbm-etool/locale (Django translation file) settings.py import os import psycopg2.extensions # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'rqps9azjw7i0@_(qxirwr!@0w3f)$prsky9l7bt8t-(y)_tiuj' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False # ALLOWED_HOSTS = ['127.0.0.1','localhost', '[::1]'] ALLOWED_HOSTS = ['mereva.alwaysdata.net'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'widget_tweaks', 'bootstrap4', 'registration.apps.RegistrationConfig', 'monitor.apps.MonitorConfig', 'randomization.apps.RandomizationConfig', 'parameters.apps.ParametersConfig', 'unblind.apps.UnblindConfig', 'pharmacy.apps.PharmacyConfig', 'export.apps.ExportConfig', 'django_extensions', # 'debug_toolbar', 'partial_date', 'safedelete', 'simple_history', ] … -
Django: settings for tests of a reusable app?
I created a small app in Django and runserver and admin works fine. I wrote some tests which can call with python manage.py test and the tests pass. Now I would like to call one particular test via PyCharm. This fails like this: /home/guettli/x/venv/bin/python /snap/pycharm-community/179/plugins/python-ce/helpers/pycharm/_jb_pytest_runner.py --path /home/guettli/x/xyz/tests.py Launching pytest with arguments /home/guettli/x/xyz/tests.py in /home/guettli/x ============================= test session starts ============================== platform linux -- Python 3.6.9, pytest-5.4.1, py-1.8.1, pluggy-0.13.1 -- cachedir: .pytest_cache rootdir: /home/guettli/x collecting ... xyz/tests.py:None (xyz/tests.py) xyz/tests.py:6: in <module> from . import views xyz/views.py:5: in <module> from xyz.models import Term, SearchLog, GlobalConfig xyz/models.py:1: in <module> from django.contrib.auth.models import User venv/lib/python3.6/site-packages/django/contrib/auth/models.py:2: in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager venv/lib/python3.6/site-packages/django/contrib/auth/base_user.py:47: in <module> class AbstractBaseUser(models.Model): venv/lib/python3.6/site-packages/django/db/models/base.py:107: in __new__ app_config = apps.get_containing_app_config(module) venv/lib/python3.6/site-packages/django/apps/registry.py:252: in get_containing_app_config self.check_apps_ready() venv/lib/python3.6/site-packages/django/apps/registry.py:134: in check_apps_ready settings.INSTALLED_APPS venv/lib/python3.6/site-packages/django/conf/__init__.py:76: in __getattr__ self._setup(name) venv/lib/python3.6/site-packages/django/conf/__init__.py:61: in _setup % (desc, ENVIRONMENT_VARIABLE)) E 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. Assertion failed collected 0 items / 1 error I understand the background: My app xyz is reusable. It does not contain any settings. The app does not know (and should not know) my project. But the settings are in my … -
Call a python function in Django and display the results on the same page
I'm a beginner to django and I'm trying to perform a cipher operation, but what I want to do is whenever I press the cipher button it should compute the logic and display the results on the same page i.e. my homepage. It'd be really great if someone could help me out. This is my html template ''' <h1>PRODUCT CIPHER</h1> <form action=""> <label> Enter Message Here: <input name="message" type="text"><br><br> Enter key for Shift: <input name="shiftKey" type="number"><br><br> Enter key for transpose: <input name="transKey" type="number"><br> For transposition 1->Reverse and 2->Even Odd<br><br> </label> <input type="submit" value="Encrypt" name="Encrypt"><br> <p>{{ encrypted_message }}</p><br> <input type="submit" value="Decrypt" name="Decrypt"> <p>{{ decrypted_message }}</p> </form> Thanks in advance -
How to make Django API with registration and login
I am trying to make an API in Django that returns employee info as JSON only when a user is logged in. I want to make a way for users to register and log in only via a client or via the link, for example: localhost:examplelink/registration_email_username_password... I do not know how to do this without the use of a html form. Is it possible? -
Displaying random items from table
I am trying to display 3 random items from my database in my product page. I have created a function in my models: class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) label = models.ManyToManyField(Label, blank=True) slug = models.SlugField(unique=True) description = models.TextField() def random(self): count = self.aggregate(count=Count('id'))['count'] random_index = randint(0, count - 1) return self.all()[random_index] My views: def random_items(request): random = Item.objects.random() return render(request, "product.html", {'random': random}) and the product page: {% for item in random %} <div class="col-lg-3 col-md-6 mb-4 d-flex align-items-stretch "> <div class="card"> <div class="view overlay "> <img src="{{ item.image.url }} " class="card-img-top"> </div> </div> </div> {% endfor %} I am getting no image, any suggestions? -
Automatic React build for Django server
I know there is probably a simple solution to this but I was not able to find anything. I am using VSCode and have a front end in React and backend in Django, but currently, whenever I make a change in the front end it seems like I need to rebuild everything for the changes to appear in the Django server. Is there any way I can automate this so I don't need to build every small change I make? -
Missing '/' in static path using django and nginx
I'm very new to django and nginx. When hitting /domain/admin The admin page loads but without css. After checking the logs by hitting this command tail -30 /var/log/nginx/error.log output: /usr/local/apps/appname/staticrest_framework/js/prettify-min.js I've found out that / is missing in the staticrest_framework the expected output should be /usr/local/apps/appname/static/rest_framework/js/prettify-min.js Here is my settings.py: STATIC_URL = '/static/' STATIC_ROOT = '/usr/local/apps/appname/static/' nginx config: server { listen 80 default_server; location /static/ { alias /usr/local/apps/appname/static/; } location / { proxy_pass http://127.0.0.1:9000/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; proxy_redirect off; } } Please help, how do I add / in the middle of static and rest_framework path? -
How to change root and itemlist name in XML API in a django view
Am trying to change root and list-items name to fit API requirements. I don't want to change XMLRenderer class in renderer.py because i might use it again, I just want to use view to customize. The following are the Serializer classes, view class and output Serializer class class CategorySerializer(serializers.ModelSerializer): class Meta: model = TypeCategory fields = '__all__' class ZoneSerializer(serializers.ModelSerializer): type = CategorySerializer(many=True, read_only=True) class Meta: model = Type fields = ('TypeDesc', 'type') in view class ZoneLists(APIView): renderer_classes = (JSONRenderer, XMLRenderer) def get(self, request): zone1 = Type.objects.all() serializer = ZoneSerializer(zone1, many=True) return Response(serializer.data) Output <root> <list-item> <TypeDesc>NORMAL</TypeDesc> <type> <list-item> <id>5</id> <Category>Normal</Category> <Type>1</Type> </list-item> </type> </list-item> <list-item> <TypeDesc>ZONES</TypeDesc> <type> <list-item> <id>9</id> <Category>Zone manager</Category> <Type>4</Type> </list-item> <list-item> <id>10</id> <Category>zone officials</Category> <Type>4</Type> </list-item> </type> </list-item> </root> -
Python Multii User Auth
I want to create a project in Python, Django. So I will be the admin. I will allow employer to create their system that allows their employee to login. How would I do so? I cant find any documentation on it. Employer will have to create employee account. -
Using Falcon with Django ORM
I'm trying to compare a few web frameworks (Falcon/FastAPI, etc...), with a single requirement, using Django's ORM as our method to interact with our DB (the reason at the moment isn't relevant). At the moment I'm focusing on Falcon, but I've already encountered a roadblock. I've set up a Django App, for the ORM portion, but every time I'm trying to access a model from the within the Falcon app, I get a OperationalError('no such table: db_customer') error. The table (db_customer) is there, and I can access it via dbshell or from python code that references to my django settings file directly via DJANGO_SETTINGS_MODULE. ** Please ignore logical code errors, this is just a quick and dirty to check viability and performance ** This is my directory tree: enter link description here app - api/ - customer_resource.py - db/ - dal/ - customer_actions.py - migrations/ - apps.py - manage.py - models.py - settings.py - sqlite.db - main.py Here are my files: models.py import json import django django.setup() from django.db.models import Model, BooleanField, CharField, URLField, DateTimeField class Customer(Model): name = CharField(max_length=100, db_index=True) domain = URLField(max_length=255, null=True) join_date = DateTimeField(auto_created=True, auto_now_add=True, null=True) is_active = BooleanField(default=True) def to_dict(self): return { 'id': self.id, 'name': … -
Python Django URL linking problems
I am working on an online school project, so there is classes in the classes there are subjects in the subjects the is a playlist of lessons. I created tow different playlist one for math lessons and one for English lessons, when I am entering the English Playlist I am seeing English and Math lessons in the same playlist, so Django Is showing me all the lessons I created in the tow playlists, thus I made some, OnetoOne, ManytoMany, ForignKeys relations in the database. How to add math lesson to math playlist and English Lesson to English Playlist?? CODE views.py: def playlist(request, classes_id, list_id): theMaterial=get_object_or_404(Material, pk=list_id) classid=get_object_or_404(Class, pk=classes_id) thePlaylist=get_object_or_404(Playlist, pk=list_id) theList=Playlist.objects thelesson=Lesson.objects context={ 'list':thePlaylist, 'Material': theMaterial, 'playlist':theList, 'class':classid, 'lesson':thelesson } return render(request, 'classes/list.html', context) def lesson(request, classes_id, list_id, lesson_id): playlist=get_object_or_404(Lesson, pk=lesson_id) material=get_object_or_404(Playlist, pk=list_id) theClass=get_object_or_404(Class, pk=classes_id) context={ 'material':material, 'list':playlist, 'class':theClass } return render(request, 'classes/lesson.html', context) models.py: class Playlist(models.Model): title=models.CharField(max_length=200, default="") Material= models.OneToOneField(Material, default=1, on_delete=models.SET_DEFAULT) def __str__(self): return self.title class Lesson(models.Model): video=models.FileField(upload_to="videos", default="") title=models.CharField(max_length=200, default="") description=models.TextField( default="" ) thumbnail=models.ImageField(upload_to="images", default="") Playlist=models.ManyToManyField(Playlist) Material=models.ManyToManyField(Material) classes=models.ManyToManyField(Class) def __str__(self): return self.title webpage: <html> <body> {% for lesson in lesson.all %} <li style="margin-left: 20px;"> <a style="font-family: Arial; font-size: 25px;" href="{% url 'lessons' class.id list.id lesson.id %}">{{lesson.title}} </a></li> … -
I got error ModuleNotFound when I try to import a class from another app
I have a django project named 'LibraryManagement' and there are two apps named book and authors. When I try to import the class from 'authors' models.py I got error ModuleNotFoundError: No module named 'LibraryManagement.authors' Code of models.py of 'authors' app from django.db import models class Authors(models.Model): author_name = models.CharField(max_length=100) description = models.TextField(max_length=300) Code of models.py of 'book' app from django.db import models from LibraryManagement.authors.models import Authors class Book(models.Model): book_name = models.CharField(max_length=100) author = models.ForeignKey(Authors) remarks = models.TextField(max_length=300) -
Filter lookup ignores default custom manager
I'm trying to filter entries of a certain model by doing a lookup in a field of it's one-to-many relationship. The problem is that I have a default custom manager overriding the default queryset which is not taken into account when I do the lookup. If I build a query explicitly using that manager, it does use the default queryset and I get the expected results. But when I do a field lookup from another model it does not. It will be easier to understand by checking the example below: class Ingredient(models.Model): name = CharField() gtin = CharField() def __unicode__(self): return self.name class Package(models.Model): ingredient = ForeignKey(Ingredient, related_manager='packages') size = CharField() active = BooleanField() objects = PackageManager() def __unicode__(self): return self.size class PackageManager(models.Manager): def get_queryset(self): return super(PackageManager, self).get_queryset().filter(active=True) and I have the following entries: ingredient = Ingredient.objects.create(name='Egg', gtin='2344234') package_1 = Package.objects.create(ingredient=ingredient, size='1 unit', active=True) package_2 = Package.objects.create(ingredient=ingredient, size='12 units', active=False) If I retrieve the packages through the related manager, I get only the active ones: ingredient.packages.all() <Package: '1 unit'> But if then I do a filter lookup: Ingredient.objects.filter(packages__size='12 units') <Ingredient: 'egg'> So the Package entry that was not active was not excluded from the lookup. I know I could build … -
DRF - how to 'update' the pk after deleting an object?
a beginner here! here's how im using url path (from the DRF tutorials): path('articles/', views.ArticleList.as_view()), path('articles/<int:pk>/', views.ArticleDetail.as_view()) and i noticed that after deleting an 'Article' (this is my model), the pk stays the same. an Example: 1st Article pk = 1, 2nd Article pk = 2, 3rd Acrticle pk = 3 after deleting the 2n Arctile im expecting -- 1st Article pk = 1, 3rd Artcile pk = 2 yet it remains 3rd Artile pk = 3. is there a better way to impleten the url, maybe the pk is not the variable im looking for? or i should update the list somehow? thnkx -
How to add remote debugger with docker in pycharm where there is some custom parameters after docker compose command
i was trying to add remote debugger to python based Geo Spatial Information CMS . They made a docs to run their system properly in debug mode in docker. But there was no clear instruction to add them in a ide's debugger like pycharm. the three commands that deploys and run their system are: docker-compose -f docker-compose.async.yml -f docker-compose.development.yml up docker-compose stop django docker-compose run \ -e DOCKER_ENV=development \ -e IS_CELERY=False \ -e DEBUG=True \ -e GEONODE_LB_HOST_IP=localhost \ -e GEONODE_LB_PORT=80 \ -e SITEURL=http://localhost/ \ -e ALLOWED_HOSTS="['localhost', ]" \ -e GEOSERVER_PUBLIC_LOCATION=http://localhost/geoserver/ \ -e GEOSERVER_WEB_UI_LOCATION=http://localhost/geoserver/ \ --rm --service-ports django python manage.py runserver --settings=geonode.settings 0.0.0.0:8000 This works on command line and successfully run the project. But i was trying to attach a debugger to the container. So i create a configuration in pycharm like this Docker-compose config and another django server configuration with that remote interpreter: django server with remote debugger of docker container But when i want to debug with django server configuration the ide says that Connection to Python debugger failed: Connection to the debugger script at localhost:52662 timed out you can find their docs here: On the top how can i add --rm --service-ports django python manage.py runserver --settings=geonode.settings 0.0.0.0:8000 … -
How to make Django select box option not selectable?
I have made a Django Form using Django Crispy Forms. I used the Foreign Key concept to display dropdowns in my page. I would like the first option of the dropdown ('Choose..') to be shown to the user but he/she must not be able to select it. It is very easy to do with JavaScript but I'm not sure how to do it with Django. My page with the dropdowns I am also attaching the code for my forms.py and models.py. models.py from django.db import models from django import forms class Organization(models.Model): orgname = models.CharField(max_length = 100, blank=True) def __str__(self): return str(self.orgname) class Team(models.Model): teamID = models.AutoField(primary_key=True) teamName = models.CharField(max_length = 100, blank=True) org = models.ForeignKey(Organization, on_delete=models.CASCADE) def __str__(self): return str(self.teamName) class AgileTeam(models.Model): agileTeamID = models.AutoField(primary_key=True) agileTeamName = models.CharField(max_length = 100, blank=True) org = models.ForeignKey(Organization, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE) def __str__(self): return str(self.agileTeamName) class Employee(models.Model): name = models.CharField(max_length=100) assoc_id = models.CharField(max_length=10) username = models.CharField(max_length=50, blank=True) password = models.CharField(max_length=50, blank=True) organization = models.ForeignKey(Organization, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE) agile_team = models.ForeignKey(AgileTeam, on_delete=models.CASCADE) forms.py from django import forms from django.forms import ModelForm from .models import Organization, Team, AgileTeam, Employee class EmployeeForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput(render_value = True)) class Meta: model = Employee …