Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Incorrect datetime format in Django
I have a django project in which one of my models has a dateField named start_time. In my views.py I created a DetailView, and try to retrieve the timestamp like: s = self.object.start_time.strftime('%d-%b-%Y') On my Raspberry Pi, it gives the expected result. print(s) 22-Nov-2018 However on my Ubuntu 18 computer it gives: print(s) 22-nov.-2018 How can I get my Ubuntu machine to give the same (expected) result as the Raspberry Pi? They both run Django 2.1.3. -
customizing serialized object in django
i have a response for an api, "mailinglist": [ { "id": 690, "name": "Donotdelete", "count": "3", "mailing_list": 109, "person": [ { "id": 939, "first_name": "Aladdin", "last_name": "Abdul", "email": "aladdin@sharklasers.com", "mailinglist_id": 109 } ] }, { "id": 691, "name": "Donotdelete", "count": "3", "mailing_list": 109, "person": [ { "id": 938, "first_name": "smitha", "last_name": "sraj", "email": "smithasraj.kp@gmail.com", "mailinglist_id": 109 } ] } ] using nested serializer method.but i have to change this response to "mailinglist": [ { "id": 690, "name": "Donotdelete", "count": "3", "mailing_list": 109, "person": [ { "id": 938, "first_name": "smitha", "last_name": "sraj", "email": "smithasraj.kp@gmail.com", "mailinglist_id": 109 } ] } ] the common fields like name count mailing list should be outside the array.Is there any option to do this? Can we iterate the serializer data object and can be customize it? -
Django testing kwarg input to form.save()
In Django testing, form.save gets a kwarg. How can I test this? def save(self, **kwargs): user = super(UserCreationForm, self).save(commit=False) user.email = kwargs.pop('email') user.set_password(self.cleaned_data['password1']) user.save() return user -
Passing value from one field to other field in django form
I have two django models ModelA and ModelB. class ModelA(models.Model): fieldA1 = models.CharField() fieldA2 = models.CharField() fieldA3 = models.ManyToManyField('ModelC') class ModelB(models.Model): key = models.CharField() value = models.CharField() and a django form: class MyForm(forms.ModelForm): A_fields =[field.name for field in ModelA._meta.get_fields()] key= forms.ChoiceField(label='Key',choices = [(str(l),str(l)) for l in A_fields]) value= forms.MultipleChoiceField(label='Value',choices = 'Need Help here'). 'I have used MultipleChoiceField because if key == fieldA3 then there could be multiple choices for this field.' class Meta: model = ModelB fields = ('key', 'value') Since choices for 'key' field are the field names of ModelA. I want that based on the key selected (which will be some field name of ModelA), choices shown for the 'value' field in MyForm must be all the values stored in that particular field of ModelA. I know how to fetch values stored in a particular field of ModelA.I have to use the following command. field_values = ModelA.objects.values('Field for which i want values') How do i approach this problem? Thanks in advance. -
Django Rest Framework validate method not working
This is my first task that I'm doing in Rest Framework.I referred a video tutorial to do this and it's weird why my validate method in serializer not working even if I totally copied the code from the video. Below is my view function: class UserLoginAPIView(APIView): permission_classes = [AllowAny] serializer_class = UserLoginSerializer def post(self, request, *args, **kwargs): data = request.data serializer = UserLoginSerializer(data=data) if serializer.is_valid(raise_exception=True): new_data = serializer.data return Response(new_data, status=HTTP_200_OK) //I'm getting this response return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) and my serializer: def validate(self, data): print("***************validating*******************") //This line is not being printed # user_obj = None email = data.get("email", None) username = data.get("username", None) password = data["password"] if not email and not username: raise ValidationError("A username or email is required to login.") user = User.objects.filter( Q(email=email) | Q(username=username) ).distinct() user = user.exclude(email__isnull=True).exclude(email__iexact='') print(user, "-------------*********************") if user.exists() and user.count() == 1: user_obj = user.first() else: raise ValidationError("This username/email is not valid.") if user_obj: if not user_obj.check_password(password): print("wrong pwd", "**************************************") raise ValidationError("Incorrect credentials! Please Try again!") data["token"] = "SOME RANDOM TOKEN" return data As the first line in validate method not being executed, how am I getting the response(200_OK)? Please help me with this.. -
Session are not maintained for new request in django when using iframe
I am creating a chatbot. for that i am maintaining session to create chat flow. and its working properly when running the server. But when i am using iframe to give link of the file of chat window then session are not maintained. for every new request older session got destroyed. this is my code for the chat flow def extract_data(request, input_data): from chat import validations if 'city' not in request.session: response_data = {'extra': {}, 'data': {}} response_data['extra']['statement'] = 'Select Car Model which you like to rent?' response_data['extra']['type'] = 'carmodel' response_data['data'] = Cars.city_check(request,response_data, input_data) elif 'veh_name' not in request.session: response_data = Cars.veh_name_check(request, input_data) elif 'days' not in request.session: response_data = validations.days_check(request, input_data) elif 'phone' not in request.session: response_data = validations.phone_check(request, input_data) elif 'email' not in request.session: response_data = validations.mail_check(request, input_data) elif 'name' not in request.session: response_data = validations.name_check(request, input_data, 'Car') return response_data def city_check(request, response_data, input_data): import pdb;pdb.set_trace() if len(input_data.split()) == 6: request.session['city'] = input_data.split()[4]+' '+input_data.split()[5] else:request.session['city'] = input_data.split()[4] request.session['flag'] = 0 city_list = dict(city=list(models.CityForCars.objects.filter(CityForCars=request.session['city']).values_list().values().order_by('id'))) city = city_list['city'][0]['id'] car_model_data = dict(car_model=list(models.CarModel.objects.filter(City_id=city).values_list().values().order_by('id'))) response_data = car_model_data return response_data @staticmethod def veh_name_check(request, input_data): response_data = {'extra': {}, 'data': {}} response_data['extra']['statement'] = 'For how many days are you looking to rent a vehicle? (Type … -
Request for OAuth 2 bearer token from django
I am working in Django. I need to access a external API to get access token. I can connect from Postman (See the image). I have given following information Access_Token_url : http://{doamin-name}/auth/token Client_ID: {client_id} Client_secret: {client_secret} Scope : {sapmle-scope} How can I request to get the access token from Django? I tried oauth2_handler = OAuth2(client_id = client_id, client_secret = client_secret, site=token_url, redirect_uri ='http://localhost:444/api/v1/taitodata/', token_url=token_url, scope_sep=scopes) code = request.get("code") parameters = oauth2_handler.get_token(code='code') return Response(response) -
Is there a modification of django framework in the last 24 jours?
We experienced strange behaviour. Especially under chrome, some items are missing. Anyone ? -
Django ForeignKey filtering whole object or object_id
I know that object_id is more efficient than object.id but is this rule working for ForeignKey filtering ? Is Model.objects.filter(author_id=author_obj.id) or Model.objects.filter(author_id=author_id) more efficient than Model.objects.filter(author=author_obj) -
mysql.h file could not be found python
I am trying to do pip install mysqlclient in my django virtualenv but getting the same error over and again. I have tried almost all Stack Overflow questions solutions related to this but none worked. What I have in my system are: Microsoft Visual C++ Build Tool 14.0.x Microsoft Visual C++ Redistributable 14.0.x MySQL connector for C++, ODBC, Python Microsoft Visual Studio Build Took 2017 Visual Studio Community 2017 as attached in images... As some answers asked to install mysql community server and some to install connector and some to install visual c++ but none seems to work for me! I even tried uninstalling and reinstalling above listed applications and everything worked fine except pip install mysqlclient(error given below) Error (venv) PS E:\ayasya\hasslefreeaccounts> pip install mysqlclient Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/ec/fd/83329b9d3e14f7344d1cb31f128e6dbba70c5975c9e57896815dbb1988ad/mysqlclient-1.3.13.tar.gz Building wheels for collected packages: mysqlclient Running setup.py bdist_wheel for mysqlclient ... error Complete output from command e:\ayasya\hasslefreeaccounts\venv\scripts\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\Gahlawat\\AppData\\Local\\Temp\\pip-install-cqvytcbo\\mysqlclient\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d C:\Users\Gahlawat\AppData\Local\Temp\pip-wheel-4ih_hetb --python-tag cp37: running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.7 copying _mysql_exceptions.py -> build\lib.win-amd64-3.7 creating build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\__init__.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\compat.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win-amd64-3.7\MySQLdb … -
Django CMS - How to add multiple (zero or more) links on a model in admin
I'm fairly new to Django CMS, and I've inherited a website with these specs: Django 1.10.8 Django CMS 3.4.5 Python 2.7 Unfortunately, there is no option to upgrade at the moment. Also, please pardon if I the terminology wrong - I'd appreciate corrections. I have a Staff app with models for Staff and StaffTranslation (etc), and I have a task to update the admin to allow adding one or more links to each StaffTranslation. However, I'm having trouble identifying the best way to do this, and what components to use. I have identified the Django CMS Link plugin, which could be a possibility, but I can't find instructions on how to add multiple instances to a model or admin page. Also, the latest version requires Django 1.11, at minimum. I have also found the PageSmartLinkField - which seems smart - but I haven't been able to discover how to integrate it with data for the StaffTranslation object or how to display it on the admin page for that object. I would appreciate any suggestions as to how to structure this - it seems like a simple enough task, I think I am just missing a piece or two, of the … -
Django message with breakline and redirect url inside
I would like to improve my django message with some things : add a breakline in the text and add an url using django reverse url. This is my message : messages.error(self.request, _( f"The link to download the document has expired. Please request it again in our catalogue : {redirect to freepub-home}" I would like to separate my message by adding a new line after the . in order to get something like this : messages.error(self.request, _( f"The link to download the document has expired. Please request it again in our catalogue : {redirect to freepub-home}" Then, how I can set django redirection in my message thanks to reverse url to "freepub-home" ? Thank you by advance ! -
Difference between JWT and Oauth
I don't know if I get it right or not, please guide me with this. I figured out that we have two kinds of token authenthication one using JWT and the other is oAuth. First, I don't know what is the difference between this two Second, As we can see this two have two different output, JWT shows only Token and OAuth shows "access_token": "<your_access_token>", "token_type": "Bearer", "expires_in": 36000, "refresh_token": "<your_refresh_token>", "scope": "read write groups" why this two outputs are different. Third, why in JWT refresh token does not come with token and we should define another URL for it.and as I figured out the refresh token in jwt is different with the refresh token in OAuth. Everything about this things is confusing for me and I couldn't find my solution on the internet -
How to use Detect Intent(Text) in Django Python?
Good day everyone, I am a student and I'm currently working my way in successfully creating a chatbot with Dialogflow and Django-python. Right now, I already created an agent in Dialogflow, already have a Django app, used ngork, and other necessary stuffs except for connecting Dialogflow to Django app's fulfillment/and calling APIs. I stumbled across this documentation https://github.com/googleapis/dialogflow-python-client-v2 and successfully did all the steps needed. In the last part of the documentation, it seems that what I finally need to do is use the dialogflow detect intent text , so I copied it and put it into my Django app(views.py). def detect_intent_texts(project_id, session_id, texts, language_code): """Returns the result of detect intent with texts as inputs. Using the same `session_id` between requests allows continuation of the conversation.""" import dialogflow_v2 as dialogflow session_client = dialogflow.SessionsClient() session = session_client.session_path(project_id, session_id) print('Session path: {}\n'.format(session)) for text in texts: text_input = dialogflow.types.TextInput( text=text, language_code=language_code) query_input = dialogflow.types.QueryInput(text=text_input) response = session_client.detect_intent( session=session, query_input=query_input) print('=' * 20) print('Query text: {}'.format(response.query_result.query_text)) print('Detected intent: {} (confidence: {})\n'.format( response.query_result.intent.display_name, response.query_result.intent_detection_confidence)) print('Fulfillment text: {}\n'.format( response.query_result.fulfillment_text)) Now, I don't know what to do next. Unfortunately, I don't know how to use it or how it exactly works as I am still new … -
File is not getting found by the js in Django
I am trying to use the example from the following: https://bl.ocks.org/anilnairxyz/a51393d7c51342abe8d4e3f4cbab7ae1 I have modified the example with simple tweaks to get it landed in the Django framework. Here is the template code: temp.html {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="{% static 'test/cschart.css' %}"> </head> <body> <div id="demobox"> <div id="csbox"> <div id="option"> <input id="oneM" name="1M" type="button" value="1M"/> <input id="threeM" name="3M" type="button" value="3M" /> <input id="sixM" name="6M" type="button" value="6M" /> <input id="oneY" name="1Y" type="button" value="1Y" /> <input id="twoY" name="2Y" type="button" value="2Y" /> <input id="fourY" name="4Y" type="button" value="4Y" /> </div> <div id="infobar"> <div id="infodate" class="infohead"></div> <div id="infoopen" class="infobox"></div> <div id="infohigh" class="infobox"></div> <div id="infolow" class="infobox"></div> <div id="infoclose" class="infobox"></div> </div> <div id="chart1"></div> </div> <!-- csbox --> </div> <!-- demobox --> <script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script> <script src="https://d3js.org/d3-queue.v3.min.js"></script> <script src="https://d3js.org/topojson.v1.min.js"></script> <script src="{% static 'test/cschart.js' %}"></script> <script src="{% static 'test/csbars.js' %}"></script> <script src="{% static 'test/csheader.js' %}"></script> <script src="{% static 'test/csdataprep.js' %}"></script> <script src="{% static 'test/csmain.js' %}"></script> </body> </html> views.py def temp(request): return render(request, 'tt/temp.html', {}) urls.py urlpatterns = [ path('tt/', views.show), path('pie/', views.pie), path('dd3/', views.testingD3), path('fera/', views.fera), path('line/', views.lined3), path('temp/', views.temp), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) I have kept the complete js and css in the static/test folder and have … -
Django: Pulling data from Quickbooks Online and Storing it into MySQL database
I recently have a Django project that requires me to pull data from Quickbooks Online and then storing it in MySQL database for later uses. Following a tutorial that I found in https://github.com/sidecars/python-quickbooks, I was able to get my access and refresh token using quickbooks-cli -p 8000 <Client ID> <Client Secret> 2 Here come a few questions I like to ask: Is there any implications setting http://localhost:8000 as one of my Redirect URLs in the Intuit Developer's Key section? What should I do with the access and refresh token? I think I need to continue from the "Accessing the API" section in https://github.com/sidecars/python-quickbooks but I have no idea which files to put the code mentioned in the documentation (I do not touch API in the past so some guidance is appreciated) I noticed there is a duration before the access and refresh token expires, so does it mean I have to change them every once in a while? Thanks in advance. -
Django schedule process to excecute every day at a certain time
I have a django app and I want to retrieve some data from remote location and do some processing every day 00.00 H. How to schedule this kind of process to run in the background. Thanks. -
Tablesorter not loading in Django
Tablesorter doesn’t work for my Django-based website. Clicking on the table header doesn’t do anything, and I didn’t see any error message either. I feel like something simple was missing… The JS plugins were invoked with: {% load static %} <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/jquery.tablesorter.js"></script> <table id="myTable" class="tablesorter"> <thead>…</thead> <tbody>…</tbody> … <script> $(document).ready(function(){ $('#myTable').tablesorter({sortList: [[0,0], [1,0]]}); } ); </script> The JS files are in a static folder with the following structure: myvenv mysite |---- db.sqlite3 |---- manage.py |---- blog |---- management |---- migrations |---- templates |---- templatetags |---- admin.py |---- models.py |---- urls.py |---- views.py |---- static |---- js |---- jquery.js |---- jquery.tablesorter.js |---- … |---- mysite -
Creating dynamic forms with Django
Apologies if this has been asked before, but I'm trying to build a dynamic form in Django where depending on a selection in a Dropdown, I plan to render a different set of fields on my form along with a different set of formsets. For e.g. Choosing Option A in the dropdown shows fields X,Y and Z while selecting Option B shows fields W and X. The number of options in the dropdown can be quite large, so I am hesitant to use jQuery to toggle the css for these. I was wondering if the ideal way would be to map the different options in the dropdown (any examples or references would be appreciated) to maybe some kind of model or db entry so that depending on the selection, I can render my form accordingly. I am also not using React right now (I'm not that familiar with the latest ui frameworks), but happy to switch if any of the newer frameworks are more appropriate for this exercise. Thanks! -
Django CreateView not able to create model object
I am using Django CreateView on model object. The form gets rendered but on submitting Post button, nothing happens. In console I am receiving code 200 (Success) but object is not created. Also, I am using same HTML template and same code for Update View and it is working perfectly. Please help. class EventCreateView(LoginRequiredMixin, CreateView): model = Event fields = ['name', 'event_attendees'] def form_valid(self, form): form.instance.creator = self.request.user return super().form_valid(form) Model name = models.CharField(max_length=100) date = models.DateTimeField(default=timezone.now) location = models.CharField(max_length=16, choices=EVENT_VENUES, default='sec-1, noida') event_attendees = models.FileField(upload_to='documents/', default='') creator = models.ForeignKey(User, on_delete=models.CASCADE) form_rollout_time = models.DateTimeField(default=timezone.now) def __str__(self): return self.name def get_absolute_url(self): return reverse('event-detail', kwargs={'pk': self.pk}) Html template {% extends "events/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">New Event</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> </div> {% endblock content %} -
Find local python package registry and remove
I'm following the Django example to create my own reusable app. I created it following the Tutorials: Advanced tutorial: How to write reusable apps After installing it with pip, I found some error so I removed the directory manually rather than using pip uninstall. When I made some change and wanted to re-install I got an error: (venv) C:\source_code\django_test>pip install --user django-polls/dist/django-polls-0.1.tar.gz Processing c:\source_code\django_test\django-polls\dist\django-polls-0.1.tar.gz Building wheels for collected packages: django-polls Running setup.py bdist_wheel for django-polls ... done Stored in directory: C:\Users\admin\AppData\Local\pip\Cache\wheels\d0\f6\b0\5993fd9396ff005d6d1f1af971ea04814e5f6b9efcc8f9ea89 Successfully built django-polls Installing collected packages: django-polls Found existing installation: django-polls 0.1 Not uninstalling django-polls at c:\users\admin\appdata\roaming\python\python37\site-packages, outside environment c:\source_code\django_test\venv Can't uninstall 'django-polls'. No files were found to uninstall. Successfully installed django-polls-0.1 (venv) C:\source_code\django_test> Despite it shows "Successfully installed", there is no new directory created under my Django project. It seems that despite I removed the directory, Python recorded the installation somewhere (like registry) and detected the version conflict. I wonder where does Python store such information and how can I clean up the registry item so I can install it again just like I have never installed it before? By the way, I cannot uninstall it with pip either: (venv) C:\source_code\django_test>pip uninstall django-polls Not uninstalling django-polls at c:\users\admin\appdata\roaming\python\python37\site-packages, … -
Django realtime access on mobile devices
I am new to web backend. Currently I am using DjangoREST framework, it is working upon my expectations except it doesn't assist in real-time communication. I don't want to use firebase. In other words I wanna build my own backend like firebase not all features but at least real-time access on mobile devices. Recently I found Django Channels , as I have mentioned I haven't background of server-side developing so I don't know much about this. I just wanna ask is Django realtime access is possible on mobile devices through Django Channels ? Can I do something similer to DjangoREST GET, PUT, POST and DELETE in Django Channels ? -
how to correct zmq address in use error with django
I am trying to create a simple video streaming site with django. I am using cv2 for starting the webcam and zmq for transferring data from client to server. I found this link with which i wrote the networking part of the code. The code by itself works fine, but when I create a simple html file to start the live stream through the browser the code fails with this error message zmq.error.ZMQError: Address in use I guess this error arises because the ip django uses and the ip zmq tries to uses is the same. But I am not sure how to rectify this error. This is my code so far server.py def start_server(): context = zmq.Context() footage_socket = context.socket(zmq.SUB) print('socket created') footage_socket.bind('tcp://192.168.1.18:8000') print('binding complete') footage_socket.setsockopt_string(zmq.SUBSCRIBE, np.unicode('')) print('server ready') return footage_socket def recv_content(face_cascade_path): footage_socket=start_server() cascade = cv2.CascadeClassifier(face_cascade_path) while True: try: data = footage_socket.recv_string() img = base64.b64decode(data) npimg = np.fromstring(img, dtype=np.uint8) frame = cv2.imdecode(npimg, 1) print(frame) face = cascade.detectMultiScale(frame, scaleFactor=1.3, minNeighbors=3) for (x, y, w, h) in face: cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 0, 255), 2) if cv2.waitKey(1) & 0xFF == ord('q'): break cv2.imshow("Stream", frame) except KeyboardInterrupt: cv2.destroyAllWindows() break views.py from server import * def index(request): face_cascade_path = '../../../TRAINED … -
Django-rest-framework + Django-oauth-toolkit permission of scopes for different applications
Good afternoon! I am trying to build an API with DRF + Django-OAuth-Toolkit and having a problem with understanding if it is possible to restrict some scopes for different applications/users. If user makes token request with scopes defined, how can I filter scopes for him working with custom scopes and not read/write+? Or what is the best way to restrict some functionality for user? Thank you in advance. -
for loop in python to get nth element in a query set
Please can you check my python code below if it okay to do this for a queryset : gp_id= [0,1,2] for gp in gp_id: specail_list = Special.objects.filter(promotion=False, start__lte=date_instance, minimum_stay__lte=nights, object_id=room_filter.id, end__gte=date_instance, is_active=True, member_deal=False)[gp] print specail_list