Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Oracle ORA-00942: table or view does not exist
Using direct query (not model) def my_custom_sql(self): with connection.cursor() as cursor: cursor.execute("select name from mydb.products") row = cursor.fetchone() return row settings DATABASES = { 'default': { 'ENGINE':'django.db.backends.oracle', 'NAME':'orcl', 'USER':'username', 'PASSWORD':'password', 'HOST':'1.1.1.1', 'PORT':'1111' } obviously the parameters have been changed When I try to run my_custom_sql I get a 500 page error and the Apache log says DatabaseError: ORA-00942: table or view does not exist mydb and user are different it seems. -
Get CKEditor value using Jquery in django framework
I'm using CkEditor for Django and I have a form with 3 fields, a product code, a subject and a body. The first two fields are normal fields and the body field is a CKEditor field that is being rendered on the template from forms.py. In order to do an ajax call on this data, I need to use Jquery to get the CkEditor content. How to do this? This is my code so far. My template: form action="." method="post"> {{form2.as_p}} {% csrf_token %} <br><button name="form_submit" id="email_submit" type="submit" class="btn btn-primary" value="send_email">Submit</button> </form> My forms: class CustomersWhoBoughtForm(forms.Form): product_code = forms.CharField(required=True, max_length=1000, label='Product Code') subject = forms.CharField(required=True, max_length=1000, label='Email Subject') body = forms.CharField(widget=CKEditorUploadingWidget(config_name='default')) #trying to get value of this field for Ajax Call -
Parsing JSON with key-value-value (django/python)
I am making an RSVP form where the invitee can opt to bring a guest (or 2 or 3). The form has inputs generated x number of times, where x is the # of guests the user sets. So for example, if the user chooses "0" from the dropdown, they're not bringing a guest so the form only has inputs for 1 person (themselves). If they select "1" from the dropdown, the form duplicates all the fields, but there is still just one route/one submit button. The duplicated form fields are identical to the original, so the form has 2 inputs named "name", 2 inputs named "dinner", etc. I get a dictionary when I print request.POST: <QueryDict: {u'restrictions': [u'None', u'Gluten'], u'name': [u'Krista', u'Joel'], u'dinner': [u'chicken', u'fish'], u'csrfmiddlewaretoken': [u'iEjxo6KgLGHZWwvaxEd6I7CUd7GTs89VGpiKwmiCP9xqXKFK096s0vboK4pPQxea']}> In vanilla python I can access the values like so: dictionary['restrictions'][1] which returns "Gluten". But in Django this expression returns 'e' - the letter at index 1 of the key name 'restrictions'. Likewise, for key, val1, val2 print key, val1, val2 returns "too many values to unpack", presumably because it's unpacking the letters in the key name instead of the values. How can I access the values? Alternatively, is there a better … -
Why am I getting an integrity error django?
I am building a django web app with a custom user model. At the end of the sign up process when I submit the form an integrity error occurs. Here is the error: Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: accounts_user.job_history_id This error indicates that the field in the custom user model named job_history cannot be null. However such a field does not even exist. Here is my custom user model: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) username = models.CharField(max_length=40, unique=True) avatar = models.ImageField(blank=True, null=True) date_joined = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username", "password"] def __str__(self): return "@{}".format(self.username) def get_short_name(self): return self.username I have no idea what this error is referring to and why it is occurring. I added the field named job_history at a previous point but have since deleted it and updated the database accordingly. This error only began to occur when I was fiddling around with the Job and User models in order to achieve a field capable of storing the users previously completed jobs. Further details are available in this stackoverflow questions. Why is the integrity error occuring and how do I fix it? -
Django how to open file in FileField
I need to open a file saved in a FileField, create a list with the content of the file and pass it to the template. How can I open the file? I tried with open(stocklist.csv_file.url, "wb") but it gave me a "File not found" error. If I do this: csv_file = stocklist.csv_file.open(mode="rb") csv_file is None. However, there is a file. If I print print("stocklist.csv_file.url: %s" % stocklist.csv_file.url) I do get stocklist.csv_file: https://d391vo1.cloudfront.net/csv_pricechart/...ss7.csv And if I go to the admin, I can download the file. So, how can I open a file saved in a FileField? -
pagination error page is less than 1 in django
i am trying to do pagination. i got error called page is less than 1 from my html... plz help me... this is my view def index(request): searched = False form = SearchForm(request.GET or None) if request.method == "GET" and form.is_valid(): Mother_language = form.cleaned_data['Mother_language'] Nationality = form.cleaned_data['Nationality'] myuser_qs = MyUser.objects.filter(Q(Mother_language__contains=Mother_language)|Q(Nationality__contains=Nationality)) paginator = Paginator( myuser_qs, 3) page = request.GET.get('page') searched = True try: users = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) return render(request, "LanguageExchange/user_list.html",{'Result': users,"searched":searched,}) return render(request, "LanguageExchange/index.html", { "form": form,"searched":searched}) i think my problem is from ?page={{ Result.previous_page_number }} i do not know what to correct here .... this is my user_list.html. {% block body_block %} {% for each_model in Result %} <div class="panel panel-success" style="margin-left:100px;margin-top:100px;width:400px ;float:right"> <div class="panel-heading"> <h3 class="panel-title"style="text-align:center"><strong>USER INFORMATION</strong></h3> </div> <div class="panel-body"> <img src="{{MEDIA_URL}}{{each_model.Profile_image}}"style="width:300px; height:200px; display:block; margin-left:auto;margin-right:auto"> <hr> <div class="alert alert-info" role="alert" style="text-align:center"> <strong>NAME</strong><br> </div> <div style="text-align:center;">{{each_model.username}}</div> <hr> <div class="alert alert-info" role="alert"style="text-align:center"> <strong>Nationality </strong><br></div><div style="text-align:center"> {{each_model.Nationality}}</div> <hr> <div class="alert alert-info" role="alert"style="text-align:center"> <strong> Mother_language </strong> <br></div><div style="text-align:center">{{each_model.Mother_language}}</div> <hr> <div class="alert alert-info" role="alert"style="text-align:center"> <strong> Wish_language </strong> <br></div><div style="text-align:center">{{each_model.Wish_language}}</div> <hr> <div class="alert alert-info" role="alert"style="text-align:center"> <strong> Message_status </strong><br> </div><div style="text-align:center"> {{each_model.message_status}}</div> </div> </div> {% endfor %} <div class="pagination"> <span class="step-links"> {% if Result.has_previous %} <a href="?page={{ … -
django_tables2 ManyToMany Columns
I'm trying to learn Django and web development aspects and have set myself a challenge of writing some 3rd party tools for the popular action RPG, Path of Exile. A key feature of any ARPG is collecting loot items, which may have any number of 'stats', these are represented in the model as a ManyToManyField. I'd like to list a group of items and their stats in table. I know how to do this with HTML tags in the relevant template.html but would like to use django_tables2 if possible, to reduce repetition etc. I've played around a bit and read the documentation and the tables.html template but can't see an obvious way of doing this or find any other posts etc, I'd be grateful for any help or a nudge in the right direction. Here is a mockup of what I'd like the table to look like I'm not too bothered about having cell dividers or not but would like to be able to sort the columns of these many to many aspects. modely.py class Stats(models.Model): name = models.ForeignKey(StatNames, models.DO_NOTHING) min_value = models.IntegerField() max_value = models.IntegerField() class ItemName(models.Model): name = models.CharField(unique=True, max_length=50) i_level = models.SmallIntegerField() min_dmg = models.SmallIntegerField(blank=True, null=True) max_dmg … -
django view to insert into database model?
I need to save some information into the database after a callback but I get an error saying that the column name is not a valid keyword argument. Model: class TempUser(models.Model): TempID = models.IntegerField(max_length=255), TempName = models.CharField(max_length=255), TempAccessToken = models.CharField(max_length=255), TempRefreshToken = models.CharField(max_length=255) and code for the insert in the view: user = TempUser(TempID=getContent['CharacterID'], TempName=getContent['CharacterName'], TempAccessToken=postContent['access_token'], TempRefreshToken=postContent['refresh_token']); user.save() So the error says TempUser is an invalid keyword argument for this function. I can't find anything anywhere that will help fix this. Thanks django version 1.10.6 python 2.7.13 -
django admin fieldsets only show specific choices
I have fieldsets in admin.py as fieldsets = ((None, { 'fields': ('first_name', 'last_name', 'status') }),) where status is status = models.CharField(max_length=11, choices=STATUS, default='good') with choices STATUS = (('good', 'Good'), ('bad', 'Bad'), ('very_bad', 'Very Bad'), ('very_good', 'Very Good')) And I can see in change model admin page status with drop down menu with above 4 options. But is there way to only show 2 options in drop-down menu. e.g. good and bad? -
Display link on template when user is a staff member in Django
I am kind a newbie to Django, and I have a navigation bar in which I need to display a link only when the user is a staff member. The following is my navigation bar: <div id="navbar" class="navbar-collapse collapse" aria-expanded="false" style="height: 1px;"> <ul class="nav navbar-nav navbar-right"> <li><a href="{% url 'pledges:preferences' %}">{% trans 'Preferences' %}</a></li> <li><a href="{% url 'pledges:account' %}">{% trans 'My Account' %}</a></li> {# The following link should be displayed just to staff members #} <li><a href="{% url dashboard %}">{% trans 'Dashboard' %}</a></li> <li><a href="{% url 'pledges:logout' %}">{% trans 'Log Out' %}</a></li> </ul> </div> Any ideas how can I solve this? -
How to prevent user access to media directory while hosting django sites on pythonanywhere
currently these files can be accessed by typing mysite.pythonanywhere/media/example.png in the url. Is there any way to prevent user from reaching this link. -
'tuple' object has no attribute 'get'
I am new to Django framework and I am trying to perform the Django authentication views but i keep on getting this error Internal Server Error: / Traceback (most recent call last): File "C:\Users\Harsley\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py", line 42, in inner response = get_response(request) File "C:\Users\Harsley\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\deprecation.py", line 138, in __call__ response = self.process_response(request, response) File "C:\Users\Harsley\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\middleware\clickjacking.py", line 32, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'tuple' object has no attribute 'get' [21/Mar/2017 20:58:27] "GET / HTTP/1.1" 500 57044 This is my url.py file from django.conf.urls import url from django.contrib.auth import views as auth_views from . import views urlpatterns = [ url(r'^login$', auth_views.login, name='login'), url(r'^logout$', auth_views.logout, name='logout'), url(r'^logout_then_login$', auth_views.logout_then_login, `name='logout_then_login'),` url(r'^$', views.dashboard, name='dashboard'), ] -
ImportError: No module named django.core.wsgi when deploying with nginx
This question asked saverel times. i tried all things but i am unable to solve this error.i am deploying my django app with nginx but getting this error. my wsgi file import os, sys # add the hellodjango project path into the sys.path sys.path.append('/home/ubuntu/webapps/microbird/lib/python2.7/site-packages') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "microbird.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() i am getting this error [uWSGI] getting INI configuration from run_microbird.ini open("./python_plugin.so"): No such file or directory [core/utils.c line 3684] !!! UNABLE to load uWSGI plugin: ./python_plugin.so: cannot open shared object file: No such file or directory !!! *** Starting uWSGI 2.0.14 (64bit) on [Tue Mar 21 19:46:25 2017] *** compiled with version: 4.8.4 on 21 March 2017 14:56:34 os: Linux-3.13.0-108-generic #155-Ubuntu SMP Wed Jan 11 16:58:52 UTC 2017 nodename: ip-172-31-9-49 machine: x86_64 clock source: unix detected number of CPU cores: 1 current working directory: /home/ubuntu/webapps detected binary path: /usr/local/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! chdir() to /home/ubuntu/webapps/microbird your processes number limit is 7861 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) uwsgi socket 0 bound to TCP address 127.0.0.1:3031 fd 3 Python … -
Implementing django template cache in base template
I want to implement caching in a base template: <!DOCTYPE html> <html lang="en"> {% load cache %} {% load app_config %}{% verbose_name 'polls' as app_name %} <head> {% cache head %} <meta charset="UTF-8"> <title>{% block title %}{% endblock %} - {{ app_name }}</title> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'polls/css/style.css' %}" /> {% endcache %} </head> <body> {% cache header %} <h2 id="header"><a href="{% url 'polls:index' %}">{{ app_name }}</a></h2><hr/> {% endcache %} {% block content %}{% endblock %} </body> </html> There are two problems: verbose_name templatetag is always executed. How could I prevent this? the timeout of None, which means that it never expires, is not accepted by the template tag. -
How can I make it so different clients load unique rows each time (non-overlapping), without making user login sessions?
Incoming noob. In case my title makes no sense, I have an app built in Django whose purpose is to be able to allow the user to customize a specific column of a database. Here is the current basic functionality: select 30 distinct rows from table_a. one row at a time, let user edit specific field. after each edit, send that row to table_b, to be retrieved again for final inspection before updating table_a. after the batch of 30 rows is completed and stored in table_b, retrieve them all from table_b for inspection. press the confirm button to update table_b with the edits that were inspected. All of the above works just fine, and isn't the problem. The problem is that after the initial batch selection of 30 rows, another client could also potentially select some (or all) of those 30 rows for their batch. This question isn't about the structure of the app as detailed above, it's about how to integrate keeping clients from working on the same rows under the current app architecture. But if you'd like to tear apart how it's built, please also explain how to do what I'm asking. Especially if that's necessary for what … -
How do I simply take user's first name and last name, store it in a database and greet the user by calling his full name using django?
from django.db import models class Username(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) def __str__(self): return self.first_name+' '+self.last_name I have made models and have settings and all things migrated. I tried searching on web how to do this simple thing but I am getting very detailed answers with stuff I don't want, I just want a simple page that will greet the user with his full name pulled from the database -
Django Polling of Import script - need user status update. Use model? Sessions?
I have an application where a user uploads a file, then there is some processing of those files that I take care of. The process can take minutes, so I want to send regular updates to the user about what is going on. Right now I'm thinking of implementing Ajax polling to a view which renders json. The problem is that I don't currently have a mechanism for that view to grab the status data. For something like a status update, it seems weird to put that into a model for the view to access, but is that the best route? Am I better off going a different route like storing the status data in user sessions? -
django, ManyToManyField in Abstract Class Model, is it impossible?
CODE: class Basemodel(models.Model): set = models.ManyToManyField(User, related_name="setset_set", symmetrical=False, through="Follow") class Meta : abstract = True class Post_1(Basemodel): post1 = models.CharField(max_length=50) class Post_2(Basemodel): post2 = models.CharField(max_length=50) class Follow(models.Model): follower = models.ForeignKey(User, related_name="who_is_allowing",) followee = models.ForeignKey(Basemodel, related_name="who_is_allowed",) created_at = models.DateTimeField(auto_now_add=True,) updated_at = models.DateTimeField(auto_now=True,) def __str__(self): return "%s follows %s at %s" %(self.follower, self.followee, self.updated_at) In that codes, I wanna make a ManyToManyField in abstract class. So i want to make a user can follow Post_1 or Post_2, whatever kind of post it is. And more, i want to check how it goes on Follow Class, which is used in Basemodel - set = models.ManyToManyField - through kwargs Is there no way to make it possible? -
Iterating through json data in django template
I'm having trouble iterating through a JSON inside the django template. My JOSN looks like, { "main_cats": [ { "pk": 1, "model": "BeeForms.maincategory", "fields": { "is_visible": true, "name": "Test Main", "order_by_asc": true, "base_category": 1, "help_text": "", "is_seller_field": false, "position": 10, "show_seller": true, "order_by_type": true } } ], "sub_cats": [ { "pk": 15, "model": "BeeForms.subcategory", "fields": { "regex": "[0-9a-zA-Z]", "library_id": "TextBox", "input_length": 255, "name": "TextBox", "order_by_asc": false, "field_type": "text", "main_category": 1, "is_active": true, "is_visible": true, "help_text": "", "position": 10, "is_required": true, "field_display_type": "input", "order_by_type": true, "has_enumerations": false } }, { "pk": 16, "model": "BeeForms.subcategory", "fields": { "regex": "[A-Za-z0-9]", "library_id": "SelectBox", "input_length": 255, "name": "SelectBox", "order_by_asc": false, "field_type": "", "main_category": 1, "is_active": true, "is_visible": true, "help_text": "", "position": 10, "is_required": false, "field_display_type": "select", "order_by_type": true, "has_enumerations": true } }, { "pk": 18, "model": "BeeForms.subcategory", "fields": { "regex": "[0-9a-zA-Z]", "library_id": "TextArea", "input_length": 255, "name": "TextArea", "order_by_asc": false, "field_type": "varchar", "main_category": 1, "is_active": true, "is_visible": true, "help_text": "", "position": 10, "is_required": false, "field_display_type": "textarea", "order_by_type": true, "has_enumerations": false } }, { "pk": 22, "model": "BeeForms.subcategory", "fields": { "regex": "[A-Za-z0-9]", "library_id": "Checkbox", "input_length": 255, "name": "Checkbox", "order_by_asc": false, "field_type": "", "main_category": 1, "is_active": true, "is_visible": true, "help_text": "", "position": 10, "is_required": false, "field_display_type": "checkbox", "order_by_type": … -
Getting cx_oracle to work on CentOs
this is a remote db not a local installation. export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:'/usr/lib/oracle/12.1/client64/' export ORACLE_HOME='/usr/lib/oracle/12.1/client64/' pip istall cx_Oracle returns Collecting cx_Oracle Using cached cx_Oracle-5.3.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-build-Evoa3e/cx-Oracle/setup.py", line 205, in <module> includeDirs = FindInstantClientRPMInclude(instantClientRPMLib) File "/tmp/pip-build-Evoa3e/cx-Oracle/setup.py", line 148, in FindInstantClientRPMInclude raise DistutilsSetupError("cannot locate Oracle Instant Client " \ distutils.errors.DistutilsSetupError: cannot locate Oracle Instant Client SDK RPM header files I tried the online suggestions of creating a sym link, it doesn't work. The client64 folder is as follows Client64 -bin -lib -sdk -include using: CentOS, Django, Apache -
I need to enable single-sign on using SAML for my Django App. I would like to know the steps to follow?
I am new to Django and SAML, I have a Django app ready but I need to enable single-sign on using SAML. I would like some insights into the steps to follow. Any Help? PS - We are really close to the deadline. -
Django 1.10 Auto_now Error
When updating to Django 1.10, my unit tests throw: ERROR: test_upload_file_requires_login (project_share.tests.test_api.ProjectTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/test/testcases.py", line 209, in __call__ self._pre_setup() File "/usr/local/lib/python2.7/dist-packages/django/test/testcases.py", line 839, in _pre_setup self._fixture_setup() File "/usr/local/lib/python2.7/dist-packages/django/test/testcases.py", line 895, in _fixture_setup **{'verbosity': 0, 'database': db_name}) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 130, in call_command return command.execute(*args, **defaults) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/loaddata.py", line 64, in handle self.loaddata(fixture_labels) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/loaddata.py", line 104, in loaddata self.load_label(fixture_label) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/loaddata.py", line 167, in load_label obj.save(using=self.using) File "/usr/local/lib/python2.7/dist-packages/django/core/serializers/base.py", line 201, in save models.Model.save_base(self.object, using=using, raw=True, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 824, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 908, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 947, in _do_insert using=using, raw=raw) File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 1045, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 1054, in execute_sql cursor.execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) IntegrityError: Problem installing fixture '/vagrant/project_share/fixtures/default.json': Could not load project_share.Project(pk=1): null value in column "when_created" violates not-null constraint DETAIL: Failing row … -
Django rest swagger post parameter
I have integrated swagger with django rest framework, but the swagger docs does not create a input box to post data for post request. Here is my view class snippet,` class TeamViewList(APIView, BaseView): """ Class based view to handle all operations related to Team Model """ logger = logging.getLogger(__name__) def get_serializer(self): return serializers.TeamSerializer def post(self, request): """ To create a new team """ try: urlmapping: urlpatterns = [ url(r'^role/$', rest_views.UserTeamRoleView.as_view(), name='user_team_role'), url(r'^teams/$', rest_views.TeamViewList.as_view(), name='team_list'), url(r'^teams/(?P<name>[_a-zA-Z0-9\-]+)$', rest_views.TeamViewDetail.as_view(), name='team_detail'), ] And my swagger doc generates, There is no way to pass the json payload as input to post request. -
CSRF token missing or incorrect, when sending request across 2 different apps
I am new to django, I am sending a form data from my index.html(1st app 's template) file to accounts app's(another app) views.py index.html - app01/templates <!DOCTYPE html> <html> <head> <title>hello</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <style type="text/css"> body{ background-color: 'lightblue'; } </style> </head> <body> <nav class="navbar navbar-inverse bg-faded"> <a class="navbar-brand" href="#about"> <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2a/Cyno_Small_Logo_(Aug._2015).png/240px-Cyno_Small_Logo_(Aug._2015).png" width="30" height="30" > </a> <div class="col-md-2 bg-warning"><h3>Quizapp</h3></div> <div class="container off col-md-offset-2"> <ul class="nav nav-tabs"> <li><a data-toggle="tab" href="#regtab">New User? Register here!</a></li> <li><a data-toggle="tab" href="#logtab">Already have an account? Login!</a></li> </ul> </nav> <div class="tab-content"> <div id="regtab" class="tab-pane fade text-primary"> {% csrf_token %} {{ rform }} <button id="rbtn" type="button" class="btn btn-primary btn-lg ">Register!</button> </div> <div id="logtab" class="tab-pane fade text-success" data- loading-text="Registering"> {% csrf_token %} {{ lform.as_p }} <button id="lbtn" type="button" class="btn btn-primary btn-lg " data-loading-text="Logging in" >Login!</button> </div> </div> </div> <script type="text/javascript"> $('#rbtn').click(function(){ var form_data = { 'username' : $('#id_username').val(), 'password' : $('#id_password').val(), 'name' : $('#id_name').val() } $.post('/register_data/',form_data,function (data, status){ var dt = JSON.parse(data); var reg_status = dt.data.status; if(reg_status == 'success'){ alert("registered! click Ok to go to home"); window.location = '/'; } else{ alert("check form bro!"); } }); }); </script> </body> </html> views.py - accounts from django.shortcuts import render,redirect … -
Cannot resolve keyword 'user2' into field. Choices are:
I am trying to edit UserProfile model. But I am getting error Cannot resolve keyword 'user2' into field. Choices are: address, age, contact_number, gender, id, profile_photo, user, user_id #forms.py class UserprofileForm(forms.ModelForm): class Meta: model = UserProfile fields = ['profile_photo', 'gender', 'contact_number', 'age', 'address'] #views.py def edit_user(request): if not request.user.is_authenticated(): return render(request, 'service/login.html') else: userdata = UserProfile.objects.all().filter(user = request.user) userd = UserProfile.objects.get(user2 = request.user.pk) form = UserprofileForm(request.POST or None, instance = user2) if form.is_valid(): user1 = form.save(commit = False) user1.user = request.user user1.save() return render(request,'service/user.html', {'userdata' : userdata,}) return render(request,'service/useredit.html', {'form' : form, 'userd' : userd,})