Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
daphne.service failed to boot
Just wondering if anyone could give me a little direction with my daphne.service file. I am struggling with getting this service to boot. When running systemctl status daphne.service, the service active status is being returned as failed. [Unit] Description=WebSocket Daphne Service After=network.target [Service] Type=simple User=root WorkingDirectory=/home/myapp ExecStart=/usr/bin/python3.6 /usr/local/bin/daphne -e ssl:8001:privateKey=/etc/letsencrypt/live/mydomain.com/privkey.pem:certKey=/etc/letsencrypt/live/mydomain.com/fullchain.pem myapp.asgi:application Restart=on-failure [Install] WantedBy=multi-user.target Where it says "mydomain.com" and "myapp", these are just placeholders for whee I have the actual domain and app name configured correctly. I have opened up port 8001 and within the code I have displayed above, I'm trying to pass through my SSL configuration through to Daphne. I'm guessing it must be a file path related issue, but from what I can see, I have the correct PYTHONPATH and path to Daphne. Any suggestions are welcome! Thank you :-) -
Cannot resolve keyword 'created' into field django rest framework
i have follwing structure: class FullTreeAdminUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class AdminFullTreeListView(generics.ListAPIView): queryset = User.objects.all() serializer_class = FullTreeAdminUserSerializer When i query users/all i have following error: Cannot resolve keyword 'created' into field The user model looks like class User(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = models.CharField(max_length=255, unique=True, db_index=True) first_name = models.CharField(max_length=255, blank=True) last_name = models.CharField(max_length=255, blank=True) email = models.EmailField(max_length=255, unique=True, db_index=True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) date_joined = models.DateTimeField(auto_now=True) balance = models.FloatField(default=0.0) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() I cannot figure out where the problem is. I simply wanna get list of all user and i didn't expect such problems. I don't have created filed in my user model -
I have recently shifted from sqlite3 to SQL. What should be the correct SQL option?
I have recently shifted from sqlite3 to SQL and I have a blog website while running migrations I get a warning message "?: (mysql.W002) MariaDB Strict Mode is not set for database connection 'default' HINT: MariaDB's Strict Mode fixes many data integrity problems in MariaDB, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/3.2/ref/databases/#mysql-sql-mode" I have set my SQL mode to transactional, Now I am not getting this warning. Am I using the correct option? What are the other options and when should I use those? -
docker doesn't install package enviirons
I am trying to install a package "environs" in docker using the command docker-compose exec web pipenv install 'environs [django] == 8.0.0', however nothing happens in the terminal and the package is not installed in the container. What is the reason? docker-compose.yml version: '3.8' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db environment: - "DJANGO_SECRET_KEY=django-insecure-c@p4-@$$@#0deu2p5&-59#-1kv&@(ayfu*b+a+wt(i9j5p7&=p3" db: image: postgres:11 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - "POSTGRES_HOST_AUTH_METHOD=trust" volumes: postgres_data: dockerfile FROM python:3.8 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system # Copy project COPY . /code/ -
django authentication using another api
how do I authenticate users using another api that is not built in django, also I need to store the session cookie from that api. Is it possible to avoid django's authentication and use an external api to do so? I just need to send credentials using post method with a cookie and store it throughout the session. Also, what about using model backend? if after the post request I get 200 status code then authenticate user -
How to connect models between two projects with same database in django
How to take models from project 1 to project 2 in django, both projects sharing same database -
NLTK: The nltk messages is showing on the console screen every time I perform the migration
I am working on a django project where I am using nltk library. I have created an virtual environment to work on this project and every time I perform migration it shows nltk messages which it was not showing previously on the console screen and the address given in that too are not from virtual environment. (django-ai) C:\gsData\venv\django-ai\src>python manage.py runserver Watching for file changes with StatReloader Performing system checks... [nltk_data] Downloading package averaged_perceptron_tagger to [nltk_data] C:\Users\pc\AppData\Roaming\nltk_data... [nltk_data] Package averaged_perceptron_tagger is already up-to- [nltk_data] date! [nltk_data] Downloading package punkt to [nltk_data] C:\Users\pc\AppData\Roaming\nltk_data... [nltk_data] Package punkt is already up-to-date! [nltk_data] Downloading package stopwords to [nltk_data] C:\Users\pc\AppData\Roaming\nltk_data... [nltk_data] Package stopwords is already up-to-date! [nltk_data] Downloading package averaged_perceptron_tagger to [nltk_data] C:\Users\pc\AppData\Roaming\nltk_data... [nltk_data] Package averaged_perceptron_tagger is already up-to- [nltk_data] date! [nltk_data] Downloading package punkt to [nltk_data] C:\Users\pc\AppData\Roaming\nltk_data... [nltk_data] Package punkt is already up-to-date! [nltk_data] Downloading package stopwords to [nltk_data] C:\Users\pc\AppData\Roaming\nltk_data... [nltk_data] Package stopwords is already up-to-date! System check identified no issues (0 silenced). June 16, 2021 - 18:53:11 Django version 3.2.4, using settings 'django_ai.settings' Starting development server at http://127.0.0.1:8080/ Quit the server with CTRL-BREAK. -
What is the use of writing custom QuerySet classes in Django
I was going through Django documentation for model managers. I saw that in this section i saw that that model.QuerySet class is overriden by a custom QuerySet class which has two methods which returns the queryset by filtering role='A' or role='E'. class PersonQuerySet(models.QuerySet): def authors(self): return self.filter(role='A') def editors(self): return self.filter(role='E') class PersonManager(models.Manager): def get_queryset(self): return PersonQuerySet(self.model, using=self._db) def authors(self): return self.get_queryset().authors() def editors(self): return self.get_queryset().editors() class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) role = models.CharField(max_length=1, choices=[('A', _('Author')), ('E', _('Editor'))]) people = PersonManager() But I don't understand what was the need of filtering in the QuerySet class when we could have done that in model manager itself like this. class PersonManager(models.manager): def authors(self): return self.filter(role='A') def editors(self): return self.filter(role='E') Please help to understand the difference. Thank you in advance. -
django - get() returned more than one Phones -- it returned 4
I am working on a small api in django. I have 2 models/tables 1st user , 2nd phones _____________ **models.py** _____________ class Users(models.Model): userId = models.AutoField(primary_key=True,default=None) name = models.CharField(max_length=10) status = models.CharField(max_length=10 , default='BLOCKED') address = models.TextField(null=False,default=None) class Meta: db_table = 'users' class Phones(models.Model): phoneId = models.AutoField(primary_key=True,default=None) userId = models.IntegerField(null=False) numbers = models.CharField(max_length = 15, null=True) phonesCountryCode = models.CharField(max_length=5,null=True) class Meta: db_table = 'phones' I have written the code to get data from json object. the json object looks like this ______________ **json input** ______________ { "name": "abc", "status": "ACTIVE", "address": "xyz", "phones": [ { "numbers": { "numbers": "23378", "phonesCountryCode": "+91" } }, { "numbers": { "numbers": "12390", "phonesCountryCode": "+91" } }, { "numbers": { "numbers": "7890", "phonesCountryCode": "+91" } }, { "numbers": { "numbers": "45221", "phonesCountryCode": "+91" } } ] } inserting data into database works fine. but when i want to update the data it is giving me the error I have multiple data in the database that is why getting multiple data error if using get() and if use filter() it gives me error that no attribute _meta. I am not finding any answer a help will be very appreciated. ____________ **views.py** ____________ @api_view(['PUT']) def ListUpdate(request,pk): data … -
GitHub Actions Django Testing errors with ValueError: Port could not be cast to integer value as 'None'
I have a Django and Django REST app, and when I run my unit testing locally, every test runs and passes. However, when I create a GitHub Action to run my unit testing, 6 of my unit tests failure with the following message: File "/opt/hostedtoolcache/Python/3.9.5/x64/lib/python3.9/urllib/parse.py", line 178, in port raise ValueError(message) from None ValueError: Port could not be cast to integer value as 'None' These 6 tests test sending data to my api endpoints. Here is my Action: django-test-lint: runs-on: ubuntu-latest services: postgres: image: postgres:12.3-alpine env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: github_actions ports: - 5432:5432 options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - name: Checkout uses: actions/checkout@v2 - name: Set up Python 3.9 uses: actions/setup-python@v1 with: python-version: 3.9 - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: psycopg2 prerequisites run: sudo apt-get install libpq-dev - name: Run migrations run: python app/manage.py migrate - name: Run tests and lint with coverage run: | cd app coverage erase coverage run manage.py test && flake8 coverage report -m The impression I get, is this happens when I run my tests to test my endpoints using DRF. It's like Github Actions can't … -
Pycharm Pro connection to PostgreSQL database via SSH tunnel doesn't work with Django
I have added a PostgreSQL datasource in Pycharm Pro, which uses a SSH tunnel to access to the database, on a distant server accessible via VPN. I want to access this database in my Django project. The database parameters are the following (the white bar hides the public IP of the distant server) and the SSH parameters like this (my username and the server public IP are hidden too). I use the same credentials in my settings.py file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'rhu4bdd', 'USER': 'rhu4gres', 'PASSWORD': <password>, 'HOST': <public IP>, 'PORT': '5432' } } Django returns this error: django.db.utils.OperationalError: could not connect to server: Connection timed out Is the server running on host "<public IP>" and accepting TCP/IP connections on port 5432? How can I use my Pycharm database connection in my Django project ? Thank you, MB -
Django EMAIL_CONFIG
when the password contains forward slash "/" this function bring error EMAIL_CONFIG = env.email_url('DD_EMAIL_URL', default='smtp://username:xseebds/wdsdff@email-smtp.eu-central-1.amazonaws.com:25') it brings this error ValueError: invalid literal for int() with base 10: 'B******3' ERROR: Service 'nginx' failed to build: The command '/bin/sh -c env DD_SECRET_KEY='.' python3 manage.py collectstatic --noinput && true' returned a non-zero code: 1 I edited in settings.dist.py EMAIL_CONFIG = env.email_url( 'DD_EMAIL_URL', default='smtp://AC@:B3/x***************+9**G@email-smtp.eu-central-1.amazonaws.com:25') -
Reverse for 'new_entry' with arguments '(1,)' not found. 1 pattern(s) tried: ['new_entry/<int:post_id/$']
I am currently working on a tutorial in the "Python Crash course" Book. The tutorial is about creating a "blog" Webapp with Django. The idea is create an app called blogs in the project and a model called BlogPost. The model should have fields like post, text and date_added. Create a superuser for the project, and use the admin site to make a couple of short posts. Make a home page that shows all posts in chronological order. Create a form for making new posts and another for editing existing posts. Fill in your forms to make sure they work. I am currently stuck at editing an existing Entry form and receive an Error, when I run http://127.0.0.1:8000/posts/1/ I have read the answers for questions similar to mine, but the solutions they propose have already been reviewed and it still gives me an error. I do not understand why. If anyone can help me I would really appreciate it. views.py from django.shortcuts import render, redirect from .models import BlogPost, Entry from .forms import BlogPostForm, EntryForm def index(request): """The home page for blog.""" return render(request, 'blogs/index.html') def posts(request): """Show all posts.""" posts = BlogPost.objects.order_by('date_added') context = {'posts': posts} return render(request, 'blogs/posts.html', … -
Why translations do not work in ModelChoiceField?
I am using Django and I have that code : from django.utils.translation import ugettext_lazy as _ from django import forms auth_d = forms.ModelChoiceField( label=_('Water'), ) I wrote the translations in the django.po file and then I typed that compilesmessages and I have not the translation. Could you help me please ? Thank you very much ! -
Possible design schema to avoid concatenating joined query results
I have a permission model in which I have Users, Groups, Resources and Entities. Each user belongs to one or many groups, and each group can access a specific set of resources and entities. To simplify, I chose to deal with resources and actions as a single string, like resourceA.create and resourceB.delete. So I came up with: class User: id = db.Column(db.Integer) name = db.Column(db.String) class Groups: id = db.Column(db.Integer) name = db.Column(db.String) class UserGroups: id = db.Column(db.Integer) group_id = db.Column(db.Integer) user_id = db.Column(db.Integer) class Permissions: id = db.Column(db.Integer) group_id = db.Column(db.Integer) resources = db.Column(JSONB) # List of strings in the format of "resource.action" entities = db.Column(JSONB) # List of strings in the format of "entity" # The permission table would be something like: "master" | ["*"] | ["*"] "admin" | ["resourceA.create", "resourceA.read", "resourceA.delete", "resourceA.update"] | ["entityC", "entityD"] "member" | ["resourceB.create", "resourceB.read", "resourceB.delete"] | ["entityA", "entityB"] This would be pretty straighforward if I had a simple relationship between users and groups, but gets messy if users <> groups is a many-to-many relationships (one user can be a part of many groups). I guess could solve this with a fairly complex query, joins users, roles, permissions, but than I would have … -
Django - Not sure why my form isn't working
I have multiple forms with large numbers of inputs. I'm not seeing any errors but nothing is showing up in my database either. I also don't really understand the whole URL path thing. This is the relevant part of my models.py file: class example_model(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, default=None) datetime = models.DateTimeField(default=timezone.now) boolean = models.BooleanField(default=True, blank=False) dec = models.DecimalField(max_digits = 100, decimal_places = 5, default=1) dec_unit = models.TextChoices('dec_unit', 'cm inches') views file: def submit_form(request): if request.method == 'POST': if request.POST.get('boolean')\ and request.POST.get('dec')\ and request.POST.get('dec_unit')\: data=example_model() data.boolean= request.POST.get('boolean') data.dec= request.POST.get('dec') data.dec_unit= request.POST.get('dec_unit') data.save() context = { 'context': example_model.objects.all() } return render(request, 'MyAppName/page.html', context) urls: urlpatterns = [ path('', views.home, name='MyAppName-home'), path('form/', views.about, name='MyAppName-about'), path('form/submit_form', views.submit_form, name='submit_form') ] Part of the form: <form action="{% url 'MyAppName:submit_form' %}" method="POST" id="main_form" name="main_form"> The name and id of each input in the rest of the html form are all accurate. My Questions: Why is nothing showing up in my sqlite database under example_model? Running example_model.objects.all() in the Django shell returns an empty QuerySet. Why do I need to redirect with the submit_form url extension to submit the form? I would prefer the user could just stay on the same page. Why does my context not … -
i'm trying to convert a .tex file to pdf using python and django anyone can help me with this and django-tex giving error while creating temp folder
enter image description here Please help me i'm stuck badly in this part. -
Django nested url different views
I have two views CollectionView and CatalogView which are both APIView. In my urls I have: urlpatterns = [ url(r'diwata-2-smi', CatalogView.as_view()), path('diwata-2-smi/collection/', StacCollectionView.as_view()), ] However I cannot access diwata-2-smi/collection/, it is pointing me to CatalogView. How can I achieve so that I have the endpoint for CollectionView? -
Having issue in handling multipart form data in django rest framework
I have an addproduct api in which frontend is sending a multipart/formdata in a post axios call. multipart/form-data is used because there is an image field that needs to be sent in arrays. But I got the following error. Category field is required The data is sent like this name: Soap category[0]: 7 category[1]: 23 brand: 7 collection: 11 availability: in_stock warranty: no_warranty service: cash_on_delivery rating: 3 best_seller: true top_rated: true featured: true main_product_image: (binary) merchant: 2 variants[0][product_id]: fgfdg variants[0][price]: 127 variants[0][quantity]: 1 variants[0][color]: red variants[0][size]: M variants[0][variant_availability]: not_available variants[0][variant_image]: (binary) variants[1][product_id]: fgfdg variants[1][price]: 127 variants[1][quantity]: 1 variants[1][color]: red variants[1][size]: M variants[1][variant_availability]: not_available variants[1][variant_image]: (binary) The same issue is with the variants. My models: class Variants(models.Model): product_id = models.CharField(max_length=70, default='OAXWRTZ_12C',blank=True) price = models.DecimalField(decimal_places=2, max_digits=20,default=500) size = models.CharField(max_length=50, choices=SIZE, default='not applicable',blank=True,null=True) color = models.CharField(max_length=70, default="not applicable",blank=True,null=True) variant_image = models.ImageField(upload_to="products/images", blank=True,null=True) thumbnail = ImageSpecField(source='variant_image', processors=[ResizeToFill(100, 50)], format='JPEG', options={'quality': 60}) quantity = models.IntegerField(default=10,blank=True,null=True) # available quantity of given product variant_availability = models.CharField(max_length=70, choices=AVAILABILITY, default='available') class Meta: verbose_name_plural = "Variants" def __str__(self): return self.product_id #Product Model class Product(models.Model): merchant = models.ForeignKey(Seller,on_delete=models.CASCADE,blank=True,null=True) category = models.ManyToManyField(Category, blank=False) sub_category = models.ForeignKey(Subcategory, on_delete=models.CASCADE,blank=True,null=True) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) collection = models.ForeignKey(Collection, on_delete=models.CASCADE) featured = models.BooleanField(default=False) # is product featured? … -
I am not able to pass the url argument to views.py
My urls.py is from django.urls import path from . import views urlpatterns = [ path('registration', views.teacher_registration, name='teacher-registration'), path('list', views.teacher_list, name='teacher-list'), path('profile/<UploadedDetails_FirstName>/', views.teacher_profile, name='teacher-profile'), path('load-upazilla', views.load_upazilla, name='load-upazilla'), ] Views.py is def teacher_profile(request, UploadedDetails_FirstName): UploadedDetails = UploadedPersonalDetails.objects.get(FirstName=UploadedDetails_FirstName) context = { 'UploadedDetails': UploadedDetails } return render(request, 'teacher/teacher-profile.html', context) models.py is class UploadedPersonalDetails(models.Model): FirstName = models.CharField(max_length=45) LastName = models.CharField(max_length=45) PhoneNumber = models.CharField(max_length=11) EmailAddress = models.CharField(max_length=255, unique=True) RoomNumber = models.CharField(max_length=5) SubjectsTaught =models.CharField(max_length=205) def __str__(self): return f'FirstName:{self.FirstName}' And my .html codeis The error i am facing is NoReverseMatch at /teacher/list Reverse for 'teacher-profile' with arguments '('',)' not found. 1 pattern(s) tried: ['teacher/profile/(?P<UploadedDetails_FirstName>[^/]+)/$'] -
How to handle two different forms in one page?
I have multiple forms in my template. When I submit my first form, the second form is also submitted because it does not need a required input field. I want to submit my second form (with id = lead_form ) when user click it's submit button. How can I do that? approval_page.html // The first form <form method="POST" enctype="multipart/form-data"> <!-- Very Important csrf Token --> {% csrf_token %} {{ form.media }} {{ form|crispy }} <input type="hidden" name="form" value="risk" /> <input type="submit" class="btn btn-primary btn-lg" value="Approve"> </form> // The second form <form method="POST" enctype="multipart/form-data" class="lead_form" id="lead_form" > <!-- Very Important csrf Token --> {% csrf_token %} {{ form_approval.media }} {{ form_approval|crispy }} <input type="hidden" name="rank_name" value="{{ waiting.rank.rank_name }}" /> <button type="submit" class="btn btn-success btn-xs"> Submit </button> </form> views.py def approval_page(request, id): current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) pdf = get_object_or_404(Pdf, id=id) .... if request.method == 'POST' and request.POST.get('form') == 'risk': form = PdfRiskForm(request.POST, request.FILES, instance=pdf) if form.is_valid(): this_pdf = form.save() this_pdf.save() else: form = PdfRiskForm() ... form_approval = LeadApprovalForm(request.POST) if request.method == 'POST': if form_approval.is_valid(): lead_approval = form_approval.save() lead_approval.user = request.user lead_approval.approval_id = approval lead_approval.rank = request.POST.get('rank_name', None) lead_approval.save() else: form_approval = LeadApprovalForm() context = { 'form': form, 'form_approval': form_approval .... … -
Can a django application be a client and a provider to different apps?
I have build 2 application using Django and one of them is a client app (in order to login with github credentials using oauth2), and its also the provider for my other django application. Is that gonna create any issues ? I am using OAuth toolkit for provider and python social for client. -
Why do I get "ModuleNotFoundError: No module named 'mysite'", while I have no mysite module at all?
** My wsgi configuration page** import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'finalproject.settings') ## Uncomment the lines below depending on your Django version ###### then, for Django >=1.5: application = get_wsgi_application() ###### or, for older Django <=1.4 import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() My env and packages myenv) 11:40 ~/test (main)$ ls README.md db.sqlite3 finalproject main manage.py media requirements.txt static I don't know what went wrong, because I did everything following documentation. -
How to Select Multiple data from drop down in django form(Field has M2M relation in database)?
I have one many to many field in my model.py class jira(models.Model): Jira_ID = models.CharField(max_length=100, blank=True) Jira_Story = models.CharField(max_length=500) Short_Description = models.CharField(max_length=500) Story_Points = models.CharField(max_length=30) Sprint = models.CharField(max_length=200) DX4C_Object = models.CharField(max_length=500) Developer = models.ManyToManyField(developer) Sandbox = models.ForeignKey(environments, on_delete=models.CASCADE, limit_choices_to={'Mainline': None},blank=True, null=True) def developer_assigned(self): return ",".join([str(p) for p in self.Developer.all()]) here's my admin.py @admin.register(jira) # class ImpExp(ImportExportModelAdmin): # pass class JiraAdmin(admin.ModelAdmin): list_display = ('id', 'Jira_ID' ,'Jira_Story', 'Short_Description', 'Story_Points', 'Sprint','DX4C_Object','Sandbox', 'developer_assigned') here's my form.py class jiraReg(forms.ModelForm): class Meta: model = jira fields = ['Jira_ID', 'Jira_Story', 'Short_Description', 'Story_Points', 'Sprint','DX4C_Object','Developer','Sandbox'] widgets = { 'Jira_ID':forms.TextInput(attrs={'class':'form-control','id':'Jira_ID','readonly':'readonly'}), 'Jira_Story':forms.TextInput(attrs={'class':'form-control','id':'Jira_Story','readonly':'readonly'}), 'Short_Description':forms.TextInput(attrs={'class':'form-control', 'id':'Short_Description','readonly':'readonly'}), 'Story_Points':forms.TextInput(attrs={'class':'form-control', 'id':'Story_Points','readonly':'readonly'}), 'Sprint':forms.TextInput(attrs={'class':'form-control', 'id':'Sprint','readonly':'readonly'}), 'DX4C_Object':forms.TextInput(attrs={'class':'form-control', 'id':'DX4C_Object','readonly':'readonly'}), 'Developer':forms.Select(attrs={'class':'form-control', 'id':'Developer'}), 'Sandbox':forms.Select(attrs={'class':'form-control', 'id':'Sandbox'}), # 'Sandbox':forms.ModelMultipleChoiceField(queryset=jira.objects.all()), # 'Sandbox': SelectMultiple(attrs={'class': 'form-control-sm form-control js-multiple-select', 'multiple':'multiple'}) } here's my view page for edit data using form # update dependency management def update_jiradata(Request,id): if Request.method == 'POST': pi = jira.objects.get(pk=id) fm = jiraReg(Request.POST, instance=pi) if fm.is_valid(): fm.save() fm.save.m2m() fm = jiraReg() return HttpResponseRedirect('/DependencyManagement') else: pi = jira.objects.get(pk=id) fm = jiraReg(instance=pi) jira_story = jira.objects.all() return render(Request, 'hello/EditManagement.html', {'jiraform': fm, 'JIRA': jira_story}) here in my form the developer field i want to select multiple data and update that in table. some one plese help to achieve that? -
import json not working with shell and manage.py Django
I am writing some python scripts for my Django project. And I am running it using manage.py and shell. import json is not working if I am running it with manage.py and sell. But it is working if I try without shell and manage.py I don't know why this is happening. With manage.py and shell: (Not working) python3 manage.py shell < custom_scripts/imports.py Error: NameError: name 'json' is not defined Without manage.py and shell: (Works) python3 custom_scripts/imports.py Code inside the script: import json print(json.loads("{}")) Any thoughts?