Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'Response' object has no attribute 'label' drf-yasg
I am integrating drf-yasq swagger for the first time, Sorry! if my question is silly. I read the doc from here https://drf-yasg.readthedocs.io/en/stable/readme.html and followed the instructions and end up with AttributeError: 'Response' object has no attribute 'label' drf-yasg. original code is from https://drf-yasg.readthedocs.io/en/stable/readme.html and what I have written is mentioned below: Terminal: Internal Server Error: /swagger/ Traceback (most recent call last): File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site- packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site- packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site- packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site- packages/django/views/decorators/csrf.py", line 54, in wrapped_view r . eturn view_func(*args, **kwargs) File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site- packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site- packages/rest_framework/views.py", line 497, in dispatch response = self.handle_exception(exc) File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site- packages/rest_framework/views.py", line 457, in handle_exception self.raise_uncaught_exception(exc) File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site- packages/rest_framework/views.py", line 468, in raise_uncaught_exception raise exc File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site- packages/rest_framework/views.py", line 494, in dispatch response = handler(request, *args, **kwargs) File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site- packages/drf_yasg/views.py", line 94, in get schema = generator.get_schema(request, self.public) File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site- packages/drf_yasg/generators.py", line 254, in get_schema paths, prefix = self.get_paths(endpoints, components, request, public) File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site- packages/drf_yasg/generators.py", line 412, in get_paths operation = self.get_operation(view, path, prefix, method, components, request) File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site- packages/drf_yasg/generators.py", line … -
Im on ubuntu 18.04 Lts
I am new to Django .while trying to import Django.i,m getting this message"import-im6.q16: not authorized `django' @ error/constitute.c/WriteImage/1037." why it is happening? -
How to get id from list in dictionary in the serializer django
CHOICE_FIELD_SET = { 'dependent': [ {'id': 1, 'name': "Spouse"}, {'id': 2, 'name': "Children"}, {'id': 3, 'name': "Parents"} ] } This is my constant.py @staticmethod def validate_dependent_type(dependent_type): if dependent_type > util_constants.CHOICE_FIELD_SET['dependent'].extend('id'): raise serializers.ValidationError("Dependent can be of three types only") return dependent_type this is my serializer.py how to validate up to id 3 only hope you understand the question if not please ask in comment -
502 Bad Gateway nginx/1.14.0 (Ubuntu) Django
Well I've depoloyed my Django application on DigitalOcean, and used domain which I bought. Now instead of default application page it shows 502 Bad Gateway nginx/1.14.0 (Ubuntu). And nginx errors log returns such error: *4 connect() to unix:/home/username/project.sock failed (111: Connection refused) while connecting to upstream, client: 82.194.22.116, server: challenge.com, request: "GET / HTTP/1.1", upstream: "http://unix:/home/username/project.sock:/", host: "challenge.com" my nginx configurations: server { listen 80; server_name challenge.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/username; } location / { include proxy_params; proxy_pass http://unix:/home/username/ccproject.sock; proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $server_name; } } my settings in ``settings.py```: ALLOWED_HOSTS = ['64.225.1.249', 'challenge.com'] And my socket file is in /home/username/ -
Django: i18n (translations) doesn't work for en-us, but works for bg?
locale/bg/LC_MESSAGES/django.po: #: .\users\templates\account\login.html:44 msgid "Sign In" msgstr "asdfbg" locale/en-us/LC_MESSAGES/django.po: #: .\users\templates\account\login.html:44 msgid "Sign In" msgstr "asdfen" Usage: {% trans "Sign In" %} So.. if LANGUAGE_CODE in settings.py is set to: LANGUAGE_CODE = 'bg' text is 'asdfbg' but if LANGUAGE_CODE is set to: LANGUAGE_CODE = 'en-us' it shows 'Sign in' instead of 'asdfen' Where am I wrong ? -
What does the save() method of form actually do?
I am watching a django tutorial and in it this code is used: class UserFormView(View): form_class=UserForm def post(self:request): form=self.form_class(request.POST) if form.is_valid(): user=form.save() username=form.cleaned_data('username') password=form.cleaned_data('password') user.set_password(password) user.save() In the tutorial it is said that the form.save() command stores the field data to the shell, which i find incredibly misleading. Shouldn't the save command save the data to a user object in the database? Next they use set_password to save the password value, what does set_password do? Does it hash the password input? Finally the user details are persisted to the database by calling save() on user. But how does django know which model user belongs too? Is that information also acquired when you call form.save() and assign the result to user ? Thank you -
Django's get_current_language strange behavior
I want to set the lang attribute in my html tag to the current locale's language based on the language defined in my settings.py. I don't use the LocaleMiddleware and the user can not choose the language. (I have different domain's for the same page. If someone want's to see the website in a different language, the user has to go to a different website ) settings.py LANGUAGE_CODE = 'pl-PL' USE_I18N = True USE_L10N = True LANGUAGES = [ ('en', 'English'), ('de', 'German'), ('pl', 'Polish'), ('ru', 'Russian'), ('uk', 'Ukrainian'), ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'pipeline.middleware.MinifyHTMLMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.contrib.redirects.middleware.RedirectFallbackMiddleware', ] Django version Django==2.0.9 Template {% load i18n %} {% get_current_language as LANGUAGE_CODE %} {% get_language_info for LANGUAGE_CODE as lang %} <!DOCTYPE html> <html lang="{{ LANGUAGE_CODE }}"> Output If I refresh the page without interacting I got sometimes: pl pl-pl pl-PL Why is that happening? -
Django GraphQL returns null
I have a Django GraphQL app (graphene_django) running with djongo (mongoDB). When I try to list all twitter queries (with GraphiQL), it returns null data : My query : query { allTwitterQueries { id, keyword } } Returns : { "data": { "allTwitterQueries": null } } Here are my Django files : untitled/schema.py import untitled.api.schema import graphene from graphene_django.debug import DjangoDebug class Query( untitled.api.schema.Query, graphene.ObjectType, ): debug = graphene.Field(DjangoDebug, name="_debug") schema = graphene.Schema(query=Query) untitled/api/models.py from django.db import models from django.contrib.auth.models import User class TwitterQuery(models.Model): user_key = models.ForeignKey(User, related_name="created_by", on_delete=models.CASCADE, default=0) keyword = models.TextField(default="null") active = models.BooleanField(null=True) created_at = models.BigIntegerField(default=0) updated_at = models.BigIntegerField(default=0) count = models.IntegerField(default=0) def __str__(self): return self.keyword untitled/api/schema.py import graphene from graphene_django.types import DjangoObjectType from untitled.api.models import TwitterQuery class TwitterQueryType(DjangoObjectType): class Meta: model = TwitterQuery class Query(object): twitter_query = graphene.Field(TwitterQueryType, id=graphene.Int(), keyword=graphene.String(), active=graphene.Boolean()) all_twitter_queries = graphene.List(TwitterQueryType) def fetch_twitter_queries(self, context): return TwitterQuery.objects.all() def fetch_twitter_query(self, context, user_id=None, active=None): if user_id is not None: return TwitterQuery.objects.get(user_id=user_id) if active is not None: return TwitterQuery.objects.get(active=active) return None I have one item in my mongoDB instance : {"_id":{"$oid":"5df20401d4e39b1e89223b15"}, "id":{"$numberInt":"1"}, "user_key_id":{"$numberInt":"1"}, "keyword":"greve", "active":true, "created_at":{"$numberLong":"1575846000000"}, "updated_at":{"$numberLong":"1575846000000"}, "count":{"$numberInt":"0"}} -
Django: pass 'choices' from another database to a MultipleChoiceField
I have a model which has a field that is supposed to be a multi select. I have created a ModelForm for this. In this, I query another database to obtain the possible options a user should be able to choose from. class CollaborationForm(forms.ModelForm): cursor = connections['diseases'].cursor() cursor.execute('select some_column from some_table') all_cuis = cursor.fetchall() cui = forms.MultipleChoiceField(choices=all_cuis, help_text='Relevant CUI, can select more than one') class Meta: model = Collaboration fields = '__all__' MultipleChoiceField only takes a tuple as choices argument. It just so happens that this is exactly what cursor.fetchall() returns. The only issue is that this tuple looks something like this: (('value1',), ('value2',),...)) Since there is no second value in the tuple django throws an error: not enough values to unpack (expected 2, got 1) A tuple is supposed to be immutable, so I feel like somehow adding the same value again to make the error go away is very hacky. On the other hand, making the tuple into a list, and then into a tuple again also seems wrong. Is there a better approach for this? -
Django dropdown error even value is selected
Hello Really having hard time, to figure out why form.is_valid() showing false. Here is the code: MODEL class Config(ValidateOnSaveMixin, models.Model): dcsubnet = models.ForeignKey(Add_Site, on_delete=models.CASCADE, null=True) dcurl = models.CharField(max_length=35, default='') dcsvrip = models.GenericIPAddressField(protocol='IPv4', default='', unique=True) FORM: class GenForm(forms.ModelForm): dc_dcnmurl = forms.ModelChoiceField(queryset=Add_Site.objects.order_by('dcnmURL').values_list('dcnmURL', flat=True).distinct()) dcsvrip = forms.ModelChoiceField(queryset=Add_Site.objects.order_by('dcIP').values_list('dcIP', flat=True).distinct()) dcsubnet = forms.ModelChoiceField(queryset=Add_Site.objects.order_by('subnet').values_list('subnet', flat=True).distinct()) class Meta: model = Config fields = '__all__' field_classes = { 'json_field': JSONFormField, } VIEW: def dc_config(request): form = GenForm(request.POST or None) if request.method == 'POST': print("FORM is VALID: {}".format(form.is_valid())) # Have we been provided with a valid form? if form.is_valid(): task = form.save(commit=False) messages.success(request, 'Successfully stored data into database.') return render(request, template_name, {'form': form }) else: pprint(form.errors) # The supplied form contained errors - just print them to the terminal. messages.error(request, form.errors) HTML: <form id="config" role=form method="POST" class="post-form" action="config">{% csrf_token %} <div name="dcsubnet" class="dropdown" id="dropdownselection" required> {{ form.subnet }</div> <div name="dcnmurl" class="dropdown" id="dropdownselection" required> {{ form.dcurl }} </div> <div name="dcnm_server_ip" class="dropdown" id="dropdownselection" required>{{ form.dcsrvip }}</div> </form> Keep getting error that form is not valid. FORM is VALID: False {'dcurl': ['Select a valid choice. That choice is not one of the available choices.'], 'dcsrvip': ['Select a valid choice. That choice is not one of the available choices.'], 'dcsubnet': ['Select a valid … -
Unable to get Django to update data in model tables
I have been trying to use Advanced Python Scheduler, with my Django application in order to periodically run my script to update my database. My Script (thought process: since the titles are always unique we can use the titles to match): from main.script import get_anime_info from main.models import AnimeInfo anime_list = get_anime_info() database = list(AnimeInfo.objects.values()) real_title = [] data_title = [] def update_database(): for anime in anime_list: real_title.append(anime["title"]) for data in database: data_title.append(data["title"]) if len(data_title) == 0: #if database is currently empty, save all data from api for t in real_title: missing = next(item for item in anime_list if item["title"] == t) a = AnimeInfo(title=missing["title"], latest_ep_num=missing["latest_ep_num"],ld=missing["ld"],sd=missing["sd"],hd=missing["hd"],fhd=missing["fhd"]) a.save() elif anime_list is not None: #test if api fails try: for t in real_title: if t in data_title: #testing if the titles in the database and from the api match a = AnimeInfo.objects.get(title=t) b = next(item for item in anime_list if item["title"] == t) a.latest_ep_num = b["latest_ep_num"] a.ld = b["ld"] a.sd = b["sd"] a.hd = b["hd"] a.fhd = b["fhd"] a.save(update_fields = ['latest_ep_num','ld','sd','hd','fhd'], force_update=True) else: #testing if there are any missing titles from the api that is not in the database missing = next(item for item in anime_list if item["title"] == t) a = … -
Django Rest Framework Seralize duration filed with custom datatype
I have a model and that is with django DurationField() class Elpased(models.Model): total_duration = models.DurationField( default=30 ) and this is my serializer, class ElapsedSerializer(ModelSerializer): class Meta: model = Elapsed fields = '__all__' I am getting data in response ln this pattern: it menas 2 minutes "total_duration": "00:02:00", It means 25 second "total_duration": "00:00:25", But I dont like this, I want to get the data in second, like if there "total_duration": "00:02:00", it should be like this "total_duration": "120", if there is "total_duration": "00:00:25",, it should like this: "total_duration": "25", Can anyone help to achieve this? -
try to run recursion function in python but it will retun non for v1 and v2 [duplicate]
This question already has an answer here: Recursive function returning none in Python [duplicate] 2 answers v1 = ['hi', 'hello', 'this', 'that', 'is', 'of'] v2 = {"Hamza": 1, "Kashif": 2, "Ali": 3} v3 = "I love pakistan." def rec(value): if isinstance(value, list): for i in value: rec(i) elif isinstance(value, dict): for k, v in value.items(): rec(k) else: return str(value).upper() print(rec(v1)) print(rec(v2)) print(rec(v3)) kindly solve this problem because i am getting None when call V! and V2 -
JSONDcode Error during POST request from AngularJS
Angular Code $scope.DMbasedHttp=function(){ var dt={ "dnm":$scope.ddsel }; dn=angular.toJson(dt); dn1=JSON.stringify(dt); $scope.unkm='http://127.0.0.1:8000/cs90a/'; $http({ method: "POST", url : $scope.unkm, data :dt, headers: {'Content-Type': 'application/json'} }).then(function(response){ alert('Back === back'); $scope.data=response.data; $window.location.href = '/Staff.html'; }); } enter code here post_data = request_body.decode(encoding='utf-8') post_data1=json.loads(post_data) File "C:\Murali TP Backup\JAVA\workspace\vasuproj\vasuproj\vasu` app\views.py", line 71, in Empview post_data1=json.loads(post_data) File "C:\Python 36\lib\site-packages\simplejson__init__.py", line 525, in loads return _enter code heredefault_decoder.decodeenter code here(s) File "C:\Python 36\lib\site-packages\simplejson\decoder.py", line 370, in decode obj, end = self.raw_decode(s) File "C:\Python 36\lib\site-packages\simplejenter code hereson\decoder.py", line 400, in Rawecode return self.scan_once(s, idx=_w(s, idx).end()) simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0) -
Making a simple web application that allow user to build portfolio by drag and drop images and text boxes
i am a student and i am trying to build a web app with Django/python. The specific functionality of the app is to allow user to build and design their own portfolio. For example: an artist can upload their artworks and drag and drop images or text boxes onto positions of blank pages, he/she can add text to the pages, and the text box would have a bar that allow them to change fonts, color, size, etc... of the text. I have found some JavaScript libraries to handle drag and drop elements but beside than that, i don't really know where to start. Any suggestion, advises? Thank you. -
How to define the Django Model Method?
I have defined the Django model in Models.py, The methods are not working properly in my environment, Models.py class Amazoninv(models.Model): SKU = models.IntegerField() Description = models.CharField(max_length=300) BanggoodID = models.IntegerField() Website = models.CharField(max_length = 250) StockInfo = models.CharField(max_length = 200) Qty = models.IntegerField() Cost = models.IntegerField() promotion_enddate = models.DateTimeField(null=True, blank=True) reorder = models.IntegerField() def __str__(self): return self.Description When I view in django admin, It shows only the objects as Amazoninv object(1), Amazoninv object(2)., It is not showing the description in the Amazoninv def. Will we need to install(pip) anything for methods to run in django? -
How to compare jinja expression in javascript with escape sequences string?
I am working on a django project which uses jinja as a templating language. My problem: I have a li tag inside html: <li onclick="toggle_size_selection('{% if \'/\' in co.2 %}{{ co.1 }}{% else %}{{co.2}}{% endif %}')">Point1</li> It returns me the following error in response when I visit the url: TemplateSyntaxError at /detail-page/ Could not parse the remainder: '\'/\'' from '\'/\'' How to properly write this expression? "toggle_size_selection('{% if \'/\' in co.2 %}{{ co.1 }}{% else %}{{co.2}}{% endif %}')" -
Display an image in django template from model
I have a django model to store some images in django model but when I am trying to show this image it shows the broken image sign instead of the image. Models.py class Uploaded_pod(models.Model): document = models.FileField(upload_to='pods/') lr_connected = models.ForeignKey(DeliveredDocket, on_delete=models.CASCADE, related_name='delivered_pod') Views.py #upload POD def pod_upload (request, pk): lr_object = get_object_or_404(DeliveredDocket, id=pk) print(lr_object) if request.method == 'POST': form = UploadPODform(request.POST, request.FILES) if form.is_valid(): obj = form.save(commit=False) obj.lr_connected = lr_object obj.save() messages.success(request, 'The POD was Uploaded with success!') return redirect('employee:delivered_docket_table') else: form = UploadPODform() form.lr_connected = lr_object return render(request, 'packsapp/employee/model_form_upload.html', {'form': form}) #show pod def list(request,pk): print("function called with pk ",pk) images = Uploaded_pod.objects.filter(lr_connected = pk) return render(request, "packsapp/employee/list.html", {'images': images}) HTML {% extends 'base.html' %} {% block content %} {% for i in images %} <img src="{{ i.image.url }}" width="500px"/> {% endfor %} {% endblock %} Settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') What is it that I am doing wrong? Please Help! -
How to use Django with Svelte?
I know it is possible to just copy index.html generated by Svelte and use it as a template, but I have a few questions: 1- Is there a plugin that eases up the process? 2- Where do I put the CSS and bundle.js files? 3- Is it even advisable to use these two together? Thanks for the responses. -
Django restapi limitate foreign keys
I'm working on a note app where users create their own categories and each note has a foreign key to one of the categories the user owns. The problem that I got is that I don't know how to constrain the users to pick up one of their own categories when submitting a note post, at the moment they can post on other user's categories their notes. this is my model: class Note(models.Model): title = models.CharField(max_length=255) content = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) category = models.ForeignKey('Category', on_delete=models.CASCADE) my serializer: class NoteSerializer(serializers.ModelSerializer): user = PublicUserSerializer(read_only=True) class Meta: model = Note fields = ('id', 'title', 'content' , 'created_at', 'category', 'user') and the view: class NoteView(viewsets.ModelViewSet): queryset = Note.objects.all() serializer_class = NoteSerializer permission_classes = [IsAuthenticated, IsOwnerOrReadOnly] authentication_classes = [SessionAuthentication, JWTAuthentication] # when a category is posted grab the user id who made the request to use it later on as a foreign key def perform_create(self, serializer): serializer.save(user=self.request.user) # return only the user's categories def get_queryset(self): return Note.objects.filter(user=self.request.user).all() -
displaying custom fieldsets field using method in admin django
I have got this model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.EmailField(_("Email"),max_length=150, blank=True, null=True) class Meta: verbose_name = _("UserProfile") verbose_name_plural = _("UserProfiles") def __str__(self): return self.user.username It refers to User using OneToOneField. Now i would like to customize admin.model to display several fields like: user, its first_name from User. So here is Admin.model: @admin.register(Profile) class ProfileAdmin(admin.ModelAdmin): list_display = ['user', 'user_firstname', 'email'] readonly_fields = ('user',) fieldsets = ( ("User", { "fields": ( 'user', 'user_firstname, # <- Why not working? ), }), ("Additional info", { "fields": ( 'email', ), }) ) def user_firstname(self,obj): return obj.user.first_name def user_firstname(self,obj) properly displays user.first_name from base User model however, if i use this method in fieldsets it shows me an error. Why i cant refer to this method in fieldsets to display this field and what is the solution? -
How can I change user id in django?
I'm simply trying to update user id in django view. But got: (1062, "Duplicate entry 'Dave' for key 'username'") views.py from django.contrib.auth.models import User current_user = request.user user = User.objects.get(id=current_user.id) user.id = 8 user.save() It works for username, but crashes with this error for id. I believe updating auth_user table is not good idea. -
Can't add value from other DB on many-to-may field in django
Here's my code a = Approver.objects.create(title = 'Tester') a.save() p = Profile.objects.create(name="Test") p.save() a.users.add(p) I'm getting this error after ValueError: Cannot add "<Profile: TEST>": instance is on database "default", value is on database "profiles_db" Here's my model class Approver(models.Model): title = models.CharField(max_length=255) users = models.ManyToManyField(Profile, blank=True) The Profile model come from another app which connects to a different database. Is it not possible? -
create a dropdown from ajax table in django
I have created a django template in which a table appears when a field is selected. I want to create a dropdown from this ajax table such that I can fill their value in another field. Ajax table: Form fields: What I am trying to do is that when I click on product1 it shows the dropdown of short code. for e.g this list: SS0002 IN063 PL001 PS001 PP001 Here's the Django template: <div class="row product-form-row"> <form method="post" id="MaterialRequestForm" data-product-url="{% url 'employee:ajax_load_rci' %}" onkeyup="fill()" class="col-md-12 proct-form" novalidate> {% csrf_token %} <div class="form-group col-md-4 mb-0 "> {{ form.transaction_type|as_crispy_field }} </div> <div class="form-group col-md-4 mb-0"> {{ form.transaction_date|as_crispy_field }} </div> <div class="form-group col-md-4 mb-0"> {{ form.dispatch_date|as_crispy_field }} </div> <div class="form-group col-md-4 mb-0"> {{ form.receiver_client|as_crispy_field }} </div> <div class="form-group col-md-4 mb-0 "> {{ form.receive_to_warehouse|as_crispy_field }} </div> <div class="form-group col-md-4 mb-0 "> {{ form.transporter_name|as_crispy_field }} </div> <div class="form-group col-md-4 mb-0 "> {{ form.driver_name|as_crispy_field }} </div> <div class="form-group col-md-4 mb-0 "> {{ form.driver_number|as_crispy_field }} </div> <div class="form-group col-md-4 mb-0 "> {{ form.lr_number|as_crispy_field }} </div> <div class="form-group col-md-4 mb-0 "> {{ form.vehicle_number|as_crispy_field }} </div> <div class="form-group col-md-4 mb-0 "> {{ form.freight_charges|as_crispy_field }} </div> <div class="form-group col-md-4 mb-0 "> {{ form.vehicle_type|as_crispy_field }} </div> <div class="form-group col-md-4 mb-0 "> … -
Value error on posting the submit form in django?
I am having a 6 goals in the bootstrap cards and then a form to submit one user can select any number of goals so I wrote my models as the goals model consisting of data and I get that data in html page goals.html and it is working properly but on select that one card i.e the selected goalids should go as a value of hidden input in my form how should I achieve this? class goals(models.Model): id=models.IntegerField(primary_key=True) goal = models.CharField(max_length=50,default='0000000') class users(models.Model): email=models.CharField(max_length=50,default='0000000') password=models.CharField(max_length=50,default='0000000') room = models.ForeignKey(rooms,on_delete=models.CASCADE) goal = models.ManyToManyField(goals) My form template <form action="{% url 'car:user_register' %}" method="POST" > {% csrf_token %} <div class="form-group"> <label for="username">Username</label> <input type="text" name="username" class="form-control" required> </div> <div class="form-group"> <input type="hidden" name="room" id="name" value=""> </div> <div class="form-group"> <input type="number" name="goal" id="name" value="{{j.id}}"> </div> <div class="form-group"> <label for="email">Email</label> <input type="text" name="email" class="form-control" required> </div> <div class="form-group"> <label for="password2">Password</label> <input type="password" name="password" class="form-control" required> </div> <input type="submit" value="Register" class="btn btn-secondary btn-block"> </form> And in views.py def user_register(request): if request.method == 'POST': username=request.POST["username"] email = request.POST['email'] password = request.POST['password'] room = request.POST["room"] goal = request.POST["goal"] user = users(password=password,email=email) user.room = rooms.objects.get(pk=room) user.goal = goals.objects.get(pk=goal) user.save() return render(request,'home.html') And error is