Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error: Could not resolve URL for hyperlinked relationship using view name "api:products-list"
I use django-rest-framework. I wanna add url field to each product item using HyperlinkedIdentityField in ProductSerializer but it says there is something wrong. I get an error: Could not resolve URL for hyperlinked relationship using view name "api:products-list". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field.I don't even know why it can happen, because I specify correct view_name and it should work fine. Thanks for help! urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('catalog.urls', namespace='blog')), url(r'^api/', include('catalog.api.urls', namespace='api')), ] catalog/api/urls.py urlpatterns = [ url(r'^categories/$', CategoryListAPIView.as_view(), name='categories-list'), url(r'^products/$', ProductListAPIView.as_view(), name='products-list'), url(r'^products/(?P<pk>\d+)/$', ProductDetailAPIView.as_view(), name='product-detail'), url(r'^products/(?P<pk>\d+)/edit/$', ProductUpdateAPIView.as_view(), name='product-update'), url(r'^products/(?P<pk>\d+)/delete/$', ProductDeleteAPIView.as_view(), name='product-delete'), url(r'^categories/(?P<pk>\d+)/$', CategoryDetailAPIView.as_view(), name='category-detail'), url(r'^categories/(?P<pk>\d+)/edit/$', CategoryUpdateAPIView.as_view(), name='category-update'), url(r'^categories/(?P<pk>\d+)/delete/$', CategoryDeleteAPIView.as_view(), name='category-delete') ] catalog/api/serializers.py class ProductSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='api:products-list', lookup_field='pk', ) category = serializers.SerializerMethodField() def get_category(self, obj): return str(obj.title) class Meta: model = Product fields = ( 'url', 'id', 'title', 'details', 'slug', 'category', ) class CategorySerializer(serializers.ModelSerializer): products_count = serializers.IntegerField() class Meta: model = Category fields = ( 'id', 'title', 'slug', 'products_count', ) class CategoryUpdateSerializer(serializers.ModelSerializer): class Meta: model = Category fields = ( 'title', ) class ProductUpdateSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ( 'title', 'details', 'category', ) catalog/api/views.py class CategoryListAPIView(ListAPIView): … -
django apache wsgi issue
i want open django server using apache and mod_wsgi. i wrote down as below sudo apt-get install apache2 sudo apt-get install libapache2-mod-wsgi and create django project and app and i add my bot in setting.py and create virtual environment and using and add below code in seoultech/wsgi.py /django = mydirctory/ seoultech=project/bot =app / import os, sys sys.path.append('/home/django') sys.path.append('/home/django/venv/lib/python2.7/site-packages') from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "seoultech.settings") application = get_wsgi_application() and cd /etc/apache2/site-available/000-default.conf add code WSGIDaemonProcess seoultech python-path=/home/django/seoultech=home/django /venv/lib/python2.7/site-packages <VirtualHost *:80> ServerAdmin webmaster@localhost WSGIScriptAlias / /home/django/seoultech/wsgi.py <Directory /home/django/seoultech> <Files wsgi.py> Require all granted </Files> </Directory </VirtualHost> but sudo apachectl-k start i got error 'AH00526: Syntax error on line 1 of /etc/apache2/sites-enabled /000default.conf:Invalid command 'WSGIDaemonProcess', perhaps misspelled or defined by a module not included in the server configuration Action '-k start' failed.The Apache error log may have more information.' im looking forward to help -
Add view in the buttom of Django modeladmin
I have a blog made with Django where I write posts in markdown. I would like to add a view in the buttom of the admin page for each instance of the class Entry (my blog post class) such that I can get a preview of what the markdown looks like, while I'm writing. Just as you get a preview here on stackoverflow when you create a new post. I already have an admin class extending ModelAdmin: class EntryAdmin(admin.ModelAdmin): list_display = ('title','created') prepopulated_fields = {'slug': ('title',)} Is it possible to modify ModelAdmin further, such that it loads a certain html file (blogpost.html) and shows it in the buttom of the admin page? I made a lame picture to show exactly what i mean: NB: I know there are various tools such as Django admin plus, that allows one to add views to the admin interface, but not for each instance of an object. -
How to use temporary storage for objects in Django?
I have a crawler in Django project which crawls thousands of urls. Crawling is performed every two hours. There are multiple requests per second which can slower the database. This is a parse method from spider: def parse(self, response): httpstatus = response.status url_obj = response.request.meta['url_obj'] xpath = url_obj.xpath elements = response.selector.xpath(xpath + '/text()').extract() ... EXCEPTIONS ... Scan.objects.create(url=url, httpstatus=httpstatus, price=price, valid=True) As you can see, I have to access database after every request (tens in second) but this database is used by users too. Moreover, I can't use these Scan objects in frontend before the whole scanning is done. My idea is to create some kind of intermediary/temporary storage for newly created Scan objects and then, after scanning is done, move them to the main database. How can I do that? Do you have any ideas? -
STATIC_ROOT setting in Django
I am learning Django and have built a sample Django app. It works fine on my computer, but I am having trouble deploying it to Heroku. My root directory has the following structure: My setttings.py file has the following settings for static files: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' When I try to deploy to Heroku, I get the following error message: ImproperlyConfigured:You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path -
Store date in a python generator? vectorized with numpy?
How could I generate a python generator equivalent to start_date = CustomerProfile.objects.filter(user__date_joined__gte=datetime.datetime(2017, 6, 1)).first().user.date_joined end_date = CustomerProfile.objects.last().user.date_joined while start_date < end_date: count = CustomerProfile.objects.filter(user__date_joined__date=start_date).count() test = 'There are {} customers during the day : {}'.format(count, start_date print(test) start_date += datetime.timedelta(1) In fact, instead of printing test, I would like to create generator, even a vector with numpy. I don't want to store them in a list. How could I do such thing? In clear, I want the best powerful tool (generator or numpy) and compatible with django. -
Dynamic dropdown on intermediate page for admin action
I have a model Jar which has a crate attribute -- a ForeignKey to a Crate model. The Crate model has a capacity attribute (the number of jars it can hold) and a jars property (the number of jars it currently holds) which is this line: return self.jar_set.filter(is_active=True).count(). I have an admin action which moves multiple jars to a new crate. It uses an intermediate page to select the destination crate. Right now all crates are listed in the dropdown, but I want to limit the crates listed to only those with room for the number of jars selected. How? Here's the admin action from admin.py: class MoveMultipleJarsForm(forms.Form): # This needs to somehow be restricted to those crates that have room dest = forms.ModelChoiceField(queryset=Crate.objects.all().order_by('number')) def move_multiple_jars(self, request, queryset): form = None if 'apply' in request.POST: form = self.MoveMultipleJarsForm(request.POST) if form.is_valid(): dest = form.cleaned_data['dest'] count = 0 for jar in queryset: jar.crate = dest jar.save() count += 1 plural = '' if count != 1: plural = 's' self.message_user(request, "Successfully moved %d jar%s to %s" % (count, plural, dest)) return HttpResponseRedirect(request.get_full_path()) if not form: form = self.MoveMultipleJarsForm() return render(request, 'admin/move_multiple_jars.djhtml', { 'jars': queryset, 'move_multiple_jars_form': form, }) move_multiple_jars.short_description = "Move multiple jars … -
How to set a remote django develop environment?
I have to set a development environment on a ubuntu machine(16.04). It's django+postgresql+Nginx, I.think I could install all these things together on that machine,but I totally don't have any idea about how to connect it by using pycharm running on my pc, and how to manipulate the database. Is there anyone could tell me how to connect it. This is the first time I have to use a remote machine. By the way, my pc and ubuntu machine are in the same LAN, but there is another person who were asked to write db are not. I hope I could get some suggestions from the community. -
Firebase for Push Notifications only
I want to develop a web application with a database using Django/Grails/Express I want to use Firebase just for sending Push Notifications to an Iphone. Do i need develop the webapplication (including the database) in firebase or can i develop the web application using Django/Grails/Express and use Firebase just for sending Push Notifications? Do all web frameworks (Django/Grails/Express) support Firebase? Will Firebase be free to use in my case? Thank you in advance! -
DRF: "detail": "Authentication credentials were not provided."
I am new to django rest framework and I am not able to figure out why this is happening. I guess the problem lies in this particular file. Please help me figuring out the problem.(If any other details files are required let me know) settings.py import os import datetime # 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/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = ')v(s0wbqw24q--b05=fy=$5pte2zqzihctbp(+lwy8rff)r8qw' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['192.168.43.215', 'localhost'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'api', 'accounts', 'rest_framework.authtoken', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', ] ROOT_URLCONF = 'testapi.urls' AUTH_USER_MODEL = 'accounts.Account' #Restframework permissions REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES':( 'rest_framework.permissions.IsAuthenticated', 'rest_framework.permissions.IsAdminUser', ) } # Default JWT preferences JWT_AUTH = { 'JWT_ENCODE_HANDLER': 'rest_framework_jwt.utils.jwt_encode_handler', 'JWT_DECODE_HANDLER': 'rest_framework_jwt.utils.jwt_decode_handler', 'JWT_PAYLOAD_HANDLER': 'rest_framework_jwt.utils.jwt_payload_handler', 'JWT_PAYLOAD_GET_USER_ID_HANDLER': 'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler', 'JWT_RESPONSE_PAYLOAD_HANDLER': 'rest_framework_jwt.utils.jwt_response_payload_handler', 'JWT_SECRET_KEY': SECRET_KEY, 'JWT_ALGORITHM': 'HS256', 'JWT_VERIFY': True, 'JWT_VERIFY_EXPIRATION': True, 'JWT_LEEWAY': 0, 'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=300), 'JWT_AUDIENCE': None, 'JWT_ISSUER': None, 'JWT_ALLOW_REFRESH': False, 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7), 'JWT_AUTH_HEADER_PREFIX': 'JWT', } TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', … -
Dynamically build AJAX dropdown resets to original state when trying to save with django form?
I my form I have few dropdowns chained between them with AJAX. This is how I a populating them function getleaseterm() { //get a reference to the select element $select = $('#id_leaseterm'); //request the JSON data and parse into the select element var l_id = ($("select[name='lease'] option:selected").attr('value')); //var l_id = 13; l_url = "/api/get_leaseterm/"+l_id+"/"; $.ajax({ url: l_url, dataType:'JSON', success:function(data1){ //clear the current content of the select $select.empty(); $select.append('<option value="-1">Select term </option>'); //iterate over the data and append a select option $.each(data1, function(key, val){ $select.append('<option value="' + val.id + '">' + val.as_char + '</option>'); }) }, }); } And this is the control <select class="select" id="id_leaseterm" name="leaseterm"> <option value="-1" selected="selected">-----</option> </select> It all works , I am changing values in my dropdowns and options of other dropdowns are updated.So I can select the relevant value. The problem is when I Save the for - the form gets not the value that I have put there but the default value that was there before any manipulation of Ajax have been done. Also when I do view source I see in the code is default value and not what was selected from what I have build with AJAX.(Even that on the screen I … -
Media files don't work in template on Django localhost
Trying to set up media locally. In template generated path appears to be correct and looks like this /media/event_img/1058 <div style="height: 201px; background: url('{{ event.image.url }}') no-repeat; background-size: cover;background-color: #091026;"></div> But still no picture is shown(It exists for every item, I checked manually), and if enter http://localhost:8000/media/event_img/1058 I'll just get 404 error, url pattern not found. In settings.py : MEDIA_ROOT = 'files/media/' MEDIA_URL = '/media/' What may be wrong? Where to look for issue? As I understand to the documentation this setup is enough to output media files.. -
Django Model Query
I have the following 2 models: class User(models.Model): user_id = models.IntegerField(null=True) name = models.CharField(max_length=50) class Blog(models.Model): id = models.IntegerField(primary_key=True) user = models.ForeignKey(User, null=True) timestamp = models.DateTimeField() How can I write a Django model query to get a list of objects which has the following formation - [(user_object, number of blog posts of this user), ...] This list is supposed to be in descending order. Basically, I want to obtain a information about how many blog posts a user has written. Incase, 2 users have the same number of blog posts, I want them to be sorted based on the latest timestamp of the blogpost created by them. So, far I've tried the following and remained unsuccessful in my approaches. user = User.objects.all() serializer = UserSerializer(user, many=True) user = list(serializer.data) user_ranks = [(key, len(list(group))) for key, group in groupby(user)] user_ranks = sorted(user_ranks, key=lambda x: x[1], reverse=True) I do not know how to plug in the timestamp comparison into the above mentioned code. Also, is there a better way of achieving this? P.S: Number if entries in User is same as number of entries in Blog -
Query with just the date
In [97]: cust = CustomerProfile.objects.get(pk=100) In [98]: CustomerProfile.objects.filter(user__date_joined=datetime.datetime(2017, 7, 28)) Out[98]: <QuerySet []> In [99]: CustomerProfile.objects.filter(user__date_joined=datetime.datetime(2017, 7, 28, 14, 43, 51, 925548)) Out[99]: <QuerySet [<CustomerProfile: George George's customer profile>]> In [100]: cust Out[100]: <CustomerProfile: George George's customer profile> In [101]: cust.user.date_joined Out[101]: datetime.datetime(2017, 7, 28, 14, 43, 51, 925548) I am not sure why it is not working here just with the date 2017/07/28. Why is it empty with just the date? How could I obtain the last queryset with just the date and not all the stuff datetime.datetime(2017, 7, 28, 14, 43, 51, 925548) ? -
Django, MultiValueDictKeyError, how to solve?
I make like in tutorial, but nothing work, how to solve? if you have some ideas, which can help pls, tell me about it) and again stack ask add more text, what wrong with him? if only i had some text which can explain my head pain , i will be add it but i have no! THIS IS FULL TRACE BACK Traceback (most recent call last): File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\django\utils\datastructures.py", line 83, in __getitem__ list_ = super(MultiValueDict, self).__getitem__(key) KeyError: 'payment_method_nonce' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\src\orders\views.py", line 143, in pay_for_one_product nonce = request.POST["payment_method_nonce"] File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\django\utils\datastructures.py", line 85, in __getitem__ raise MultiValueDictKeyError(repr(key)) django.utils.datastructures.MultiValueDictKeyError: "'payment_method_nonce'" this is view def some_view(request): nonce_from_the_client = request.POST["payment_method_nonce"] amoun_of_pr = get_pr_from_bs.total_price_for_this_good result = braintree.Transaction.sale({ "amount": amoun_of_pr, "payment_method_nonce": nonce_from_the_client, "options": { "submit_for_settlement": True } }) if result.is_success: print("YES THAT'S WORK") else: print("YOU WAS **") return JsonResponse({"Successfully":"added"}) this is html <div id="pay_it_wrapper"> <div id="dropin-container"></div> </div> {% block scripts %} <script src="https://js.braintreegateway.com/web/dropin/1.7.0/js/dropin.min.js"></script> <script> $(document).ready(function(){ var button = document.querySelector('.pay_it'); braintree.dropin.create({ authorization: '{{ … -
how push to heroku non project files?
I have a project deployed on heroku. I then added Multilingal Model with pip install which now exists under my externalLibrairies\myvirtualenv\multigual_model I then changed in a non project file which is externalLibrairies\myvirtualenv\multigual_model\models.py\. The problem is that the project works fine locally, but not on heroku, since I didn't push the exernal file that I have changed. Is there is a way to push to heroku all your files and not just the project files? -
How to use default database in django testing
Now I want to test API using my default database as I need too many data first to mock the request so I don't want to setup test database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'bills_db', 'USER': 'root', 'PASSWORD': '****', } } How can I use it ? -
Relation does not exist error in Django
I know there are many questions about this problem, I looked through the solutions and unfortunately none of them worked for me. I created a new app called "usermanagement", and added a model to the app. After adding the model I added usermanagement to INSTALLED_APPS in settings. Then I ran python manage.py makemigrations, and python manage.py migrate. This all worked fine! The problems start when I try to add a new instance of the model to the database in the Python-Django shell, by using: a = ClubOfficial(name="randomName", email="randomemail@random.com"), and a.save(), I get the following error: django.db.utils.ProgrammingError: relation "usermanagement_clubofficial" does not exist LINE 1: INSERT INTO "usermanagement_clubofficial" ("name", "email") ... Below is the model code: class ClubOfficial(models.Model): name = models.CharField(max_length=254) email = models.EmailField(max_length=254) If it helps, I use postgresql, and have tried restarting the server. The other apps in the program also work perfectly fine, it is just usermanagemenet that has this problem. Does anyone know what could be going wrong? Thank you for your time! -
Should I use Django for simple website?
I have been learning the Django framework for the last few weeks and I need to create a simple website for a dentist. The site just needs to have a few pages with flat data. I was wondering whether using django for this sort of project is good? I am also not sure whether I need any applications for this except a contact form, the site will mostly contain only views and templates. Looking for some advices/recommendations. Thanks in advance, David -
MultiValueDictKeyError with braintree, how to solve WITH MY CODE?
I make like in tutorial, but nothing work, how to solve? I make like in tutorial, but nothing work, how to solve? I make like in tutorial, but nothing work, how to solve? THIS IS FULL TRACE BACK Traceback (most recent call last): File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\django\utils\datastructures.py", line 83, in __getitem__ list_ = super(MultiValueDict, self).__getitem__(key) KeyError: 'payment_method_nonce' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\src\orders\views.py", line 143, in pay_for_one_product nonce = request.POST["payment_method_nonce"] File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\django\utils\datastructures.py", line 85, in __getitem__ raise MultiValueDictKeyError(repr(key)) django.utils.datastructures.MultiValueDictKeyError: "'payment_method_nonce'" this is view def some_view(request): nonce = request.POST["payment_method_nonce"] result = braintree.Transaction.sale({ "amount":get_pr_from_bs.total_price_for_this_good, "payment_method_nonce":nonce }) if result.is_success: print("YES THAT'S WORK") else: print("YOU WAS FUCKED UP") return JsonResponse({"Successfully":"added"}) this is html <div id="pay_it_wrapper"> <form action="/orders/pay_for_one_product/" id="pay_it_form">{% csrf_token %}</form> </div> {% block scripts %} <script src="https://js.braintreegateway.com/v2/braintree.js" ></script> <script> $(document).ready(function(){ braintree.setup("{{ client_token }}", "dropin",{ container: "pay_it_form", paypal:{ singleUse: true, amount: "{{ one_product.total_price_for_this_good }}", currency: 'USD' } }) }) </script> {% endblock scripts %} -
Django messages are not shown if Google Data Saver plugin is used
I hava a simple Python 3.5/Django 1.10.8 app consisting of one main page with one form with submit button (it's test app for catching this bug). On submit the corresponging view redirects back: messages.add_message(request, messages.INFO, "succeed") return HttpResponseRedirect('/') When I open the web page from Chrome with Google data saver plugin disabled (i.e. disable it manually or use incognito mode), everything is fine - after redirect the "succeed" info message is displayed. When I open same page with GDS enabled (i.e. from chrome of any android phone or from desktop chrome with DSE plugin manually enabled) the "succeed" message is not displayed. There is simply no "_messages" in request.GET (I've checked this in developer console)! Setting cache-control to "no-transform" as suggested here does not help. Why GDS clears django messages? How can I fix it? I guess this because it proxifies traffic but it's only the guess and anyway I need a fix/workaround. Thanks! -
Is model cycling ok in Django?
Can't figure out how to get rid of cycle in my ERD (or model) graph. Every user can have multiple products and every product is on multiple pages (urls). I scan these products every day for their description, price etc. I want to store information like when the product has been scanned, how many urls had valid scan, datetime of product scanning (not url) etc. I've created a ProductScanning model which is created when first Url object is being scanned where I store such data. I can use ProductScanning when I want to compute average price of last scans like this: sum([x.price for x in product.productscannings.last().scans]) The problem is that, as you can see there is a cycle in this graph which I should probably avoid. Do you have any ideas? -
What do I get this error : match = date_re.match(value) TypeError: expected string or bytes-like object?
Hello All I am attempting to create a patient model form for a medical database using django. I want to derive age for DOB but I keep getting a type error that I cannot fix. The following is a layout of my algorithm. This is my code : from django.db import models from django.contrib.auth.models import User import datetime from django.utils.timezone import now from Self import settings class Identity_unique(models.Model): NIS_Identity = models.IntegerField(primary_key=True) user = models.ForeignKey(settings.AUTH_USER_MODEL) date = models.DateTimeField(auto_now =True) First_Name = models.CharField(max_length = 100, default =0) Last_Name = models.CharField(max_length = 100, default=now) date_of_birth = models.DateField(max_length=8, default=now) patient_age = models.IntegerField(default=0) def __str__(self): Is_present = date.today() patient_age = Is_present.year - date_of_birth.year if Is_present.month < date_of_birth.month or Is_present.month == date_of_birth.month and Is_present.day < date_of_birth.day: patient_age -= 1 return self.patient_age contact = models.IntegerField() This is my ModelForm : from django import forms from .models import Identity_unique class Identity_form(forms.ModelForm): NIS_Identity = models.IntegerField(primary_key=True) user = models.ForeignKey(settings.AUTH_USER_MODEL) date = models.DateTimeField(auto_now =True) First_Name = models.CharField(max_length = 100, default =0) Last_Name = models.CharField(max_length = 100, default=now) date_of_birth = models.DateField(max_length=8, default=now) patient_age = models.IntegerField(default=0) class Meta: model = Identity_unique fields = ('NIS_Identity','First_Name', 'Last_Name', 'date_of_birth', 'patient_age', 'Contact', ) This is my Template: {% extends 'base.html' %} {% block head%} {%endblock%} {%block body%} … -
Django sql query sql server
I am experiencing a very strange case : When running this query c.execute ('select * from banks_row_data where Record_id=544') test=c.fetchall() The result is None while when running : c.execute ('select * from banks_row_data') test=c.fetchall() The result is the entire table What am i doing wrong? Thanks -
NameError at /accounts/upload_save/ global name 'ContactForm' is not defined
I got an error,NameError at /accounts/upload_save/ global name 'ContactForm' is not defined . I am making photo upload system. Now views.py is like def upload(request, p_id): form = UserImageForm(request.POST or None) d = { 'p_id': p_id, 'form':form, } return render(request, 'registration/accounts/photo.html', d) @csrf_exempt def upload_save(request): photo_id = request.POST.get("p_id", "") if (photo_id): photo_obj = Post.objects.get(id=photo_id) else: photo_obj = Post() files = request.FILES.getlist("files[]") if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): return HttpResponseRedirect('registration/accounts/photo.html') else: photo_obj.image = files[0] photo_obj.image2 = files[1] photo_obj.image3 = files[2] photo_obj.save() photos = Post.objects.all() context = { 'photos': photos, } return render(request, 'registration/accounts/photo.html', context) Traceback says Traceback: File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/Users/xxx/Downloads/KenshinServer/accounts/views.py" in upload_save 120. form = ContactForm(request.POST) Exception Type: NameError at /accounts/upload_save/ Exception Value: global name 'ContactForm' is not defined] Before,I got an index out of range error in files = request.FILES.getlist("files[]"),I can understand why this error happens empty files cause it .So,I tried to use ContactForm and wrote my code by seeing sample code in django document.However,I got this error and I cannot understand …