Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django listview to list only if it receives a true value
my name is Gustavo and I need help, I'm developing an application that generates requests (city hall) I'm using Django 1.11, in my shopping area I have a view using get_context_data to get the objects of my requests and list them. my problem is that there are several sectors and the request will only be listed in the next sector if the previous one approves. in my models.py I have the class Request (Solicitacao) and the class SecretaryApproval (SecretarioAprovacao) that is related to my request. What I need to do is when opening the page he checks all the requests and only lists for me the ones that receive the true value in the variable secretario_aprovacao view.py class Compraslist(LoginRequiredMixin, ListView): model = Solicitacao template_name = 'compraslist.html' def get_context_data(self, **kwargs): context = super(Compraslist, self).get_context_data(**kwargs) context['solicitacoes'] = Solicitacao.objects.all() return context models.py class SecretarioAprovacao(models.Model): secretario_relacionamento = models.ForeignKey(Solicitacao, on_delete=models.CASCADE) secretario_aprovacao_CHOICES = ( (True, 'Sim'), (False, 'Não') ) secretario_aprovacao = models.BooleanField("Aprovar Solicitação?", choices = secretario_aprovacao_CHOICES, default = True, ) class Meta: verbose_name = "Secretario Aprovação" verbose_name_plural = "Secretario Aprovações" thanks for listening. -
django model and csv file zip feature lack
I fixed a lot with your help and I guess we come to last problem; If the line from the csv file not in the my django model database than django mixes up all so that; csv line and django database are no longer going in correct order so all mixed. To prevent this problem I added if queryset count function within the loop to raise an error message or tried also pushing another default value but nothing worked. What you would suggest to prevent this sync problem ? for instance in RFP.objects.filter(FP_Item=query): if RFP.objects.filter(FP_Item=query).count() >= 1: instances.append(instance) else: messages.success(request, "ERROR") For reference the whole code: with open(path, encoding='utf-8') as f: data = csv.reader(f, delimiter='|') for row in data: line = row[0] lines.append(line) query = line for instance in FP.objects.filter(FP_Item=query): if FP.objects.filter(FP_Item=query).count() <= 1: instances.append(instance) else: messages.success(request, "ERROR") pair = zip(lines, instances) context = {'pair': pair, } return render(request, 'check_fp.html', context) -
Django Widget not Loading
I using Django with widgets to get some user input but I can't seem to get it to display even thou the code seems almost identical to examples online. forms.py from django import forms class PickerIDForm(forms.Form): pickeID = forms.NumberInput() views.py def get_id(request): template = loader.get_template('metrics/lance1.html') def get(self, request): form = PickerIDForm() return render(request, 'self.template', {'form': form}) context ={ } return HttpResponse(template.render(context,request)) urls.py from django.urls import path from . import views from . import mark_views app_name = 'metrics' urlpatterns = [ path('', views.index, name='index'), path('test/', views.get_id, name='get_id'), ] test.html {% extends 'base.html' %} {% block content %} <p>User Input</p> <form method = "post" > {% csrf_token %} {{form.as_p}} <button type="submit"> Submit </button> </form> {% endblock %} I'm never directly calling the get function as defined in views.py that to me seems to be a possible source of the input fields not showing up when I load up test.html At what point do you link the disparate parts together? Because it seems I'm missing something. -
django celery how to print or check logging for the task
I have now got django and celery working. but there is no logs print for me to check if the task is working correctly. I am using mac and plan to use celery on production in my ubuntu aws machine. Here is what i do in tasks.py: import string from celery import shared_task import logging @shared_task def send_push_notification_celery(total): logging.debug("send_push_notification_celery") logging.debug("total:%d", total) return "i love you" this is all that gets printed out on celery worker console: [2018-04-12 11:25:08,620: INFO/MainProcess] Received task: myapp.tasks.send_push_notification_celery[322eae85-3ef7-4adb-b3bd-eae90300587b] [2018-04-12 11:25:08,622: INFO/ForkPoolWorker-2] Task myapp.tasks.send_push_notification_celery[322eae85-3ef7-4adb-b3bd-eae90300587b] succeeded in 0.0001755820121616125s: 'i love you' -
Facing issue with "cannot import name models"
My code structure app/admin.py uno.core import models as core_models from app import models class TemplatePageAdmin(admin.ModelAdmin): list_display = ('url', 'template', 'state') list_filter = ('template', 'state') search_fields = ('url', 'template') while am running python manage.py shell am facing issue from uno.core import models as core_models ImportError: cannot import name models thanks in advance -
Django authenticate function that accepts extra fields
That django authenticate function accepts two parameters, eg user = authenticate(username=username, password=password), but I would like to pass in an additional parameter to validate the entry. Is that possible to do so or can the authenticate function be overridden to achieve that? Please advise, thanks. -
Django POST 400 Bad Request
I'm trying to post a message with javascript on a 1.11 django wannabe chat server. I'm rather new to javascript and so I'm posting and getting is rather new to me. If I create a message in the database it appears in the chat box. This makes me believe that this is just a posting error. This is the following error I'm getting: chat.js:13 POST http://127.0.0.1:8000/chat/api/messages/ 400 (Bad Request) send @ jquery-3.2.1.min.js:4 ajax @ jquery-3.2.1.min.js:4 r.(anonymous function) @ jquery-3.2.1.min.js:4 send @ chat.js:13 (anonymous) @ (index):186 dispatch @ jquery-3.2.1.min.js:3 q.handle @ jquery-3.2.1.min.js:3 project's urls.py url(r'^chat/', include("chat.urls",namespace='chat')), chat's urls.py urlpatterns = [ url(r'^$', chat_view, name='chats'), url(r'^(?P<sender>\d+)/(?P<receiver>\d+)/$', message_view, name='chat'), url(r'^api/messages/(?P<sender>\d+)/(?P<receiver>\d+)/$', message_list, name='message-detail'), url(r'^api/messages/$', message_list, name='message-list'), url(r'^api/users/(?P<pk>\d+)/$', user_list, name='user-detail'), url(r'^api/users/$', user_list, name='user-list'), ] java script: //For sending $(function () { scrolltoend(); $('#chat-box').on('submit', function (event) { console.log(event); event.preventDefault(); var message = $('#id_message'); send('{{ request.user.username }}', '{{ receiver.username }}', message.val()); message.val(''); }) }) more js function send(sender, receiver, message) { $.post('/chat/api/messages/', '{"sender": "'+ sender +'", "receiver": "'+ receiver +'","message": "'+ message +'" }', function (data) { console.log(data); var box = text_box.replace('{sender}', "You"); box = box.replace('{message}', message); $('#board').append(box); scrolltoend(); }) } function receive() { $.get('/chat/api/messages/'+ sender_id + '/' + receiver_id, function (data) { console.log(data); if (data.length !== … -
django-models - a non-string type is stored into CharField
I am using Django 1.11 on Python 3, and MySQL 5.7. Suppose I have a model with a CharField, like so: class ModelA(models.Model): ID = models.AutoField(primary_key=True) a = models.CharField() And in the shell, I tried doing this: >>> instance = ModelA(a={'1' : 1}) >>> instance which gives me a TypeError: __str__ returned non-string (type dict) But when I do this: >>> instance.save() I don't get any error. If I try: >>> instance.a {'1': 1} But when I try: >>> ModelA.objects.get(ID=<the ID of the above instance>).a "{'1': 1}" Which means that it got stored in the database table as a string. My question is why does this implicit conversion happen, and why doesn't save() raise an error like __str__() did? Thanks for your help! -
AttributeError: 'module' object has no attribute 'DjangoFilterBackend'
I am using django-filter but i get following error that 'module' object has no attribute 'DjangoFilterBackend' I am sending my code below: Model.py from django.db import models # Create your models here. class searchModel(models.Model): email = models.CharField(max_length=25) password = models.CharField(max_length=10) image = models.ImageField(upload_to='Image/') def __str__(self): return "%s" % self.email serializers.py from rest_framework import serializers from .models import searchModel class searchserializer(serializers.ModelSerializer): image = serializers.ImageField(max_length=None, use_url=True) class Meta: model=searchModel fields=('email','password','image') Views.py from rest_framework import viewsets from .models import searchModel from .serializers import searchserializer #from django_filters.rest_framework import filters from rest_framework import filters class searchView(viewsets.ModelViewSet): queryset=searchModel.objects.all() serializer_class = searchserializer filter_backends = (filters.DjangoFilterBackend,filters.OrderingFilter,) filter_fields = ('email') ordering = ('email') -
TypeError: Object of type 'int32' is not JSON serializable
I have to select those symptoms which is in the dictionary with the symptoms already posted.It works fine.But for some symptoms typeError is showing in command prompt and also all are getting printed in command prompt but not in html page. Here is my code views.py def predict(request): sym=request.POST.getlist('symptoms[]') sym=list(map(int,sym)) diseaseArray=[] diseaseArray=np.array(diseaseArray,dtype=int) dictArray=[] for dicti in dictionary: if (set(sym)<= set(dicti['symptoms']) and len(sym)!= 0) or [x for x in sym if x in dicti['primary']]: diseaseArray=np.append(diseaseArray,dicti['primary']) diseaseArray=np.append(diseaseArray,dicti['symptoms']) diseaseArray=list(set(diseaseArray)) print(diseaseArray) for i in diseaseArray: if i not in sym: dict={'id':i} dictArray.append(dict) print(dictArray) for j in dictArray: symptoms=Symptom.objects.get(syd=j['id']) j['name']=symptoms.symptoms print(j['name']) print(len(dictArray)) return JsonResponse(dictArray,safe=False) template $('.js-example-basic-multiple').change(function(){ $('#suggestion-list').html(''); $('#suggestion').removeClass('invisible'); $.ajax({ url:"/predict", method:"post", data:{ symptoms: $('.js-example-basic-multiple').val(), }, success: function(data){ data.forEach(function(disease){ console.log(disease.name) $('#suggestion-list').append('<li>'+disease.name+'<li>') $('#suggestion-list').removeClass('invisible'); }); } }); -
How to Limit the number of suggestions from Summernote Mentions, w/ Django Rest Framework?
I am currently working on a project using Django, Django Rest Framework and Summernote. At the moment I am customizing Summernote WYSIWYG editor in order to offer my users the opportunity to mention other users. I am passing the user list to Summernote via Django Rest Framework. My Code at the moment looks like this: Grabbing the Users: //with this function I grab the user list from and endpoint that I set w/ Django Rest Framework function userList(){ console.log("fetching user list...") user_list = [] $.ajax({ url: '/api/users/user_list/', method: "GET", success: function(data){ for (i in data) { user_list(data[i].username); } } }) return user_list Django Rest Framework View Function: class UserListAPIView(generics.ListAPIView): serializer_class = UserDisplaySerializers queryset = User.objects.all() Summernote: hint: { mentions: userListt(), match: /\B@(\w*)$/, search: function (keyword, callback) { callback($.grep(this.mentions, function (item) { return item.indexOf(keyword) == 0; })); }, content: function (item) { return '@' + item; }, }, The Code Works. I Can get the user list and offer autocompletion features to my users. But I am really afraid that as the website grows, giving the whole list of users could result in some excessively slow quering of the database, slowing down the whole website. How could I fix this? How … -
how to add template css js and bootstrap in django
I want to add bootstrap template in my django app. I have downloaded it and kept in my static folder, then added its path in setting.py file as: STATIC_URL = '/static/' index.html of template is: {% load staticfiles %} <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Business Casual - Start Bootstrap Theme</title> <!-- Bootstrap Core CSS --> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> <!-- Custom CSS --> <link href="{% static 'css/business-casual.css' %}" rel="stylesheet"> <!-- Fonts --> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Josefin+Slab:100,300,400,600,700,100italic,300italic,400italic,600italic,700italic" rel="stylesheet" type="text/css"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> <div class="brand">Business Casual</div> <div class="address-bar">3481 Melrose Place | Beverly Hills, CA 90210 ... but doesn't working ,please help me -
Auto update cache with React Apollo and Django Graphene
I have a Graphene Django backend with a query and mutation looking something like from models.example import Example as ExampleModel class Example(DjangoObjectType): class Meta: model = ExampleModel class Query(ObjectType): example = graphene.Field(Example, id=graphene.ID()) resolve_example(self, info, if): return ExampleModel.objects.get(id=id) class ExampleInput(InputObjectType): id: graphene.ID() name: graphene.String() class UpdateExample(Mutation): Output = Example class Arguments: id: graphene.ID(required=True) example_input: ExampleInput(required=True) def mutate(self, info, id, example_input): example = ExampleModel.objects.get(id=id) if 'name' in example_input: example.name = example_input.name example.save() return example On the frontend I use React Apollo and the mutation is performed with the following HOC: import { omit } from 'lodash'; const GET_EXAMPLE = gql` query Example($id: ID!) { example(id: $id) { id name } } `; const UPDATE_EXAMPLE = gql` mutation UpdateExample($botId: ID!, $exampleInput: ExampleInput!) { updateExample(id: $id, exampleInput: $exampleInput) { id name } } `; export default graphql(UPDATE_EXAMPLE, { props: ({ mutate, ownProps: { id }) => ({ onSubmit: values => mutate({ variables { id, botInput: omit(values, ['__typename'] }, }), }), })(Component) Note that I have to remove the field __typename from the exampleInput because the server doesn't know about this field (cf this question). This works fine except for one thing: Apollo's local cache state isn't automatically updated. I know I can achieve … -
CKEditor Image Upload Error : DoesNotExist at /ckeditor/browse/
I have a django blog project. Everything was working fine, however now in both my local and production servers I can't upload new images to my posts. When I click on "browse server" for images, I get : DoesNotExist at /ckeditor/browse/ Category matching query does not exist. From the traceback below, it looks like it's trying to load a view getCategory which isn't even specified in the ckeditor part of my urls.py. Traceback : Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ckeditor/browse/?CKEditor=id_body&CKEditorFuncNum=1&langCode=en Django Version: 1.11.6 Python Version: 3.6.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'posts', 'social_django', 'mptt', 'ckeditor', 'ckeditor_uploader', 'imagekit', 'django_archive'] Installed 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', 'social_django.middleware.SocialAuthExceptionMiddleware'] Traceback: File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/davidmellor/code/nomadpad/posts/views.py" in getCategory 45. childCat = childCats.get(catSlug=catSlug) File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/db/models/query.py" in get 380. self.model._meta.object_name Exception Type: DoesNotExist at /ckeditor/browse/ Exception Value: Category matching query does not exist. This was all working perfectly until recently when I added django-mptt, but I didn't change anything to do with CKEditor. My urls.py from django.conf.urls import url, include from django.contrib import admin from django.contrib.auth … -
in django drf can a authenticated user with token access other users data?
in django drf can a authenticated user with token access other users data? I know it shouldn't but in my application its not happening. for testing I was using the token in postman but I was surprised when I see by using one users token I can access any other user data by changing PK in url. when I researched this on internet I couldn't find any definite answer. may be I was using the token authentication method wrongfully... but my main question is: If I have one users token then by just changing pk in url, should I be able to get other users data? if so how to avoid that? (Note: I am currently NOT using HTTPS. ) (also this is a conceptual question so after getting answer of this I may need to ask another question regarding error in my code; that I will. but please provide answer to this) -
import channel from django-channels
what is the right import to use something like this in views.py: message = {"message":msg} Channel('chat').send(message, immediately=True) from channels import Channel -> doesn't work I find the code here : https://github.com/django/channels/issues/59 -
how to find if session has expired in django
I have to code this scenario: Some user comes to fill a form and while user is at it, session expires; User tries to submit form, as session has expired it will take him to login page after which he is rediredted to form page with a prefilled form with data he filled previously. my propsed solution: on form submit, check if user session is expired with an ajax call, if yes, drop a cookie with values of filled form, user comes back to same form, prefill the form from cookie value. how far I got: not much; I used ajax call to check session expiry with a backend call to this function: def check_valid_session(request): session_expiry_date = request.session.get_expiry_date() now = datetime.now() seconds_left = (session_expiry_date - now).total_seconds() if seconds_left <= 0: return JsonResponse({'session_expired': True, 'seconds_left': seconds_left }) else: return JsonResponse({'session_expired':False, 'seconds_left': seconds_left}) in my settings I have: SESSION_COOKIE_NAME = "sso-sessionid" SESSION_COOKIE_HTTPONLY = False SESSION_COOKIE_AGE = 10 SESSION_COOKIE_DOMAIN = '.mydomain.com' SESSION_COOKIE_SECURE = True SESSION_EXPIRE_AT_BROWSER_CLOSE = True but in response, I always get seconds_left as something close to 9.999. and session_expiry_time keeps increasing itself by 10 seconds each time i hit submit and call the backend code above. How to get correct session … -
Django exception: Improperly configured SECRET_KEY
While executing migrate command 'python manage.py migrate' on mac os, I get the following error Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/jeetpatel/final-tribute/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/jeetpatel/final-tribute/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/jeetpatel/final-tribute/venv/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/jeetpatel/final-tribute/venv/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 61, in execute super(Command, self).execute(*args, **options) File "/Users/jeetpatel/final-tribute/venv/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/Users/jeetpatel/final-tribute/venv/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 72, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "/Users/jeetpatel/final-tribute/venv/lib/python2.7/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/Users/jeetpatel/final-tribute/venv/lib/python2.7/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/Users/jeetpatel/final-tribute/venv/lib/python2.7/site-packages/django/conf/__init__.py", line 129, in __init__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. I have mentioned a SECRET_KEY = 'fooo' in my base.py file base.py import os import smtplib BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) SITE_NAME = 'final-tribute' # Allow all host headers ALLOWED_HOSTS = [] # AUTH_PROFILE_MODULE = 'profiles.Profile' LOGIN_REDIRECT_URL = '/profiles/' LOGIN_URL = '/' ADMINS = ( ('Ab Rao', 'abc@abc.in') ) MANAGERS = ADMINS # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # Application definition DJANGO_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.postgres', # 'social.apps.django_app.default', ) THIRD_PARTY_APPS = ( 'rest_framework', 'rest_framework.authtoken', … -
django delimiter not working while reading csv file
I am working nowadays a lot with csv file and got another problem. If I do as per below, delimiter is not working. with open(path, encoding='utf-8') as f: data = csv.reader(f, delimiter='|') I searched and also tried below function: csv.register_dialect('options', delimiter='|') with open(path, encoding='utf-8') as f: data = csv.reader(f, dialect='options') It's not working as well. The main issue that I am having actually I am importing from a csv file a long text but only single colomn but if there is a comma in the text I loose the rest of the text after the comma.That's what I need to prevent. But it's not working. Should I use delimiter inside the for loop while writing ? -
Ajax returns error "Failed to load resource: net::ERR_EMPTY_RESPONSE" when response does not arrive within 1 min
I am facing very strange issue.I have written django project in which I am sending ajax request.If response comes before 1 min then ajax is working fine but if response does not come within 1 min then ajax returns error "Failed to load resource: net::ERR_EMPTY_RESPONSE". My ajax code is as below: $.ajax({ url: '/index/', type: 'POST', timeout: 60000000, contentType: 'application/json; charset=utf-8', data: JSON.stringify(finalJson), dataType: 'text', success: function(response){ // Get response from django server // do your code here off(); console.log("Got response"); console.log(response); if(response.includes("documents will be deleted")) { console.log("response!!!"); if (confirm(response + '.Continue' + '?')) { document.getElementById("overlay").style.display = "block"; document.getElementById("loader").style.display = "block"; console.log("yes"); $.ajax({ url: '/index/', type: 'POST', contentType: 'application/json; charset=utf-8', data: JSON.stringify({"logpaths":jsonobj,"emails":mailobj,"cu_hostname":cu_host,"user_tag":us_tag,"delete_s_date":delete_s_date,"delete_e_date":delete_e_date,"delete_docs":true}), dataType: 'text', success: function(response) { off(); alert(response); } }); } } else { alert(response); } //document.getElementById("response_div").innerHTML = response; } }); Please help me. -
Starting chrome in from batch file
I have django app that I am able to start from batch file.I want to start google chrome with address http://localhost:8000/.I tried with different solutions available but still the chrome is not starting. Server gets activated My bat script @echo off cmd /k "cd /d C:\Users\user1\Desktop\Website\code\myenvironment\Scripts & activate & cd /d C:\Users\user1\Desktop\Website\code\myapp & python manage.py runserver" start C:\"Program Files (x86)"\Google\Chrome\Application\chrome.exe "http://localhost:8000/" -
how to install mysql-python on windows 10
I need to install mysqldb for python on windows 10, I tried the below way but I got same error: Setup script exited with error: command 'cl.exe' failed: No such file or directory pip install mysqlclinet, easy_instal mysql-python Please help! error: command 'cl.exe' failed: No such file or directory E:\Python\Django-PyCharm\DjangoPyCharmWeb>easy_install mysqlclient Searching for mysqlclient Reading https://pypi.python.org/simple/mysqlclient/ Downloading https://pypi.python.org/packages/6f/86/bad31f1c1bb0cc99e88ca2adb7cb5c71f7a6540c1bb001480513de76a931/mysqlclient-1.3.1 2.tar.gz#md5=dbf1716e2c01966afec0198d75ce7e69 Best match: mysqlclient 1.3.12 Processing mysqlclient-1.3.12.tar.gz Writing C:\Users\Hoshmand\AppData\Local\Temp\easy_install-4ln2fjka\mysqlclient-1.3.12\setup.cfg Running mysqlclient-1.3.12\setup.py -q bdist_egg --dist-dir C:\Users\me\AppData\Local\Temp\easy_install-4ln2fjka\mysqlclien t-1.3.12\egg-dist-tmp-aeu8iq_w error: Setup script exited with error: command 'cl.exe' failed: No such file or directory E:\Python\Django-PyCharm\DjangoPyCharmWeb> C:\Users\me\Downloads\mysqlclient-1.3.12>python setup.py build running build running build_py creating build creating build\lib.win32-3.6 copying _mysql_exceptions.py -> build\lib.win32-3.6 creating build\lib.win32-3.6\MySQLdb copying MySQLdb\__init__.py -> build\lib.win32-3.6\MySQLdb copying MySQLdb\compat.py -> build\lib.win32-3.6\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.6\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.6\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.6\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.6\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.6\MySQLdb creating build\lib.win32-3.6\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win32-3.6\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.6\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.6\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.6\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.6\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.6\MySQLdb\constants copying MySQLdb\constants\REFRESH.py -> build\lib.win32-3.6\MySQLdb\constants running build_ext building '_mysql' extension creating build\temp.win32-3.6 creating build\temp.win32-3.6\Release cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Dversion_info=(1,3,12,'final',0) -D__version__=1.3.12 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.1\include" -IC:\Python\Python36\include -IC:\Python\Python36\include /Tc_mysql.c /Fobuild\temp.win32-3.6\Release\_mysql.obj /Zl error: command 'cl.exe' failed: No such … -
Django form not calling custom validator
I'm using Django 2.0. This is my forms.py: class PostcodeForm(forms.Form): postcode = forms.CharField(required=True, widget=forms.TextInput( attrs={ 'placeholder': "enter a postcode", } )) def clean_postcode(self): postcode = self.clean_data.get('postcode', '') print('clean_postcode', postcode) if postcode != 'something': raise forms.ValidationError(_("Please enter a valid postcode"), code='invalid') return data And my views.py: def index(request): form = PostcodeForm() context = { 'form': form } return render(request, 'index.html', context) And my index.html: <form class="form-inline" id="lookup_postcode" action="{% url 'lookup_postcode' %}" method="get"> {% csrf_token %} {{ form.non_field_errors }} {{ form.postcode.errors }} {{ form.postcode }} <button type="submit">Submit</button> </form> But when I type in any value other than 'something', the form still submits. I also don't see any print statements in the console, so it looks as though the validator just isn't being run. What am I doing wrong? -
How to determine image resolution uploaded on amazon s3 bucket
I have an image uploaded on amazon s3 bucket. I want to know its resolution in my Django api. -
Django render to new template is not working
I am trying to render new template 'quesHome.html' via jquery ajax call. But page is not redirected to quesHome page. Also i am not getting any errors. I am a beginner to Django please correct me if i am wrong. Below is my view: def getSearchQuesions(req): print("getSearchQuesions") topic = Topic.objects.all() form = CreateQuestion() ques_id = req.GET['ques_id'] question = Question.objects.filter(pk=ques_id) return render(req,'quesHome.html',{'topic':topic ,'question':question,'form':form}) Below is my js code: function getFilteredQuestions(ques_id) { $.ajax({ type: 'GET', url: '/getSearchQuesions/', data: { "ques_id": ques_id }, success: function () { console.log("success"); } }); } Below is my urls.py: url(r'^getSearchQuesions/$', for_views.getSearchQuesions, name='getSearchQuesions'), Below is my quesHome.html: {%extends 'master_page.html'%} {% block quesHome %} <div class="container" id="cont"> <div class="row topicDiv"> <input type="hidden" value="{%csrf_token%}" id="hid_csrf" /> {% for t in topic %} <h4 id="{{t.pk}}" class="topCls"><span class="badge badge-Info">{{t.name}}</span></h4> &nbsp; {% endfor %} </div> <br /> <div class="" id=""> {% for q in question %} <div id="feed"> <div id=""> <h5><span class="">{{q.name}}</span></h5> </div> <div class=""> <h6><span class="">{{q.answer}}</span></h6> </div> </div> <br /> {% endfor %} </div> </div> {% endblock %}